text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
export const initEditor = (monacoEditor): void => {
monacoEditor.languages.register({ id: 'mermaid' });
const requirementDiagrams = [
'requirement',
'functionalRequirement',
'interfaceRequirement',
'performanceRequirement',
'physicalRequirement',
'designConstraint'
];
const keywords: {
[key: string]: {
typeKeywords: string[];
blockKeywords: string[];
keywords: string[];
};
} = {
flowchart: {
typeKeywords: ['flowchart', 'flowchart-v2', 'graph'],
blockKeywords: ['subgraph', 'end'],
keywords: [
'TB',
'TD',
'BT',
'RL',
'LR',
'click',
'call',
'href',
'_self',
'_blank',
'_parent',
'_top',
'linkStyle',
'style',
'classDef',
'class',
'direction',
'interpolate'
]
},
sequenceDiagram: {
typeKeywords: ['sequenceDiagram'],
blockKeywords: ['alt', 'par', 'and', 'loop', 'else', 'end', 'rect', 'opt', 'alt', 'rect'],
keywords: [
'participant',
'as',
'Note',
'note',
'right of',
'left of',
'over',
'activate',
'deactivate',
'autonumber',
'title',
'actor'
]
},
classDiagram: {
typeKeywords: ['classDiagram', 'classDiagram-v2'],
blockKeywords: ['class'],
keywords: [
'link',
'click',
'callback',
'call',
'href',
'cssClass',
'direction',
'TB',
'BT',
'RL',
'LR'
]
},
stateDiagram: {
typeKeywords: ['stateDiagram', 'stateDiagram-v2'],
blockKeywords: ['state', 'note', 'end'],
keywords: ['state', 'as', 'hide empty description', 'direction', 'TB', 'BT', 'RL', 'LR']
},
erDiagram: {
typeKeywords: ['erDiagram'],
blockKeywords: [],
keywords: []
},
journey: {
typeKeywords: ['journey'],
blockKeywords: ['section'],
keywords: ['title']
},
info: {
typeKeywords: ['info'],
blockKeywords: [],
keywords: ['showInfo']
},
gantt: {
typeKeywords: ['gantt'],
blockKeywords: [],
keywords: [
'title',
'dateFormat',
'axisFormat',
'todayMarker',
'section',
'excludes',
'inclusiveEndDates'
]
},
requirementDiagram: {
typeKeywords: ['requirement', 'requirementDiagram'],
blockKeywords: requirementDiagrams.concat('element'),
keywords: []
},
gitGraph: {
typeKeywords: ['gitGraph'],
blockKeywords: [],
keywords: ['commit', 'branch', 'merge', 'reset', 'checkout', 'LR', 'BT']
},
pie: {
typeKeywords: ['pie'],
blockKeywords: [],
keywords: ['title', 'showData']
}
};
// Register a tokens provider for the mermaid language
monacoEditor.languages.setMonarchTokensProvider('mermaid', {
...Object.entries(keywords)
.map((entry) =>
Object.fromEntries(
Object.entries(entry[1]).map((deepEntry) => [
entry[0] + deepEntry[0][0].toUpperCase() + deepEntry[0].slice(1),
deepEntry[1]
])
)
)
.reduce((overallKeywords, nextKeyword) => ({ ...overallKeywords, ...nextKeyword }), {}),
tokenizer: {
root: [
[/%%(?=.*%%$)/, { token: 'string', nextEmbedded: 'json' }],
[/%%$/, { token: 'string', nextEmbedded: '@pop' }],
[/^\s*gitGraph/m, 'typeKeyword', 'gitGraph'],
[/^\s*info/m, 'typeKeyword', 'info'],
[/^\s*pie/m, 'typeKeyword', 'pie'],
[/^\s*(flowchart|flowchart-v2|graph)/m, 'typeKeyword', 'flowchart'],
[/^\s*sequenceDiagram/, 'typeKeyword', 'sequenceDiagram'],
[/^\s*classDiagram(-v2)?/, 'typeKeyword', 'classDiagram'],
[/^\s*journey/, 'typeKeyword', 'journey'],
[/^\s*gantt/, 'typeKeyword', 'gantt'],
[/^\s*stateDiagram(-v2)?/, 'typeKeyword', 'stateDiagram'],
[/^\s*erDiagram/, 'typeKeyword', 'erDiagram'],
[/^\s*requirement(Diagram)?/, 'typeKeyword', 'requirementDiagram'],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment']
],
gitGraph: [
[/option(?=s)/, { token: 'typeKeyword', next: 'optionsGitGraph' }],
[/(^\s*branch|reset|merge|checkout)(.*$)/, ['keyword', 'variable']],
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@gitGraphBlockKeywords': 'typeKeyword',
'@gitGraphKeywords': 'keyword'
}
}
],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment'],
[/".*?"/, 'string'],
[/\^/, 'delimiter.bracket']
],
optionsGitGraph: [
[/s$/, { token: 'typeKeyword', nextEmbedded: 'json', matchOnlyAtLineStart: false }],
['end', { token: 'typeKeyword', next: '@pop', nextEmbedded: '@pop' }]
],
info: [
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@infoBlockKeywords': 'typeKeyword',
'@infoKeywords': 'keyword'
}
}
]
],
pie: [
[/(title)(.*$)/, ['keyword', 'string']],
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@pieBlockKeywords': 'typeKeyword',
'@pieKeywords': 'keyword'
}
}
],
[/".*?"/, 'string'],
[/\s*\d+/, 'number'],
[/:/, 'delimiter.bracket'],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment']
],
flowchart: [
[/[ox]?(--+|==+)[ox]/, 'transition'],
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@flowchartBlockKeywords': 'typeKeyword',
'@flowchartKeywords': 'keyword',
'@default': 'variable'
}
}
],
[/\|+.+?\|+/, 'string'],
[/\[+(\\.+?[\\/]|\/.+?[/\\])\]+/, 'string'],
[/[[>]+[^\]|[]+?\]+/, 'string'],
[/{+.+?}+/, 'string'],
[/\(+.+?\)+/, 'string'],
[/-\.+->?/, 'transition'],
[/(-[-.])([^->]+?)(-{3,}|-{2,}>|\.-+>)/, ['transition', 'string', 'transition']],
[/(==+)([^=]+?)(={3,}|={2,}>)/, ['transition', 'string', 'transition']],
[/<?(--+|==+)>|===+|---+/, 'transition'],
[/:::/, 'transition'],
[/[;&]/, 'delimiter.bracket'],
[/".*?"/, 'string'],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment']
],
sequenceDiagram: [
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@sequenceDiagramBlockKeywords': 'typeKeyword',
'@sequenceDiagramKeywords': 'keyword',
'@default': 'variable'
}
}
],
[/(--?>?>|--?[)x])[+-]?/, 'transition'],
[/(:)([^:\n]*?$)/, ['delimiter.bracket', 'string']],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment']
],
classDiagram: [
[/(?!class\s)([a-zA-Z]+)(\s+[a-zA-Z]+)/, ['type', 'variable']],
[/(\*|<\|?|o)?(--|\.\.)(\*|\|?>|o)?/, 'transition'],
[/^\s*class\s(?!.*\{)/, 'keyword'],
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@classDiagramBlockKeywords': 'typeKeyword',
'@classDiagramKeywords': 'keyword',
'@default': 'variable'
}
}
],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment'],
[/(<<)(.+?)(>>)/, ['delimiter.bracket', 'annotation', 'delimiter.bracket']],
[/".*?"/, 'string'],
[/:::/, 'transition'],
[/:|\+|-|#|~|\*\s*$|\$\s*$|\(|\)|{|}/, 'delimiter.bracket']
],
journey: [
[/(title)(.*)/, ['keyword', 'string']],
[/(section)(.*)/, ['typeKeyword', 'string']],
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@journeyBlockKeywords': 'typeKeyword',
'@journeyKeywords': 'keyword',
'@default': 'variable'
}
}
],
[
/(^\s*.+?)(:)(.*?)(:)(.*?)([,$])/,
[
'string',
'delimiter.bracket',
'number',
'delimiter.bracket',
'variable',
'delimiter.bracket'
]
],
[/,/, 'delimiter.bracket'],
[/(^\s*.+?)(:)([^:]*?)$/, ['string', 'delimiter.bracket', 'variable']],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment']
],
gantt: [
[/(title)(.*)/, ['keyword', 'string']],
[/(section)(.*)/, ['typeKeyword', 'string']],
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@ganttBlockKeywords': 'typeKeyword',
'@ganttKeywords': 'keyword'
}
}
],
[/(^\s*.*?)(:)/, ['string', 'delimiter.bracket']],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment'],
[/:/, 'delimiter.bracket']
],
stateDiagram: [
[/note[^:]*$/, { token: 'typeKeyword', next: 'stateDiagramNote' }],
['hide empty description', 'keyword'],
[/^\s*state\s(?!.*\{)/, 'keyword'],
[/(<<)(fork|join|choice)(>>)/, 'annotation'],
[/(\[\[)(fork|join|choice)(]])/, ['delimiter.bracket', 'annotation', 'delimiter.bracket']],
[
/[a-zA-Z][\w$]*/,
{
cases: {
'@stateDiagramBlockKeywords': 'typeKeyword',
'@stateDiagramKeywords': 'keyword',
'@default': 'variable'
}
}
],
[/".*?"/, 'string'],
[/(:)([^:\n]*?$)/, ['delimiter.bracket', 'string']],
[/{|}/, 'delimiter.bracket'],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment'],
[/-->/, 'transition'],
[/\[.*?]/, 'string']
],
stateDiagramNote: [
[/^\s*end note$/, { token: 'typeKeyword', next: '@pop' }],
[/.*/, 'string']
],
erDiagram: [
[/[}|][o|](--|\.\.)[o|][{|]/, 'transition'],
[/".*?"/, 'string'],
[/(:)(.*?$)/, ['delimiter.bracket', 'string']],
[/:|{|}/, 'delimiter.bracket'],
[/([a-zA-Z]+)(\s+[a-zA-Z]+)/, ['type', 'variable']],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment'],
[/[a-zA-Z_-][\w$]*/, 'variable']
],
requirementDiagram: [
[/->|<-|-/, 'transition'],
[/(\d+\.)*\d+/, 'number'],
[
/[a-zA-Z_-][\w$]*/,
{
cases: {
'@requirementDiagramBlockKeywords': 'typeKeyword',
'@default': 'variable'
}
}
],
[/:|{|}|\//, 'delimiter.bracket'],
[/%%[^$]([^%]*(?!%%$)%?)*$/, 'comment'],
[/".*?"/, 'string']
]
}
});
monacoEditor.editor.defineTheme('mermaid-dark', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'typeKeyword', foreground: '9650c8', fontStyle: 'bold' },
{ token: 'transition', foreground: '008800', fontStyle: 'bold' }
]
});
monacoEditor.editor.defineTheme('mermaid', {
base: 'vs',
inherit: true,
rules: [
{ token: 'typeKeyword', foreground: '9650c8', fontStyle: 'bold' },
{ token: 'keyword', foreground: '649696' },
{ token: 'custom-error', foreground: 'ff0000', fontStyle: 'bold' },
{ token: 'string', foreground: 'AA8500' },
{ token: 'transition', foreground: '008800', fontStyle: 'bold' },
{ token: 'delimiter.bracket', foreground: '000000', fontStyle: 'bold' },
{ token: 'annotation', foreground: '4b4b96' },
{ token: 'number', foreground: '4b4b96' },
{ token: 'comment', foreground: '888c89' },
{ token: 'variable', foreground: 'A22889' },
{ token: 'type', foreground: '2BDEA8' }
]
});
// Register a completion item provider for the mermaid language
monacoEditor.languages.registerCompletionItemProvider('mermaid', {
provideCompletionItems: () => {
const suggestions = [
{
label: 'loop',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['loop ${1:Loop text}', '\t$0', 'end'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Sequence Diagram Loops'
},
{
label: 'alt',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['alt ${1:Describing text}', '\t$0', 'else', '\t', 'end'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Alternative Path'
},
{
label: 'opt',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['opt ${1:Describing text}', '\t$0', 'end'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Optional Path'
},
{
label: 'par',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: [
'par ${1:[Action 1]}',
'\t$0',
'and ${2:[Action 2]}',
'\t',
'and ${3:[Action 3]}',
'\t',
'end'
].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Parallel Actions'
},
{
label: 'rect',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['rect ${1:rgb(0, 255, 0)}', '\t$0', 'end'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Background Color'
},
{
label: 'subgraph',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['subgraph ${1:title}', '\t$0', 'end'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Subgraph'
},
{
label: 'class',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['class ${1:className} {', '\t$0', '}'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Class'
},
{
label: 'state',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['state ${1:stateName} {', '\t$0', '}'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'State'
},
{
label: 'note',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['note ${1:right of State1}', '\t$0', 'end note'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'State'
},
{
label: 'section',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['section ${1:Go to work}', '\t$0'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'User-journey Section'
},
{
label: 'element',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['element ${1:test_entity} {', '\t$0', '}'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Requirement Diagram Element'
},
{
label: 'options',
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: ['options', '{', ' $0', '}', 'end'].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: 'Git Graph Options'
},
...requirementDiagrams.map((requirementDiagramType) => ({
label: requirementDiagramType,
kind: monacoEditor.languages.CompletionItemKind.Snippet,
insertText: [
requirementDiagramType + ' ${1:test_req} {',
'\tid: 1',
'\ttext: the test text.',
'\trisk: high',
'\tverifyMethod: test',
'}'
].join('\n'),
insertTextRules: monacoEditor.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: requirementDiagramType
.split(/(?=[A-Z])/)
.map((part) => part[0].toUpperCase() + part.slice(1))
.join(' ')
})),
...[
...new Set(
Object.values(keywords)
.map((diagramKeywords) =>
Object.entries(diagramKeywords)
.filter((keywordType) => keywordType[0] !== 'annotations')
.map((entry) => entry[1])
)
.flat(2)
)
].map((keyword) => ({
label: keyword,
kind: monacoEditor.languages.CompletionItemKind.Keyword,
insertText: keyword
}))
];
return { suggestions: suggestions };
}
});
monacoEditor.languages.setLanguageConfiguration('mermaid', {
autoClosingPairs: [
{
open: '(',
close: ')'
},
{
open: '{',
close: '}'
},
{
open: '[',
close: ']'
}
],
brackets: [
['(', ')'],
['{', '}'],
['[', ']']
]
});
}; | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
import {Readable} from 'stream';
interface Blob {}
declare class EBS extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: EBS.Types.ClientConfiguration)
config: Config & EBS.Types.ClientConfiguration;
/**
* Seals and completes the snapshot after all of the required blocks of data have been written to it. Completing the snapshot changes the status to completed. You cannot write new blocks to a snapshot after it has been completed.
*/
completeSnapshot(params: EBS.Types.CompleteSnapshotRequest, callback?: (err: AWSError, data: EBS.Types.CompleteSnapshotResponse) => void): Request<EBS.Types.CompleteSnapshotResponse, AWSError>;
/**
* Seals and completes the snapshot after all of the required blocks of data have been written to it. Completing the snapshot changes the status to completed. You cannot write new blocks to a snapshot after it has been completed.
*/
completeSnapshot(callback?: (err: AWSError, data: EBS.Types.CompleteSnapshotResponse) => void): Request<EBS.Types.CompleteSnapshotResponse, AWSError>;
/**
* Returns the data in a block in an Amazon Elastic Block Store snapshot.
*/
getSnapshotBlock(params: EBS.Types.GetSnapshotBlockRequest, callback?: (err: AWSError, data: EBS.Types.GetSnapshotBlockResponse) => void): Request<EBS.Types.GetSnapshotBlockResponse, AWSError>;
/**
* Returns the data in a block in an Amazon Elastic Block Store snapshot.
*/
getSnapshotBlock(callback?: (err: AWSError, data: EBS.Types.GetSnapshotBlockResponse) => void): Request<EBS.Types.GetSnapshotBlockResponse, AWSError>;
/**
* Returns information about the blocks that are different between two Amazon Elastic Block Store snapshots of the same volume/snapshot lineage.
*/
listChangedBlocks(params: EBS.Types.ListChangedBlocksRequest, callback?: (err: AWSError, data: EBS.Types.ListChangedBlocksResponse) => void): Request<EBS.Types.ListChangedBlocksResponse, AWSError>;
/**
* Returns information about the blocks that are different between two Amazon Elastic Block Store snapshots of the same volume/snapshot lineage.
*/
listChangedBlocks(callback?: (err: AWSError, data: EBS.Types.ListChangedBlocksResponse) => void): Request<EBS.Types.ListChangedBlocksResponse, AWSError>;
/**
* Returns information about the blocks in an Amazon Elastic Block Store snapshot.
*/
listSnapshotBlocks(params: EBS.Types.ListSnapshotBlocksRequest, callback?: (err: AWSError, data: EBS.Types.ListSnapshotBlocksResponse) => void): Request<EBS.Types.ListSnapshotBlocksResponse, AWSError>;
/**
* Returns information about the blocks in an Amazon Elastic Block Store snapshot.
*/
listSnapshotBlocks(callback?: (err: AWSError, data: EBS.Types.ListSnapshotBlocksResponse) => void): Request<EBS.Types.ListSnapshotBlocksResponse, AWSError>;
/**
* Writes a block of data to a snapshot. If the specified block contains data, the existing data is overwritten. The target snapshot must be in the pending state. Data written to a snapshot must be aligned with 512-KiB sectors.
*/
putSnapshotBlock(params: EBS.Types.PutSnapshotBlockRequest, callback?: (err: AWSError, data: EBS.Types.PutSnapshotBlockResponse) => void): Request<EBS.Types.PutSnapshotBlockResponse, AWSError>;
/**
* Writes a block of data to a snapshot. If the specified block contains data, the existing data is overwritten. The target snapshot must be in the pending state. Data written to a snapshot must be aligned with 512-KiB sectors.
*/
putSnapshotBlock(callback?: (err: AWSError, data: EBS.Types.PutSnapshotBlockResponse) => void): Request<EBS.Types.PutSnapshotBlockResponse, AWSError>;
/**
* Creates a new Amazon EBS snapshot. The new snapshot enters the pending state after the request completes. After creating the snapshot, use PutSnapshotBlock to write blocks of data to the snapshot.
*/
startSnapshot(params: EBS.Types.StartSnapshotRequest, callback?: (err: AWSError, data: EBS.Types.StartSnapshotResponse) => void): Request<EBS.Types.StartSnapshotResponse, AWSError>;
/**
* Creates a new Amazon EBS snapshot. The new snapshot enters the pending state after the request completes. After creating the snapshot, use PutSnapshotBlock to write blocks of data to the snapshot.
*/
startSnapshot(callback?: (err: AWSError, data: EBS.Types.StartSnapshotResponse) => void): Request<EBS.Types.StartSnapshotResponse, AWSError>;
}
declare namespace EBS {
export interface Block {
/**
* The block index.
*/
BlockIndex?: BlockIndex;
/**
* The block token for the block index.
*/
BlockToken?: BlockToken;
}
export type BlockData = Buffer|Uint8Array|Blob|string|Readable;
export type BlockIndex = number;
export type BlockSize = number;
export type BlockToken = string;
export type Blocks = Block[];
export type Boolean = boolean;
export interface ChangedBlock {
/**
* The block index.
*/
BlockIndex?: BlockIndex;
/**
* The block token for the block index of the FirstSnapshotId specified in the ListChangedBlocks operation. This value is absent if the first snapshot does not have the changed block that is on the second snapshot.
*/
FirstBlockToken?: BlockToken;
/**
* The block token for the block index of the SecondSnapshotId specified in the ListChangedBlocks operation.
*/
SecondBlockToken?: BlockToken;
}
export type ChangedBlocks = ChangedBlock[];
export type ChangedBlocksCount = number;
export type Checksum = string;
export type ChecksumAggregationMethod = "LINEAR"|string;
export type ChecksumAlgorithm = "SHA256"|string;
export interface CompleteSnapshotRequest {
/**
* The ID of the snapshot.
*/
SnapshotId: SnapshotId;
/**
* The number of blocks that were written to the snapshot.
*/
ChangedBlocksCount: ChangedBlocksCount;
/**
* An aggregated Base-64 SHA256 checksum based on the checksums of each written block. To generate the aggregated checksum using the linear aggregation method, arrange the checksums for each written block in ascending order of their block index, concatenate them to form a single string, and then generate the checksum on the entire string using the SHA256 algorithm.
*/
Checksum?: Checksum;
/**
* The algorithm used to generate the checksum. Currently, the only supported algorithm is SHA256.
*/
ChecksumAlgorithm?: ChecksumAlgorithm;
/**
* The aggregation method used to generate the checksum. Currently, the only supported aggregation method is LINEAR.
*/
ChecksumAggregationMethod?: ChecksumAggregationMethod;
}
export interface CompleteSnapshotResponse {
/**
* The status of the snapshot.
*/
Status?: Status;
}
export type DataLength = number;
export type Description = string;
export interface GetSnapshotBlockRequest {
/**
* The ID of the snapshot containing the block from which to get data.
*/
SnapshotId: SnapshotId;
/**
* The block index of the block from which to get data. Obtain the BlockIndex by running the ListChangedBlocks or ListSnapshotBlocks operations.
*/
BlockIndex: BlockIndex;
/**
* The block token of the block from which to get data. Obtain the BlockToken by running the ListChangedBlocks or ListSnapshotBlocks operations.
*/
BlockToken: BlockToken;
}
export interface GetSnapshotBlockResponse {
/**
* The size of the data in the block.
*/
DataLength?: DataLength;
/**
* The data content of the block.
*/
BlockData?: BlockData;
/**
* The checksum generated for the block, which is Base64 encoded.
*/
Checksum?: Checksum;
/**
* The algorithm used to generate the checksum for the block, such as SHA256.
*/
ChecksumAlgorithm?: ChecksumAlgorithm;
}
export type IdempotencyToken = string;
export type KmsKeyArn = string;
export interface ListChangedBlocksRequest {
/**
* The ID of the first snapshot to use for the comparison. The FirstSnapshotID parameter must be specified with a SecondSnapshotId parameter; otherwise, an error occurs.
*/
FirstSnapshotId?: SnapshotId;
/**
* The ID of the second snapshot to use for the comparison. The SecondSnapshotId parameter must be specified with a FirstSnapshotID parameter; otherwise, an error occurs.
*/
SecondSnapshotId: SnapshotId;
/**
* The token to request the next page of results.
*/
NextToken?: PageToken;
/**
* The number of results to return.
*/
MaxResults?: MaxResults;
/**
* The block index from which the comparison should start. The list in the response will start from this block index or the next valid block index in the snapshots.
*/
StartingBlockIndex?: BlockIndex;
}
export interface ListChangedBlocksResponse {
/**
* An array of objects containing information about the changed blocks.
*/
ChangedBlocks?: ChangedBlocks;
/**
* The time when the BlockToken expires.
*/
ExpiryTime?: TimeStamp;
/**
* The size of the volume in GB.
*/
VolumeSize?: VolumeSize;
/**
* The size of the blocks in the snapshot, in bytes.
*/
BlockSize?: BlockSize;
/**
* The token to use to retrieve the next page of results. This value is null when there are no more results to return.
*/
NextToken?: PageToken;
}
export interface ListSnapshotBlocksRequest {
/**
* The ID of the snapshot from which to get block indexes and block tokens.
*/
SnapshotId: SnapshotId;
/**
* The token to request the next page of results.
*/
NextToken?: PageToken;
/**
* The number of results to return.
*/
MaxResults?: MaxResults;
/**
* The block index from which the list should start. The list in the response will start from this block index or the next valid block index in the snapshot.
*/
StartingBlockIndex?: BlockIndex;
}
export interface ListSnapshotBlocksResponse {
/**
* An array of objects containing information about the blocks.
*/
Blocks?: Blocks;
/**
* The time when the BlockToken expires.
*/
ExpiryTime?: TimeStamp;
/**
* The size of the volume in GB.
*/
VolumeSize?: VolumeSize;
/**
* The size of the blocks in the snapshot, in bytes.
*/
BlockSize?: BlockSize;
/**
* The token to use to retrieve the next page of results. This value is null when there are no more results to return.
*/
NextToken?: PageToken;
}
export type MaxResults = number;
export type OwnerId = string;
export type PageToken = string;
export type Progress = number;
export interface PutSnapshotBlockRequest {
/**
* The ID of the snapshot.
*/
SnapshotId: SnapshotId;
/**
* The block index of the block in which to write the data. A block index is a logical index in units of 512 KiB blocks. To identify the block index, divide the logical offset of the data in the logical volume by the block size (logical offset of data/524288). The logical offset of the data must be 512 KiB aligned.
*/
BlockIndex: BlockIndex;
/**
* The data to write to the block. The block data is not signed as part of the Signature Version 4 signing process. As a result, you must generate and provide a Base64-encoded SHA256 checksum for the block data using the x-amz-Checksum header. Also, you must specify the checksum algorithm using the x-amz-Checksum-Algorithm header. The checksum that you provide is part of the Signature Version 4 signing process. It is validated against a checksum generated by Amazon EBS to ensure the validity and authenticity of the data. If the checksums do not correspond, the request fails. For more information, see Using checksums with the EBS direct APIs in the Amazon Elastic Compute Cloud User Guide.
*/
BlockData: BlockData;
/**
* The size of the data to write to the block, in bytes. Currently, the only supported size is 524288 bytes. Valid values: 524288
*/
DataLength: DataLength;
/**
* The progress of the write process, as a percentage.
*/
Progress?: Progress;
/**
* A Base64-encoded SHA256 checksum of the data. Only SHA256 checksums are supported.
*/
Checksum: Checksum;
/**
* The algorithm used to generate the checksum. Currently, the only supported algorithm is SHA256.
*/
ChecksumAlgorithm: ChecksumAlgorithm;
}
export interface PutSnapshotBlockResponse {
/**
* The SHA256 checksum generated for the block data by Amazon EBS.
*/
Checksum?: Checksum;
/**
* The algorithm used by Amazon EBS to generate the checksum.
*/
ChecksumAlgorithm?: ChecksumAlgorithm;
}
export type SnapshotId = string;
export interface StartSnapshotRequest {
/**
* The size of the volume, in GiB. The maximum size is 65536 GiB (64 TiB).
*/
VolumeSize: VolumeSize;
/**
* The ID of the parent snapshot. If there is no parent snapshot, or if you are creating the first snapshot for an on-premises volume, omit this parameter. If your account is enabled for encryption by default, you cannot use an unencrypted snapshot as a parent snapshot. You must first create an encrypted copy of the parent snapshot using CopySnapshot.
*/
ParentSnapshotId?: SnapshotId;
/**
* The tags to apply to the snapshot.
*/
Tags?: Tags;
/**
* A description for the snapshot.
*/
Description?: Description;
/**
* A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully. The subsequent retries with the same client token return the result from the original successful request and they have no additional effect. If you do not specify a client token, one is automatically generated by the Amazon Web Services SDK. For more information, see Idempotency for StartSnapshot API in the Amazon Elastic Compute Cloud User Guide.
*/
ClientToken?: IdempotencyToken;
/**
* Indicates whether to encrypt the snapshot. To create an encrypted snapshot, specify true. To create an unencrypted snapshot, omit this parameter. If you specify a value for ParentSnapshotId, omit this parameter. If you specify true, the snapshot is encrypted using the KMS key specified using the KmsKeyArn parameter. If no value is specified for KmsKeyArn, the default KMS key for your account is used. If no default KMS key has been specified for your account, the Amazon Web Services managed KMS key is used. To set a default KMS key for your account, use ModifyEbsDefaultKmsKeyId. If your account is enabled for encryption by default, you cannot set this parameter to false. In this case, you can omit this parameter. For more information, see Using encryption in the Amazon Elastic Compute Cloud User Guide.
*/
Encrypted?: Boolean;
/**
* The Amazon Resource Name (ARN) of the Key Management Service (KMS) key to be used to encrypt the snapshot. If you do not specify a KMS key, the default Amazon Web Services managed KMS key is used. If you specify a ParentSnapshotId, omit this parameter; the snapshot will be encrypted using the same KMS key that was used to encrypt the parent snapshot. If Encrypted is set to true, you must specify a KMS key ARN.
*/
KmsKeyArn?: KmsKeyArn;
/**
* The amount of time (in minutes) after which the snapshot is automatically cancelled if: No blocks are written to the snapshot. The snapshot is not completed after writing the last block of data. If no value is specified, the timeout defaults to 60 minutes.
*/
Timeout?: Timeout;
}
export interface StartSnapshotResponse {
/**
* The description of the snapshot.
*/
Description?: Description;
/**
* The ID of the snapshot.
*/
SnapshotId?: SnapshotId;
/**
* The Amazon Web Services account ID of the snapshot owner.
*/
OwnerId?: OwnerId;
/**
* The status of the snapshot.
*/
Status?: Status;
/**
* The timestamp when the snapshot was created.
*/
StartTime?: TimeStamp;
/**
* The size of the volume, in GiB.
*/
VolumeSize?: VolumeSize;
/**
* The size of the blocks in the snapshot, in bytes.
*/
BlockSize?: BlockSize;
/**
* The tags applied to the snapshot. You can specify up to 50 tags per snapshot. For more information, see Tagging your Amazon EC2 resources in the Amazon Elastic Compute Cloud User Guide.
*/
Tags?: Tags;
/**
* The ID of the parent snapshot.
*/
ParentSnapshotId?: SnapshotId;
/**
* The Amazon Resource Name (ARN) of the Key Management Service (KMS) key used to encrypt the snapshot.
*/
KmsKeyArn?: KmsKeyArn;
}
export type Status = "completed"|"pending"|"error"|string;
export interface Tag {
/**
* The key of the tag.
*/
Key?: TagKey;
/**
* The value of the tag.
*/
Value?: TagValue;
}
export type TagKey = string;
export type TagValue = string;
export type Tags = Tag[];
export type TimeStamp = Date;
export type Timeout = number;
export type VolumeSize = number;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2019-11-02"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the EBS client.
*/
export import Types = EBS;
}
export = EBS; | the_stack |
import assert = require('assert');
import trm = require('../../lib/taskRunner');
import path = require('path');
import os = require('os');
import fs = require('fs');
function setResponseFile(name: string) {
process.env['MOCK_RESPONSES'] = path.join(__dirname, name);
}
describe('AzureCLI Suite', function () {
this.timeout(parseInt(process.env.TASK_TEST_TIMEOUT) || 20000);
before((done) => {
done();
});
after(function () {
});
function addInlineObjectJson(responseFileName:string, nameOfFileToBeCreated:string)
{
var jsonFileObject:any = JSON.parse(fs.readFileSync(path.join(__dirname,responseFileName)).toString());
if(os.type() == "Windows_NT")
{
if( !jsonFileObject.exec[nameOfFileToBeCreated]){
jsonFileObject.exec[nameOfFileToBeCreated] = jsonFileObject.exec['script.bat arg1'];
}
if(!jsonFileObject.which[nameOfFileToBeCreated]) {
jsonFileObject.which[nameOfFileToBeCreated] = nameOfFileToBeCreated;
}
if(!jsonFileObject.checkPath[nameOfFileToBeCreated]) {
jsonFileObject.checkPath[nameOfFileToBeCreated] = true;
}
}
else
{
if( !jsonFileObject.checkPath[nameOfFileToBeCreated]){
jsonFileObject.checkPath[nameOfFileToBeCreated] = true;
}
if( !jsonFileObject.exec[nameOfFileToBeCreated]){
jsonFileObject.exec[nameOfFileToBeCreated] = jsonFileObject.exec['script.bat arg1'];
}
}
fs.writeFileSync(path.join(__dirname,responseFileName), JSON.stringify(jsonFileObject));
}
function deleteInlineObjectJson(responseFileName:string, nameOfFileToBeCreated:string)
{
var jsonFileObject:any = JSON.parse(fs.readFileSync(path.join(__dirname,responseFileName)).toString());
if(os.type() === "Windows_NT")
{
delete jsonFileObject.exec[nameOfFileToBeCreated];
delete jsonFileObject.which[nameOfFileToBeCreated];
delete jsonFileObject.checkPath[nameOfFileToBeCreated];
}
else
{
delete jsonFileObject.exec[nameOfFileToBeCreated];
delete jsonFileObject.checkPath[nameOfFileToBeCreated];
}
fs.writeFileSync(path.join(__dirname,responseFileName), JSON.stringify(jsonFileObject));
}
var publishsettingFileName:string = '.*subscriptions.*';
var inlineScriptName:string = '.*azureclitaskscript.*';
it('successfully login azure RM and run shell script (scriptPath)', (done) => {
setResponseFile('azureclitaskPass.json');
var tr = new trm.TaskRunner('AzureCLI', false, false ,false);
tr.setInput('scriptLocation', 'scriptPath');
tr.setInput('scriptPath', 'script.sh');
tr.setInput('cwd', 'fake/wd');
tr.setInput('args', 'arg1');
tr.setInput('failOnStandardError', 'false');
tr.setInput('connectedServiceNameARM', 'AzureRM');
tr.run()
.then(() => {
assert(tr.ran('/usr/local/bin/az account clear'), 'it should have logged out of azure');
assert(tr.invokedToolCount == 4, 'should have only run ShellScript');
assert(tr.stderr.length == 0, 'should not have written to stderr');
assert(tr.succeeded, 'task should have succeeded');
done();
})
.fail((err) => {
done(err);
});
})
it('successfully login azure RM and run shell script (inline)', (done) => {
var responseFileName:string = 'azureclitaskPass.json';
addInlineObjectJson(responseFileName, inlineScriptName);
setResponseFile(responseFileName);
var tr = new trm.TaskRunner('AzureCLI', false, false, true);
tr.setInput('scriptLocation', 'inlineScript');
tr.setInput('inlineScript', 'console.log("test");');
tr.setInput('cwd', 'fake/wd');
tr.setInput('args', 'arg1');
tr.setInput('failOnStandardError', 'false');
tr.setInput('connectedServiceNameARM', 'AzureRM');
tr.run()
.then(() => {
deleteInlineObjectJson(responseFileName, inlineScriptName);
assert(tr.ran('/usr/local/bin/az account clear'), 'it should have logged out of azure');
assert(tr.invokedToolCount == 4, 'should have only run ShellScript');
assert(tr.stderr.length == 0, 'should not have written to stderr');
assert(tr.succeeded, 'task should have succeeded');
done();
})
.fail((err) => {
done(err);
});
})
it('should fail when endpoint is not correct (scriptPath)',(done) => {
setResponseFile('azureLoginFails.json');
var tr = new trm.TaskRunner('AzureCLI');
tr.setInput('scriptLocation', 'scriptPath');
tr.setInput('scriptPath', 'script.sh');
tr.setInput('cwd', 'fake/wd');
tr.setInput('args', 'arg1');
tr.setInput('failOnStandardError', 'false');
tr.setInput('connectedServiceNameARM', 'InvalidEndpoint');
tr.run()
.then(() => {
assert(tr.invokedToolCount == 0, 'should have only run ShellScript');
assert(tr.stderr.length > 0, 'should have written to stderr');
assert(tr.failed, 'task should have failed');
done();
})
.fail((err) => {
done(err);
});
})
it('should not logout and not run bash when login failed AzureRM (scriptPath)',(done) => {
setResponseFile('azureLoginFails.json');
var tr = new trm.TaskRunner('AzureCLI');
tr.setInput('scriptLocation', 'scriptPath');
tr.setInput('scriptPath', 'script.sh');
tr.setInput('cwd', 'fake/wd');
tr.setInput('args', 'arg1');
tr.setInput('failOnStandardError', 'false');
tr.setInput('connectedServiceNameARM', 'AzureRMFail');
tr.run()
.then(() => {
assert(tr.invokedToolCount == 1, 'should have only run 1 azure invocations');
assert(tr.stderr.length > 0, 'should have written to stderr');
assert(tr.failed, 'task should have failed');
done();
})
.fail((err) => {
done(err);
});
})
it('should logout and fail without running bash when subscription not set in AzureRM (scriptPath)',(done) => {
setResponseFile('azureLoginFails.json');
var tr = new trm.TaskRunner('AzureCLI');
tr.setInput('scriptLocation', 'scriptPath');
tr.setInput('scriptPath', 'script.sh');
tr.setInput('cwd', 'fake/wd');
tr.setInput('args', 'arg1');
tr.setInput('failOnStandardError', 'false');
tr.setInput('connectedServiceNameARM', 'AzureRM');
tr.run()
.then(() => {
assert(tr.ran('/usr/local/bin/az account clear'), 'it should have logged out of azure');
assert(tr.invokedToolCount == 3, 'should have only run ShellScript');
assert(tr.resultWasSet, 'task should have set a result');
assert(tr.stderr.length > 0, 'should have written to stderr');
assert(tr.failed, 'task should have failed');
done();
})
.fail((err) => {
done(err);
});
})
it('should logout of AzureRM if shell script execution failed (scripPath)',(done) => {
setResponseFile('scriptExecutionFailed.json');
var tr = new trm.TaskRunner('AzureCLI');
tr.setInput('scriptLocation', 'scriptPath');
tr.setInput('scriptPath', 'scriptfail.sh');
tr.setInput('cwd', 'fake/wd');
tr.setInput('args', 'arg1');
tr.setInput('failOnStandardError', 'false');
tr.setInput('connectedServiceNameSelector', 'connectedServiceNameARM');
tr.setInput('connectedServiceNameARM', 'AzureRM');
tr.run()
.then(() => {
assert(tr.invokedToolCount == 4, 'logout happened when bash fails');
assert(tr.stderr.length > 0, 'should have written to stderr');
assert(tr.failed, 'task should have failed');
done();
})
.fail((err) => {
done(err);
});
})
it('task should fail if bash not found',(done) => {
setResponseFile('toolnotfoundFails.json');
var tr = new trm.TaskRunner('AzureCLI');
tr.run()
.then(() => {
assert(tr.invokedToolCount == 0, 'should not have invoked any tool');
assert(tr.stderr.length > 0, 'should have written to stderr');
assert(tr.failed, 'task should have failed');
done();
})
.fail((err) => {
done(err);
});
})
it('task should fail if cmd not found',(done) => {
setResponseFile('toolnotfoundFails.json');
var tr = new trm.TaskRunner('AzureCLI');
tr.setInput('scriptLocation', 'scriptPath');
tr.setInput('cwd', 'fake/wd');
tr.setInput('scriptPath', 'script.bat');
tr.setInput('args', 'args1');
tr.setInput('failOnStandardError', 'false');
tr.run()
.then(() => {
assert(tr.invokedToolCount == 0, 'should not have invoked any tool');
assert(tr.stderr.length > 0, 'should have written to stderr');
assert(tr.failed, 'task should have failed');
done();
})
.fail((err) => {
done(err);
});
})
it('task should fail in case script path is invalid',(done) => {
setResponseFile('checkpathFails.json');
var tr = new trm.TaskRunner('AzureCLI');
tr.setInput('scriptLocation', 'scriptPath');
tr.setInput('cwd', 'fake/wd');
tr.setInput('scriptPath', 'scriptfail.sh');
tr.run()
.then(() => {
assert(tr.invokedToolCount == 0, 'logout happened when script checkpath fails');
assert(tr.stderr.length > 0, 'should have written to stderr');
assert(tr.failed, 'task should have failed');
done();
})
.fail((err) => {
done(err);
});
})
}); | the_stack |
import * as stream from "stream";
import * as util from "util";
import { parseJson5 } from "@adpt/utils";
import * as ld from "lodash";
import * as sb from "stream-buffers";
import * as xml2js from "xml2js";
import {
AnyProps,
DOMNode,
DOMObject,
} from "./dom";
const rootName = "Adapt";
async function parseXML(xmlStr: string): Promise<any> {
return new Promise<any>((res, rej) => {
xml2js.parseString(xmlStr, {
explicitRoot: false,
explicitChildren: true,
preserveChildrenOrder: true,
charsAsChildren: true,
xmlns: true,
}, (err, result) => {
if (err != null) rej(err);
else res(result);
});
});
}
export type XMLNode = GenericXMLNode | XMLPropsNode | XMLPropNode | XMLTextNode;
export interface GenericXMLNode {
"#name": string;
"$"?: Attrs;
"$$"?: XMLNode[];
"$ns"?: XMLNS;
}
export interface XMLPropsNode extends GenericXMLNode {
"#name": "__props__";
"$$"?: XMLPropNode[];
}
export interface XMLPropNode extends GenericXMLNode {
"#name": "prop";
"$$": XMLTextNode[];
}
export interface XMLLifecycleNode extends GenericXMLNode {
"#name": "__lifecycle__";
"$$"?: XMLLifecycleFieldNode[];
}
export interface XMLLifecycleFieldNode extends GenericXMLNode {
"#name": "field";
"$$": XMLTextNode[];
}
export interface XMLTextNode extends GenericXMLNode {
"#name": "__text__";
"_": string;
}
export interface XMLNS {
local: string;
uri: string;
}
export interface Attr {
local: string;
name: string;
prefix: string;
uri: string;
value: any;
}
export interface Attrs {
[key: string]: Attr;
}
function nameOf(xmlNode: XMLNode): string {
if (xmlNode.$ns) return xmlNode.$ns.local;
return xmlNode["#name"];
}
function uriOf(xmlNode: XMLNode): string {
if (xmlNode.$ns) return xmlNode.$ns.uri;
return "";
}
export function handleShortProp(val: string): string | number {
if (/^\d/.test(val)) {
const ret = Number(val);
if (isNaN(ret)) {
throw new Error("invalid short prop value \"" + val + "\"");
}
return ret;
} else {
return val;
}
}
function isTextNode(xmlNode: XMLNode): xmlNode is XMLTextNode {
return xmlNode["#name"] === "__text__";
}
function extractSoleText(xmlNode: XMLNode) {
if (xmlNode.$$ == null) {
throw new Error("body missing");
}
if (!ld.isArray(xmlNode.$$)) {
throw new Error("Internal Error");
}
if (xmlNode.$$.length > 1) {
throw new Error("too many children");
}
if (xmlNode.$$.length === 0) {
throw new Error("node has no body");
}
const child = xmlNode.$$[0];
if (isTextNode(child)) {
return child._;
} else {
throw new Error("no text node found");
}
}
function extractDOMObject(xmlNode: XMLNode): DOMObject {
if (xmlNode.$$ == null) new Error("body missing");
if (!ld.isArray(xmlNode.$$)) throw new Error("Internal Error");
if (xmlNode.$$.length > 1) throw new Error("too many children");
if (xmlNode.$$.length === 0) throw new Error("node has no body");
const child = xmlNode.$$[0];
const uri = uriOf(child);
if (!uri.startsWith("urn:")) throw new Error("child has bad xmlns");
const json = extractSoleText(child);
return new DOMObject(uri, parseJson5(json));
}
function handleJSON(xmlNode: XMLNode): object {
if (nameOf(xmlNode) !== "json") {
throw new Error("Internal Error: Request to handle json node for non-json: " +
util.inspect(xmlNode));
}
let txt = "";
try {
txt = extractSoleText(xmlNode);
return parseJson5(txt);
} catch (e) {
throw new Error("malformed json node body: " + e.message);
}
}
function getPropsNode(xmlNode: XMLNode): XMLPropsNode[] {
const anode = xmlNode as any;
if (anode.__props__ != null) {
return anode.__props__;
}
return [];
}
function extractProp(prop: XMLPropNode): any {
try {
return parseJson5(extractSoleText(prop));
} catch (err) { /* */ }
return extractDOMObject(prop);
}
function computeProps(xmlNodeIn: XMLNode): AnyProps {
const ret: AnyProps = {};
const xmlNode = xmlNodeIn as GenericXMLNode;
if (xmlNode.$ != null) {
for (const prop in xmlNode.$) {
if (prop === "xmlns" || prop.startsWith("xmlns:")) continue;
if (!Object.prototype.hasOwnProperty.apply(xmlNode.$, [prop])) continue;
ret[prop] = handleShortProp(xmlNode.$[prop].value);
}
}
const propsNodes = getPropsNode(xmlNode);
if (propsNodes.length > 1) {
throw new Error("malformed node, multiple __props__ children");
}
if (propsNodes.length < 1) {
return ret;
}
const propsNode = propsNodes[0];
if (propsNode.$$ != null) {
for (const prop of propsNode.$$) {
if (prop.$ != null) {
const name = prop.$.name.value;
if (ret[name] != null) throw new Error("duplicate prop: " + name);
try {
ret[name] = extractProp(prop);
} catch (e) {
throw new Error("malformed prop node for " + name + ": " + e.message);
}
}
}
}
return ret;
}
export interface LifecycleInfo {
stateNamespace: string[];
keyPath: string[];
path: string;
}
function getLifecycleNode(xmlNode: XMLNode): XMLLifecycleNode[] {
const anode = xmlNode as any;
if (anode.__lifecycle__ != null) {
return anode.__lifecycle__;
}
return [];
}
function extractStringArray(xmlNode: XMLNode): string[] {
const dataJson = extractSoleText(xmlNode);
if (dataJson == null) throw new Error(`No text data in node: ${util.inspect(xmlNode)}`);
const data = parseJson5(dataJson);
if (!util.isArray(data)) throw new Error(`text data is not an array, expecting string[]: ${util.inspect(xmlNode)}`);
const notString = data.find((v) => !util.isString(v));
if (notString !== undefined) {
throw new Error(`${util.inspect(notString)} is not string, expecting string[]:` + util.inspect(xmlNode));
}
return data as string[];
}
function extractString(xmlNode: XMLNode): string {
const dataJson = extractSoleText(xmlNode);
if (dataJson == null) throw new Error(`No text data in node: ${util.inspect(xmlNode)}`);
const data = parseJson5(dataJson);
if (!util.isString(data)) throw new Error(`text data is not a string: ${util.inspect(xmlNode)}`);
return data;
}
function augmentError<T>(msg: string, f: () => T): T {
try {
return f();
} catch (e) {
throw new Error(msg + ":" + e.message);
}
}
function computeLifecycleInfo(xmlNode: XMLNode): LifecycleInfo | undefined {
const lifecycleNodes = getLifecycleNode(xmlNode);
if (lifecycleNodes.length > 1) {
throw new Error(`malformed ndoe, multiple __lifecycle__ children: ${util.inspect(xmlNode)}`);
}
if (lifecycleNodes.length < 1) return;
const lifecycleNode = lifecycleNodes[0];
if (lifecycleNode.$$ == null) return;
const ret: Partial<LifecycleInfo> = {};
for (const field of lifecycleNode.$$) {
if (field.$ == null) {
throw new Error(`malformed node, lifecycle field with no name ${util.inspect(lifecycleNode)}`);
}
const fieldName = field.$.name.value;
switch (fieldName) {
case "stateNamespace":
ret.stateNamespace = augmentError("extracting stateNamespace", () => extractStringArray(field));
break;
case "keyPath":
ret.keyPath = augmentError("extracting keyPath", () => extractStringArray(field));
break;
case "path":
ret.path = augmentError("extracting path", () => extractString(field));
break;
default:
throw new Error(`malformed node, ` +
`uknown lifecycle field name "${fieldName}": ${util.inspect(lifecycleNode)}`);
}
}
const nodeInfo = util.inspect(xmlNode);
if (ret.stateNamespace === undefined) throw new Error(`no stateNamespace in lifecycle data: ${nodeInfo}`);
if (ret.keyPath === undefined) throw new Error (`no keyPath in lifecycle data: ${nodeInfo}`);
if (ret.path === undefined) throw new Error (`no path in lifecycle data: ${nodeInfo}`);
return ret as LifecycleInfo;
}
function buildFromXMLNode(xmlNode: XMLNode): DOMNode {
const name = nameOf(xmlNode);
const uri = uriOf(xmlNode);
const props = computeProps(xmlNode);
const lifecycle = computeLifecycleInfo(xmlNode);
const children: any[] = [];
if (xmlNode.$$ != null) {
if (ld.isArray(xmlNode.$$)) {
for (const child of xmlNode.$$) {
if (ld.isObject(child)) {
if (nameOf(child) === "__props__") {
continue;
} else if (nameOf(child) === "__lifecycle__") {
continue;
} else if (nameOf(child) === "json") {
children.push(handleJSON(child));
} else {
children.push(buildFromXMLNode(child));
}
} else {
children.push(child);
}
}
} else {
throw new Error("Internal parse error");
}
}
return new DOMNode(name, props, lifecycle, uri, children);
}
export async function domFromXMLObj(xmlObj: XMLNode) {
if (nameOf(xmlObj) !== rootName) {
throw new Error("Unknown root node: " + nameOf(xmlObj));
}
const topLevel = xmlObj.$$;
if (topLevel == null) {
return null;
}
if (!ld.isArray(topLevel)) {
throw new Error("Internal error parsing DOM");
}
if (topLevel.length === 0) {
return null;
}
if (topLevel.length > 1) {
throw new Error("Too many elements at root, must have single DOM Node");
}
//console.log(util.inspect(xmlObj));
return buildFromXMLNode(topLevel[0]);
}
export async function domFromString(xmlStr: string) {
const xmlObj: XMLNode | null = await parseXML(xmlStr);
if (xmlObj == null) throw new Error(`Invalid empty XML`);
return domFromXMLObj(xmlObj);
}
async function stringFromStream(ins: stream.Readable): Promise<string> {
return new Promise<string>((res, rej) => {
const buf = new sb.WritableStreamBuffer();
ins.pipe(buf);
buf.on("close", () => res(buf.getContentsAsString() || undefined));
buf.on("error", (e) => rej(e));
});
}
export async function domFromStream(ins: stream.Readable) {
const xmlStr = await stringFromStream(ins);
return domFromString(xmlStr);
} | the_stack |
import {
ICompiler,
ITsAccessor,
ITsClass,
ITsConstructor,
ITsDocBase,
ITsEnum,
ITsEnumMember,
ITsFlags,
ITsInterface,
ITsMethod,
ITsParameter,
ITsProperty,
ITsSignature,
ITsTypeAlias,
Kind,
} from "@documentalist/client";
import { relative } from "path";
import {
DeclarationReflection,
ParameterReflection,
ProjectReflection,
Reflection,
ReflectionKind,
SignatureReflection,
} from "typedoc";
import { Comment, UnionType } from "typedoc/dist/lib/models";
import { DefaultValueContainer } from "typedoc/dist/lib/models/reflections/abstract";
import { ITypescriptPluginOptions } from "./index";
import { resolveSignature, resolveTypeString } from "./typestring";
export class Visitor {
public constructor(private compiler: ICompiler, private options: ITypescriptPluginOptions) {}
public visitProject(project: ProjectReflection) {
const { excludePaths = [] } = this.options;
// get top-level members of typedoc project
return [
...this.visitChildren(project.getReflectionsByKind(ReflectionKind.Class), this.visitClass),
...this.visitChildren(project.getReflectionsByKind(ReflectionKind.Enum), this.visitEnum),
...this.visitChildren(project.getReflectionsByKind(ReflectionKind.Function), this.visitMethod),
...this.visitChildren(project.getReflectionsByKind(ReflectionKind.Interface), this.visitInterface),
...this.visitChildren(
// detect if a `const X = { A, B, C }` also has a corresponding `type X = A | B | C`
project.getReflectionsByKind(ReflectionKind.ObjectLiteral).filter(isConstTypePair),
this.visitConstTypePair,
),
...this.visitChildren<ITsTypeAlias>(project.getReflectionsByKind(ReflectionKind.TypeAlias), (def) => ({
...this.makeDocEntry(def, Kind.TypeAlias),
type: resolveTypeString(def.type),
})),
].filter(
// remove members excluded by path option
(ref) => isNotExcluded(excludePaths, ref.fileName),
);
}
private makeDocEntry<K extends Kind>(def: Reflection, kind: K): ITsDocBase<K> {
return {
documentation: this.renderComment(def.comment),
fileName: getSourceFileName(def),
flags: getFlags(def),
kind,
name: def.name,
sourceUrl: getSourceUrl(def),
};
}
private visitClass = (def: DeclarationReflection): ITsClass => ({
...this.visitInterface(def),
accessors: this.visitChildren(def.getChildrenByKind(ReflectionKind.Accessor), this.visitAccessor),
constructorType: this.visitChildren(
def.getChildrenByKind(ReflectionKind.Constructor),
this.visitConstructor,
)[0],
kind: Kind.Class,
});
private visitInterface = (def: DeclarationReflection): ITsInterface => ({
...this.makeDocEntry(def, Kind.Interface),
extends: def.extendedTypes && def.extendedTypes.map(resolveTypeString),
implements: def.implementedTypes && def.implementedTypes.map(resolveTypeString),
indexSignature: def.indexSignature && this.visitSignature(def.indexSignature),
methods: this.visitChildren(def.getChildrenByKind(ReflectionKind.Method), this.visitMethod, sortStaticFirst),
properties: this.visitChildren(
def.getChildrenByKind(ReflectionKind.Property),
this.visitProperty,
sortStaticFirst,
),
});
private visitConstructor = (def: DeclarationReflection): ITsConstructor => ({
...this.visitMethod(def),
kind: Kind.Constructor,
});
private visitConstTypePair = (def: DeclarationReflection): ITsEnum => ({
...this.makeDocEntry(def, Kind.Enum),
// ObjectLiteral has Variable children, but we'll expose them as enum members
members: this.visitChildren<ITsEnumMember>(def.getChildrenByKind(ReflectionKind.Variable), (m) => ({
...this.makeDocEntry(m, Kind.EnumMember),
defaultValue: resolveTypeString(m.type),
})),
});
private visitEnum = (def: DeclarationReflection): ITsEnum => ({
...this.makeDocEntry(def, Kind.Enum),
members: this.visitChildren<ITsEnumMember>(def.getChildrenByKind(ReflectionKind.EnumMember), (m) => ({
...this.makeDocEntry(m, Kind.EnumMember),
defaultValue: getDefaultValue(m),
})),
});
private visitProperty = (def: DeclarationReflection): ITsProperty => ({
...this.makeDocEntry(def, Kind.Property),
defaultValue: getDefaultValue(def),
inheritedFrom: def.inheritedFrom && resolveTypeString(def.inheritedFrom),
type: resolveTypeString(def.type),
});
private visitMethod = (def: DeclarationReflection): ITsMethod => ({
...this.makeDocEntry(def, Kind.Method),
inheritedFrom: def.inheritedFrom && resolveTypeString(def.inheritedFrom),
signatures: def.signatures !== undefined ? def.signatures.map((sig) => this.visitSignature(sig)) : [],
});
private visitSignature = (sig: SignatureReflection): ITsSignature => ({
...this.makeDocEntry(sig, Kind.Signature),
flags: undefined,
parameters: (sig.parameters || []).map((param) => this.visitParameter(param)),
returnType: resolveTypeString(sig.type),
type: resolveSignature(sig),
});
private visitParameter = (param: ParameterReflection): ITsParameter => ({
...this.makeDocEntry(param, Kind.Parameter),
defaultValue: getDefaultValue(param),
sourceUrl: undefined,
type: resolveTypeString(param.type),
});
private visitAccessor = (param: DeclarationReflection): ITsAccessor => {
let type: string;
let getDocumentation;
let setDocumentation;
if (param.getSignature) {
type = resolveTypeString(param.getSignature.type);
} else if (param.setSignature && param.setSignature.parameters && param.setSignature.parameters[0]) {
type = resolveTypeString(param.setSignature.parameters[0].type);
} else {
throw Error("Accessor did neither define get nor set signature.");
}
if (param.getSignature) {
getDocumentation = this.renderComment(param.getSignature.comment);
}
if (param.setSignature) {
setDocumentation = this.renderComment(param.setSignature.comment);
}
return {
...this.makeDocEntry(param, Kind.Accessor),
getDocumentation,
setDocumentation,
type,
};
};
/** Visits each child that passes the filter condition (based on options). */
private visitChildren<T extends ITsDocBase>(
children: Reflection[],
visitor: (def: DeclarationReflection) => T,
comparator?: (a: T, b: T) => number,
): T[] {
const { excludeNames = [], excludePaths = [], includeNonExportedMembers = false } = this.options;
return children
.filter((ref) => ref.flags.isExported || includeNonExportedMembers)
.map(visitor)
.filter((doc) => isNotExcluded(excludeNames, doc.name) && isNotExcluded(excludePaths, doc.fileName))
.sort(comparator);
}
/**
* Converts a typedoc comment object to a rendered `IBlock`.
*/
private renderComment(comment: Comment | undefined) {
if (!comment) {
return undefined;
}
let documentation = "";
if (comment.shortText) {
documentation += comment.shortText;
}
if (comment.text) {
documentation += "\n\n" + comment.text;
}
if (comment.tags) {
documentation +=
"\n\n" +
comment.tags
.filter((tag) => tag.tagName !== "default" && tag.tagName !== "deprecated")
.map((tag) => `@${tag.tagName} ${tag.text}`)
.join("\n");
}
return this.compiler.renderBlock(documentation);
}
}
function getCommentTag(comment: Comment | undefined, tagName: string) {
if (comment == null || comment.tags == null) {
return undefined;
}
return comment.tags.filter((tag) => tag.tagName === tagName)[0];
}
function getDefaultValue(ref: DefaultValueContainer): string | undefined {
if (ref.defaultValue != null) {
return ref.defaultValue;
}
const defaultValue = getCommentTag(ref.comment, "default");
if (defaultValue !== undefined) {
return defaultValue.text.trim();
}
return undefined;
}
function getSourceFileName({ sources = [] }: Reflection): string | undefined {
const source = sources[0];
const fileName = source && source.file && source.file.fullFileName;
// filename relative to cwd, so it can be saved in a snapshot (machine-independent)
return fileName && relative(process.cwd(), fileName);
}
function getSourceUrl({ sources = [] }: Reflection): string | undefined {
const source = sources[0];
return source && source.url;
}
function getFlags(ref: Reflection): ITsFlags | undefined {
if (ref === undefined || ref.flags === undefined) {
return undefined;
}
const isDeprecated = getIsDeprecated(ref);
const { isExported, isExternal, isOptional, isPrivate, isProtected, isPublic, isRest, isStatic } = ref.flags;
return {
isDeprecated,
isExported,
isExternal,
isOptional,
isPrivate,
isProtected,
isPublic,
isRest,
isStatic,
};
}
function getIsDeprecated(ref: Reflection) {
const deprecatedTag = getCommentTag(ref.comment, "deprecated");
if (deprecatedTag === undefined) {
return undefined;
}
const text = deprecatedTag.text.trim();
return text === "" ? true : text;
}
function isConstTypePair(def: DeclarationReflection) {
return def.kind === ReflectionKind.ObjectLiteral && def.type instanceof UnionType;
}
/** Returns true if value does not match all patterns. */
function isNotExcluded(patterns: Array<string | RegExp>, value?: string) {
return value === undefined || patterns.every((p) => value.match(p) == null);
}
/** Sorts static members (`flags.isStatic`) before non-static members. */
function sortStaticFirst<T extends ITsDocBase>({ flags: aFlags = {} }: T, { flags: bFlags = {} }: T) {
if (aFlags.isStatic && bFlags.isStatic) {
return 0;
} else if (aFlags.isStatic) {
return -1;
} else if (bFlags.isStatic) {
return 1;
}
return 0;
} | the_stack |
import { ObjectMap } from '@0x/types';
import { DataItem } from 'ethereum-types';
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash';
import { BigNumber } from '../../../configured_bignumber';
import { SetCalldataBlock } from '../../calldata/blocks/set';
import { CalldataBlock } from '../../calldata/calldata_block';
import { RawCalldata } from '../../calldata/raw_calldata';
import { constants } from '../../utils/constants';
import { DecodingRules } from '../../utils/rules';
import { DataType } from '../data_type';
import { DataTypeFactory, MemberIndexByName } from '../interfaces';
import { AbstractPointerDataType } from './pointer';
export abstract class AbstractSetDataType extends DataType {
protected readonly _arrayLength: number | undefined;
protected readonly _arrayElementType: string | undefined;
private readonly _memberIndexByName: MemberIndexByName;
private readonly _members: DataType[];
private readonly _isArray: boolean;
public constructor(
dataItem: DataItem,
factory: DataTypeFactory,
isArray: boolean = false,
arrayLength?: number,
arrayElementType?: string,
) {
super(dataItem, factory);
this._memberIndexByName = {};
this._members = [];
this._isArray = isArray;
this._arrayLength = arrayLength;
this._arrayElementType = arrayElementType;
if (isArray && arrayLength !== undefined) {
[this._members, this._memberIndexByName] = this._createMembersWithLength(dataItem, arrayLength);
} else if (!isArray) {
[this._members, this._memberIndexByName] = this._createMembersWithKeys(dataItem);
}
}
public generateCalldataBlock(value: any[] | object, parentBlock?: CalldataBlock): SetCalldataBlock {
const block = Array.isArray(value)
? this._generateCalldataBlockFromArray(value, parentBlock)
: this._generateCalldataBlockFromObject(value, parentBlock);
return block;
}
public generateValue(calldata: RawCalldata, rules: DecodingRules): any[] | object {
let members = this._members;
// Case 1: This is an array of undefined length, which means that `this._members` was not
// populated in the constructor. So we must construct the set of members now.
if (this._isArray && this._arrayLength === undefined) {
const arrayLengthBuf = calldata.popWord();
const arrayLengthHex = ethUtil.bufferToHex(arrayLengthBuf);
const arrayLength = new BigNumber(arrayLengthHex, constants.HEX_BASE);
[members] = this._createMembersWithLength(this.getDataItem(), arrayLength.toNumber());
}
// Create a new scope in the calldata, before descending into the members of this set.
calldata.startScope();
let value: any[] | object;
if (rules.shouldConvertStructsToObjects && !this._isArray) {
// Construct an object with values for each member of the set.
value = {};
_.each(this._memberIndexByName, (idx: number, key: string) => {
const member = this._members[idx];
const memberValue = member.generateValue(calldata, rules);
(value as { [key: string]: any })[key] = memberValue;
});
} else {
// Construct an array with values for each member of the set.
value = [];
_.each(members, (member: DataType, idx: number) => {
const memberValue = member.generateValue(calldata, rules);
(value as any[]).push(memberValue);
});
}
// Close this scope and return tetheh value.
calldata.endScope();
return value;
}
public isStatic(): boolean {
// An array with an undefined length is never static.
if (this._isArray && this._arrayLength === undefined) {
return false;
}
// If any member of the set is a pointer then the set is not static.
const dependentMember = _.find(this._members, (member: DataType) => {
return member instanceof AbstractPointerDataType;
});
const isStatic = dependentMember === undefined;
return isStatic;
}
public getDefaultValue(rules?: DecodingRules): any[] | object {
let defaultValue: any[] | object;
if (this._isArray && this._arrayLength === undefined) {
defaultValue = [];
} else if (rules !== undefined && rules.shouldConvertStructsToObjects && !this._isArray) {
defaultValue = {};
_.each(this._memberIndexByName, (idx: number, key: string) => {
const member = this._members[idx];
const memberValue = member.getDefaultValue();
(defaultValue as { [key: string]: any })[key] = memberValue;
});
} else {
defaultValue = [];
_.each(this._members, (member: DataType, idx: number) => {
const memberValue = member.getDefaultValue();
(defaultValue as any[]).push(memberValue);
});
}
return defaultValue;
}
protected _generateCalldataBlockFromArray(value: any[], parentBlock?: CalldataBlock): SetCalldataBlock {
// Sanity check: if the set has a defined length then `value` must have the same length.
if (this._arrayLength !== undefined && value.length !== this._arrayLength) {
throw new Error(
`Expected array of ${JSON.stringify(
this._arrayLength,
)} elements, but got array of length ${JSON.stringify(value.length)}`,
);
}
// Create a new calldata block for this set.
const parentName = parentBlock === undefined ? '' : parentBlock.getName();
const block = new SetCalldataBlock(this.getDataItem().name, this.getSignature(), parentName);
// If this set has an undefined length then set its header to be the number of elements.
let members = this._members;
if (this._isArray && this._arrayLength === undefined) {
[members] = this._createMembersWithLength(this.getDataItem(), value.length);
const lenBuf = ethUtil.setLengthLeft(
ethUtil.toBuffer(`0x${value.length.toString(constants.HEX_BASE)}`),
constants.EVM_WORD_WIDTH_IN_BYTES,
);
block.setHeader(lenBuf);
}
// Create blocks for members of set.
const memberCalldataBlocks: CalldataBlock[] = [];
_.each(members, (member: DataType, idx: number) => {
const memberBlock = member.generateCalldataBlock(value[idx], block);
memberCalldataBlocks.push(memberBlock);
});
block.setMembers(memberCalldataBlocks);
return block;
}
protected _generateCalldataBlockFromObject(obj: object, parentBlock?: CalldataBlock): SetCalldataBlock {
// Create a new calldata block for this set.
const parentName = parentBlock === undefined ? '' : parentBlock.getName();
const block = new SetCalldataBlock(this.getDataItem().name, this.getSignature(), parentName);
// Create blocks for members of set.
const memberCalldataBlocks: CalldataBlock[] = [];
_.forEach(this._memberIndexByName, (memberIndex: number, memberName: string) => {
if (!(memberName in obj)) {
throw new Error(
`Could not assign tuple to object: missing key '${memberName}' in object ${JSON.stringify(obj)}`,
);
}
const memberValue: any = (obj as ObjectMap<any>)[memberName];
const memberBlock = this._members[memberIndex].generateCalldataBlock(memberValue, block);
memberCalldataBlocks.push(memberBlock);
});
// Associate member blocks with Set block.
block.setMembers(memberCalldataBlocks);
return block;
}
protected _computeSignatureOfMembers(isDetailed?: boolean): string {
// Compute signature of members
let signature = `(`;
_.each(this._members, (member: DataType, i: number) => {
signature += member.getSignature(isDetailed);
if (i < this._members.length - 1) {
signature += ',';
}
});
signature += ')';
return signature;
}
private _createMembersWithKeys(dataItem: DataItem): [DataType[], MemberIndexByName] {
// Sanity check
if (dataItem.components === undefined) {
throw new Error(
`Tried to create a set using key/value pairs, but no components were defined by the input DataItem '${
dataItem.name
}'.`,
);
}
// Create one member for each component of `dataItem`
const members: DataType[] = [];
const memberIndexByName: MemberIndexByName = {};
const memberNames: string[] = [];
_.each(dataItem.components, (memberItem: DataItem) => {
// If a component with `name` already exists then
// rename to `name_nameIdx` to avoid naming conflicts.
let memberName = memberItem.name;
let nameIdx = 0;
while (_.includes(memberNames, memberName) || _.isEmpty(memberName)) {
nameIdx++;
memberName = `${memberItem.name}_${nameIdx}`;
}
memberNames.push(memberName);
const childDataItem: DataItem = {
type: memberItem.type,
name: `${dataItem.name}.${memberName}`,
};
const components = memberItem.components;
if (components !== undefined) {
childDataItem.components = components;
}
const child = this.getFactory().create(childDataItem, this);
memberIndexByName[memberName] = members.length;
members.push(child);
});
return [members, memberIndexByName];
}
private _createMembersWithLength(dataItem: DataItem, length: number): [DataType[], MemberIndexByName] {
// Create `length` members, deriving the type from `dataItem`
const members: DataType[] = [];
const memberIndexByName: MemberIndexByName = {};
const range = _.range(length);
_.each(range, (idx: number) => {
const memberDataItem: DataItem = {
type: this._arrayElementType === undefined ? '' : this._arrayElementType,
name: `${dataItem.name}[${idx.toString(constants.DEC_BASE)}]`,
};
const components = dataItem.components;
if (components !== undefined) {
memberDataItem.components = components;
}
const memberType = this.getFactory().create(memberDataItem, this);
memberIndexByName[idx.toString(constants.DEC_BASE)] = members.length;
members.push(memberType);
});
return [members, memberIndexByName];
}
} | the_stack |
import {
CompressionFlag,
ContextFlag,
instantiateSecp256k1Wasm,
instantiateSecp256k1WasmBytes,
Secp256k1Wasm,
} from '../bin/bin';
import { RecoverableSignature, RecoveryId, Secp256k1 } from './secp256k1-types';
export { RecoverableSignature, RecoveryId, Secp256k1 };
const enum ByteLength {
compactSig = 64,
compressedPublicKey = 33,
internalPublicKey = 64,
internalSig = 64,
maxPublicKey = 65,
maxECDSASig = 72,
messageHash = 32,
privateKey = 32,
randomSeed = 32,
recoverableSig = 65,
schnorrSig = 64,
uncompressedPublicKey = 65,
}
/**
* @param secp256k1Wasm - a Secp256k1Wasm object
* @param randomSeed - a 32-byte random seed used to randomize the context after
* creation
*/
const wrapSecp256k1Wasm = (
secp256k1Wasm: Secp256k1Wasm,
randomSeed?: Uint8Array
): Secp256k1 => {
/**
* Currently, this wrapper creates a context with both SIGN and VERIFY
* capabilities. For better initialization performance, consumers could
* re-implement a wrapper with only the capabilities they require.
*/
const contextPtr = secp256k1Wasm.contextCreate(ContextFlag.BOTH);
/**
* Since all of these methods are single-threaded and synchronous, we can
* reuse allocated WebAssembly memory for each method without worrying about
* calls interfering with each other. Likewise, these spaces never need to be
* `free`d, since we will continue using them until this entire object (and
* with it, the entire WebAssembly instance) is garbage collected.
*
* If malicious javascript gained access to this object, it should be
* considered a critical vulnerability in the consumer. However, as a best
* practice, we zero out private keys below when we're finished with them.
*/
const sigScratch = secp256k1Wasm.malloc(ByteLength.maxECDSASig);
const publicKeyScratch = secp256k1Wasm.malloc(ByteLength.maxPublicKey);
const messageHashScratch = secp256k1Wasm.malloc(ByteLength.messageHash);
const internalPublicKeyPtr = secp256k1Wasm.malloc(
ByteLength.internalPublicKey
);
const internalSigPtr = secp256k1Wasm.malloc(ByteLength.internalSig);
const schnorrSigPtr = secp256k1Wasm.malloc(ByteLength.schnorrSig);
const privateKeyPtr = secp256k1Wasm.malloc(ByteLength.privateKey);
const internalRSigPtr = secp256k1Wasm.malloc(ByteLength.recoverableSig);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const recoveryNumPtr = secp256k1Wasm.malloc(4);
// eslint-disable-next-line no-bitwise, @typescript-eslint/no-magic-numbers
const recoveryNumPtrView32 = recoveryNumPtr >> 2;
const getRecoveryNumPtr = () => secp256k1Wasm.heapU32[recoveryNumPtrView32];
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const lengthPtr = secp256k1Wasm.malloc(4);
// eslint-disable-next-line no-bitwise, @typescript-eslint/no-magic-numbers
const lengthPtrView32 = lengthPtr >> 2;
const parsePublicKey = (publicKey: Uint8Array) => {
secp256k1Wasm.heapU8.set(publicKey, publicKeyScratch);
return (
secp256k1Wasm.pubkeyParse(
contextPtr,
internalPublicKeyPtr,
publicKeyScratch,
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
publicKey.length as 33 | 65
) === 1
);
};
const setLengthPtr = (value: number) => {
secp256k1Wasm.heapU32.set([value], lengthPtrView32);
};
const getLengthPtr = () => secp256k1Wasm.heapU32[lengthPtrView32];
const serializePublicKey = (length: number, flag: number) => {
setLengthPtr(length);
secp256k1Wasm.pubkeySerialize(
contextPtr,
publicKeyScratch,
lengthPtr,
internalPublicKeyPtr,
flag
);
return secp256k1Wasm.readHeapU8(publicKeyScratch, getLengthPtr()).slice();
};
const getSerializedPublicKey = (compressed: boolean) =>
compressed
? serializePublicKey(
ByteLength.compressedPublicKey,
CompressionFlag.COMPRESSED
)
: serializePublicKey(
ByteLength.uncompressedPublicKey,
CompressionFlag.UNCOMPRESSED
);
const convertPublicKey = (
compressed: boolean
): ((publicKey: Uint8Array) => Uint8Array) => (publicKey) => {
if (!parsePublicKey(publicKey)) {
throw new Error('Failed to parse public key.');
}
return getSerializedPublicKey(compressed);
};
const parseSignature = (signature: Uint8Array, isDer: boolean) => {
secp256k1Wasm.heapU8.set(signature, sigScratch);
return isDer
? secp256k1Wasm.signatureParseDER(
contextPtr,
internalSigPtr,
sigScratch,
signature.length
) === 1
: secp256k1Wasm.signatureParseCompact(
contextPtr,
internalSigPtr,
sigScratch
) === 1;
};
const parseOrThrow = (signature: Uint8Array, isDer: boolean) => {
if (!parseSignature(signature, isDer)) {
throw new Error('Failed to parse signature.');
}
};
const getCompactSig = () => {
secp256k1Wasm.signatureSerializeCompact(
contextPtr,
sigScratch,
internalSigPtr
);
return secp256k1Wasm.readHeapU8(sigScratch, ByteLength.compactSig).slice();
};
const getDERSig = () => {
setLengthPtr(ByteLength.maxECDSASig);
secp256k1Wasm.signatureSerializeDER(
contextPtr,
sigScratch,
lengthPtr,
internalSigPtr
);
return secp256k1Wasm.readHeapU8(sigScratch, getLengthPtr()).slice();
};
const convertSignature = (
wasDER: boolean
): ((signature: Uint8Array) => Uint8Array) => (signature) => {
parseOrThrow(signature, wasDER);
return wasDER ? getCompactSig() : getDERSig();
};
const fillPrivateKeyPtr = (privateKey: Uint8Array) => {
secp256k1Wasm.heapU8.set(privateKey, privateKeyPtr);
};
const zeroOutPtr = (pointer: number, bytes: number) => {
secp256k1Wasm.heapU8.fill(0, pointer, pointer + bytes);
};
const zeroOutPrivateKeyPtr = () => {
zeroOutPtr(privateKeyPtr, ByteLength.privateKey);
};
const withPrivateKey = <T>(
privateKey: Uint8Array,
instructions: () => T
): T => {
fillPrivateKeyPtr(privateKey);
const ret = instructions();
zeroOutPrivateKeyPtr();
return ret;
};
const derivePublicKey = (
compressed: boolean
): ((privateKey: Uint8Array) => Uint8Array) => (privateKey) => {
const invalid = withPrivateKey<boolean>(
privateKey,
() =>
secp256k1Wasm.pubkeyCreate(
contextPtr,
internalPublicKeyPtr,
privateKeyPtr
) !== 1
);
if (invalid) {
throw new Error('Cannot derive public key from invalid private key.');
}
return getSerializedPublicKey(compressed);
};
const fillMessageHashScratch = (messageHash: Uint8Array) => {
secp256k1Wasm.heapU8.set(messageHash, messageHashScratch);
};
const normalizeSignature = () => {
secp256k1Wasm.signatureNormalize(
contextPtr,
internalSigPtr,
internalSigPtr
);
};
const modifySignature = (
isDer: boolean,
normalize: boolean
): ((signature: Uint8Array) => Uint8Array) => (signature) => {
parseOrThrow(signature, isDer);
if (normalize) {
normalizeSignature();
} else {
secp256k1Wasm.signatureMalleate(
contextPtr,
internalSigPtr,
internalSigPtr
);
}
return isDer ? getDERSig() : getCompactSig();
};
const parseAndNormalizeSignature = (
signature: Uint8Array,
isDer: boolean,
normalize: boolean
) => {
const ret = parseSignature(signature, isDer);
if (normalize) {
normalizeSignature();
}
return ret;
};
const signMessageHash = (isDer: boolean) => (
privateKey: Uint8Array,
messageHash: Uint8Array
) => {
fillMessageHashScratch(messageHash);
return withPrivateKey<Uint8Array>(privateKey, () => {
const failed =
secp256k1Wasm.sign(
contextPtr,
internalSigPtr,
messageHashScratch,
privateKeyPtr
) !== 1;
if (failed) {
throw new Error(
'Failed to sign message hash. The private key is not valid.'
);
}
if (isDer) {
setLengthPtr(ByteLength.maxECDSASig);
secp256k1Wasm.signatureSerializeDER(
contextPtr,
sigScratch,
lengthPtr,
internalSigPtr
);
return secp256k1Wasm.readHeapU8(sigScratch, getLengthPtr()).slice();
}
secp256k1Wasm.signatureSerializeCompact(
contextPtr,
sigScratch,
internalSigPtr
);
return secp256k1Wasm
.readHeapU8(sigScratch, ByteLength.compactSig)
.slice();
});
};
const signMessageHashSchnorr = () => (
privateKey: Uint8Array,
messageHash: Uint8Array
) => {
fillMessageHashScratch(messageHash);
return withPrivateKey<Uint8Array>(privateKey, () => {
const failed =
secp256k1Wasm.schnorrSign(
contextPtr,
schnorrSigPtr,
messageHashScratch,
privateKeyPtr
) !== 1;
if (failed) {
throw new Error(
'Failed to sign message hash. The private key is not valid.'
);
}
return secp256k1Wasm
.readHeapU8(schnorrSigPtr, ByteLength.schnorrSig)
.slice();
});
};
const verifyMessage = (messageHash: Uint8Array) => {
fillMessageHashScratch(messageHash);
return (
secp256k1Wasm.verify(
contextPtr,
internalSigPtr,
messageHashScratch,
internalPublicKeyPtr
) === 1
);
};
const verifySignature = (isDer: boolean, normalize: boolean) => (
signature: Uint8Array,
publicKey: Uint8Array,
messageHash: Uint8Array
) =>
parsePublicKey(publicKey) &&
parseAndNormalizeSignature(signature, isDer, normalize) &&
verifyMessage(messageHash);
const verifyMessageSchnorr = (
messageHash: Uint8Array,
signature: Uint8Array
) => {
fillMessageHashScratch(messageHash);
secp256k1Wasm.heapU8.set(signature, schnorrSigPtr);
return (
secp256k1Wasm.schnorrVerify(
contextPtr,
schnorrSigPtr,
messageHashScratch,
internalPublicKeyPtr
) === 1
);
};
const verifySignatureSchnorr = () => (
signature: Uint8Array,
publicKey: Uint8Array,
messageHash: Uint8Array
) =>
parsePublicKey(publicKey)
? verifyMessageSchnorr(messageHash, signature)
: false;
const signMessageHashRecoverable = (
privateKey: Uint8Array,
messageHash: Uint8Array
): RecoverableSignature => {
fillMessageHashScratch(messageHash);
return withPrivateKey<RecoverableSignature>(privateKey, () => {
if (
secp256k1Wasm.signRecoverable(
contextPtr,
internalRSigPtr,
messageHashScratch,
privateKeyPtr
) !== 1
) {
throw new Error(
'Failed to sign message hash. The private key is not valid.'
);
}
secp256k1Wasm.recoverableSignatureSerialize(
contextPtr,
sigScratch,
recoveryNumPtr,
internalRSigPtr
);
return {
recoveryId: getRecoveryNumPtr() as RecoveryId,
signature: secp256k1Wasm
.readHeapU8(sigScratch, ByteLength.compactSig)
.slice(),
};
});
};
const recoverPublicKey = (compressed: boolean) => (
signature: Uint8Array,
recoveryId: RecoveryId,
messageHash: Uint8Array
) => {
fillMessageHashScratch(messageHash);
secp256k1Wasm.heapU8.set(signature, sigScratch);
if (
secp256k1Wasm.recoverableSignatureParse(
contextPtr,
internalRSigPtr,
sigScratch,
recoveryId
) !== 1
) {
throw new Error(
'Failed to recover public key. Could not parse signature.'
);
}
if (
secp256k1Wasm.recover(
contextPtr,
internalPublicKeyPtr,
internalRSigPtr,
messageHashScratch
) !== 1
) {
throw new Error(
'Failed to recover public key. The compact signature, recovery, or message hash is invalid.'
);
}
return getSerializedPublicKey(compressed);
};
const addTweakPrivateKey = (
privateKey: Uint8Array,
tweakValue: Uint8Array
): Uint8Array => {
fillMessageHashScratch(tweakValue);
return withPrivateKey<Uint8Array>(privateKey, () => {
if (
secp256k1Wasm.privkeyTweakAdd(
contextPtr,
privateKeyPtr,
messageHashScratch
) !== 1
) {
throw new Error('Private key is invalid or adding failed.');
}
return secp256k1Wasm
.readHeapU8(privateKeyPtr, ByteLength.privateKey)
.slice();
});
};
const mulTweakPrivateKey = (
privateKey: Uint8Array,
tweakValue: Uint8Array
): Uint8Array => {
fillMessageHashScratch(tweakValue);
return withPrivateKey<Uint8Array>(privateKey, () => {
if (
secp256k1Wasm.privkeyTweakMul(
contextPtr,
privateKeyPtr,
messageHashScratch
) !== 1
) {
throw new Error('Private key is invalid or multiplying failed.');
}
return secp256k1Wasm
.readHeapU8(privateKeyPtr, ByteLength.privateKey)
.slice();
});
};
const addTweakPublicKey = (compressed: boolean) => (
publicKey: Uint8Array,
tweakValue: Uint8Array
) => {
if (!parsePublicKey(publicKey)) {
throw new Error('Failed to parse public key.');
}
fillMessageHashScratch(tweakValue);
if (
secp256k1Wasm.pubkeyTweakAdd(
contextPtr,
internalPublicKeyPtr,
messageHashScratch
) !== 1
) {
throw new Error('Adding failed');
}
return getSerializedPublicKey(compressed);
};
const mulTweakPublicKey = (compressed: boolean) => (
publicKey: Uint8Array,
tweakValue: Uint8Array
) => {
if (!parsePublicKey(publicKey)) {
throw new Error('Failed to parse public key.');
}
fillMessageHashScratch(tweakValue);
if (
secp256k1Wasm.pubkeyTweakMul(
contextPtr,
internalPublicKeyPtr,
messageHashScratch
) !== 1
) {
throw new Error('Multiplying failed');
}
return getSerializedPublicKey(compressed);
};
/**
* The value of this precaution is debatable, especially in the context of
* javascript and WebAssembly.
*
* In the secp256k1 C library, context randomization is an additional layer of
* security from side-channel attacks which attempt to extract private key
* information by analyzing things like a CPU's emitted radio frequencies or
* power usage.
*
* In this library, these attacks seem even less likely, since the "platform"
* on which this code will be executed (e.g. V8) is likely to obscure any
* such signals.
*
* Still, out of an abundance of caution (and because no one has produced a
* definitive proof indicating that this is not helpful), this library exposes
* the ability to randomize the context like the C library. Depending on the
* intended application, consumers can decide whether or not to randomize.
*/
if (randomSeed !== undefined) {
const randomSeedPtr = messageHashScratch;
secp256k1Wasm.heapU8.set(randomSeed, randomSeedPtr);
secp256k1Wasm.contextRandomize(contextPtr, randomSeedPtr);
zeroOutPtr(randomSeedPtr, ByteLength.randomSeed);
}
return {
addTweakPrivateKey,
addTweakPublicKeyCompressed: addTweakPublicKey(true),
addTweakPublicKeyUncompressed: addTweakPublicKey(false),
compressPublicKey: convertPublicKey(true),
derivePublicKeyCompressed: derivePublicKey(true),
derivePublicKeyUncompressed: derivePublicKey(false),
malleateSignatureCompact: modifySignature(false, false),
malleateSignatureDER: modifySignature(true, false),
mulTweakPrivateKey,
mulTweakPublicKeyCompressed: mulTweakPublicKey(true),
mulTweakPublicKeyUncompressed: mulTweakPublicKey(false),
normalizeSignatureCompact: modifySignature(false, true),
normalizeSignatureDER: modifySignature(true, true),
recoverPublicKeyCompressed: recoverPublicKey(true),
recoverPublicKeyUncompressed: recoverPublicKey(false),
signMessageHashCompact: signMessageHash(false),
signMessageHashDER: signMessageHash(true),
signMessageHashRecoverableCompact: signMessageHashRecoverable,
signMessageHashSchnorr: signMessageHashSchnorr(),
signatureCompactToDER: convertSignature(false),
signatureDERToCompact: convertSignature(true),
uncompressPublicKey: convertPublicKey(false),
validatePrivateKey: (privateKey) =>
withPrivateKey<boolean>(
privateKey,
() => secp256k1Wasm.seckeyVerify(contextPtr, privateKeyPtr) === 1
),
verifySignatureCompact: verifySignature(false, true),
verifySignatureCompactLowS: verifySignature(false, false),
verifySignatureDER: verifySignature(true, true),
verifySignatureDERLowS: verifySignature(true, false),
verifySignatureSchnorr: verifySignatureSchnorr(),
};
};
/**
* This method is like `instantiateSecp256k1`, but requires the consumer to
* `Window.fetch` or `fs.readFile` the `secp256k1.wasm` binary and provide it to
* this method as `webassemblyBytes`. This skips a base64 decoding of an
* embedded binary.
*
* ### Randomizing the Context with `randomSeed`
* This method also accepts an optional, 32-byte `randomSeed`, which is passed
* to the `contextRandomize` method in the underlying WebAssembly.
*
* The value of this precaution is debatable, especially in the context of
* javascript and WebAssembly.
*
* In the secp256k1 C library, context randomization is an additional layer of
* security from side-channel attacks which attempt to extract private key
* information by analyzing things like a CPU's emitted radio frequencies or
* power usage.
*
* In this library, these attacks seem even less likely, since the "platform"
* on which this code will be executed (e.g. V8) is likely to obscure any
* such signals.
*
* Still, out of an abundance of caution (and because no one has produced a
* definitive proof indicating that this is not helpful), this library exposes
* the ability to randomize the context like the C library. Depending on the
* intended application, consumers can decide whether or not to randomize.
*
* @param webassemblyBytes - an ArrayBuffer containing the bytes from Libauth's
* `secp256k1.wasm` binary. Providing this buffer manually may be faster than
* the internal base64 decode which happens in `instantiateSecp256k1`.
* @param randomSeed - a 32-byte random seed used to randomize the secp256k1
* context after creation. See above for details.
*/
export const instantiateSecp256k1Bytes = async (
webassemblyBytes: ArrayBuffer,
randomSeed?: Uint8Array
): Promise<Secp256k1> =>
wrapSecp256k1Wasm(
await instantiateSecp256k1WasmBytes(webassemblyBytes),
randomSeed
);
const cachedSecp256k1: { cache?: Promise<Secp256k1> } = {};
/**
* Create and wrap a Secp256k1 WebAssembly instance to expose a set of
* purely-functional Secp256k1 methods. For slightly faster initialization, use
* `instantiateSecp256k1Bytes`.
*
* @param randomSeed - a 32-byte random seed used to randomize the secp256k1
* context after creation. See the description in `instantiateSecp256k1Bytes`
* for details.
*/
export const instantiateSecp256k1 = async (
randomSeed?: Uint8Array
): Promise<Secp256k1> => {
if (cachedSecp256k1.cache !== undefined) {
return cachedSecp256k1.cache;
}
const result = Promise.resolve(
wrapSecp256k1Wasm(await instantiateSecp256k1Wasm(), randomSeed)
);
// eslint-disable-next-line require-atomic-updates, functional/immutable-data
cachedSecp256k1.cache = result;
return result;
}; | the_stack |
import { CommandDescriptor, Commands } from ".";
import { ArgumentError, commands, Context, Direction, EditorRequiredError, Shift } from "../api";
import { Register } from "../state/registers";
function getRegister<F extends Register.Flags | Register.Flags[]>(
_: Context.WithoutActiveEditor,
argument: { register?: string | Register },
defaultRegisterName: string,
requiredFlags: F extends readonly (infer Fs)[] ? Fs : F,
): Register.WithFlags<F> {
let register = argument.register;
const extension = _.extension;
if (typeof register === "string") {
if (register.startsWith(" ")) {
if (!(_ instanceof Context)) {
throw new EditorRequiredError();
}
register = extension.registers.forDocument(_.document).get(register.slice(1));
} else {
register = extension.registers.get(register);
}
} else if (!(register instanceof Register)) {
register = extension.registers.get(defaultRegisterName);
}
register.checkFlags(requiredFlags);
return (argument.register = register as any);
}
function getCount(_: Context.WithoutActiveEditor, argument: { count?: number }) {
const count = +(argument.count as any);
if (count >= 0 && Number.isInteger(count)) {
return count;
}
return (argument.count = 0);
}
function getRepetitions(_: Context.WithoutActiveEditor, argument: { count?: number }) {
const count = getCount(_, argument);
if (count <= 0) {
return 1;
}
return count;
}
function getDirection(argument: { direction?: number | string }) {
const direction = argument.direction;
if (direction === undefined) {
return undefined;
}
if (typeof direction === "number") {
if (direction === 1 || direction === -1) {
return direction as Direction;
}
} else if (typeof direction === "string") {
if (direction === "forward") {
return Direction.Forward;
}
if (direction === "backward") {
return Direction.Backward;
}
}
throw new ArgumentError(
'"direction" must be "forward", "backward", 1, -1, or undefined',
"direction",
);
}
function getShift(argument: { shift?: number | string }) {
const shift = argument.shift;
if (shift === undefined) {
return undefined;
}
if (typeof shift === "number") {
if (shift === 0 || shift === 1 || shift === 2) {
return shift as Shift;
}
} else if (typeof shift === "string") {
if (shift === "jump") {
return Shift.Jump;
}
if (shift === "select") {
return Shift.Select;
}
if (shift === "extend") {
return Shift.Extend;
}
}
throw new ArgumentError(
'"shift" must be "jump", "select", "extend", 0, 1, 2, or undefined',
"shift",
);
}
function getInput(argument: { input?: any }) {
return argument.input;
}
function getSetInput(argument: { input?: any }) {
return (input: unknown) => argument.input = input;
}
function getInputOr(argument: { input?: any }): any {
const defaultInput = argument.input;
if (defaultInput != null) {
return () => defaultInput;
}
return (promptDefaultInput: () => any) => {
const result = promptDefaultInput();
if (typeof result.then === "function") {
return (result as Thenable<any>).then((x) => (argument.input = x));
}
return (argument.input = result);
};
}
/* eslint-disable max-len */
/* eslint-disable no-useless-escape */
//
// Content below this line was auto-generated by load-all.build.ts. Do not edit manually.
/**
* Loads the "dev" module and returns its defined commands.
*/
async function loadDevModule(): Promise<CommandDescriptor[]> {
const {
copyLastErrorMessage,
setSelectionBehavior,
} = await import("./dev");
return [
new CommandDescriptor(
"dance.dev.copyLastErrorMessage",
(_) => _.runAsync((_) => copyLastErrorMessage(_.extension)),
CommandDescriptor.Flags.None,
),
new CommandDescriptor(
"dance.dev.setSelectionBehavior",
(_, argument) => _.runAsync((_) => setSelectionBehavior(_, _.extension, argument.mode, argument.value)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
];
}
/**
* Loads the "edit" module and returns its defined commands.
*/
async function loadEditModule(): Promise<CommandDescriptor[]> {
const {
align,
case_swap,
case_toLower,
case_toUpper,
copyIndentation,
deindent,
deindent_withIncomplete,
indent,
indent_withEmpty,
insert,
join,
join_select,
newLine_above,
newLine_below,
replaceCharacters,
} = await import("./edit");
return [
new CommandDescriptor(
"dance.edit.align",
(_, argument) => _.runAsync((_) => align(_, _.selections, argument.fill)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.case.swap",
(_) => _.runAsync((_) => case_swap(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.case.toLower",
(_) => _.runAsync((_) => case_toLower(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.case.toUpper",
(_) => _.runAsync((_) => case_toUpper(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.copyIndentation",
(_, argument) => _.runAsync((_) => copyIndentation(_, _.document, _.selections, getCount(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.deindent",
(_, argument) => _.runAsync((_) => deindent(_, getRepetitions(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.deindent.withIncomplete",
(_, argument) => _.runAsync((_) => deindent_withIncomplete(_, getRepetitions(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.indent",
(_, argument) => _.runAsync((_) => indent(_, getRepetitions(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.indent.withEmpty",
(_, argument) => _.runAsync((_) => indent_withEmpty(_, getRepetitions(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.insert",
(_, argument) => _.runAsync((_) => insert(_, _.selections, getRegister(_, argument, "dquote", Register.Flags.CanRead), argument.adjust, argument.handleNewLine, getRepetitions(_, argument), argument.select, getShift(argument), argument.text, argument.where)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.join",
(_, argument) => _.runAsync((_) => join(_, argument.separator)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.join.select",
(_, argument) => _.runAsync((_) => join_select(_, argument.separator)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.newLine.above",
(_, argument) => _.runAsync((_) => newLine_above(_, getRepetitions(_, argument), argument.select, getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.newLine.below",
(_, argument) => _.runAsync((_) => newLine_below(_, getRepetitions(_, argument), argument.select, getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.replaceCharacters",
(_, argument) => _.runAsync((_) => replaceCharacters(_, getRepetitions(_, argument), getInputOr(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.edit.delete",
(_, argument) => _.runAsync(() => commands([".edit.insert", { register: "_", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.delete-insert",
(_, argument) => _.runAsync(() => commands([".modes.set", { input: "insert", ...argument }], [".edit.insert", { register: "_", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.newLine.above.insert",
(_, argument) => _.runAsync(() => commands([".edit.newLine.above", { shift: "select", ...argument }], [".modes.insert.before"])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.newLine.below.insert",
(_, argument) => _.runAsync(() => commands([".edit.newLine.below", { shift: "select", ...argument }], [".modes.insert.before"])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.paste.after",
(_, argument) => _.runAsync(() => commands([".edit.insert", { handleNewLine: true, where: "end", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.paste.after.select",
(_, argument) => _.runAsync(() => commands([".edit.insert", { handleNewLine: true, where: "end" , shift: "select", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.paste.before",
(_, argument) => _.runAsync(() => commands([".edit.insert", { handleNewLine: true, where: "start", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.paste.before.select",
(_, argument) => _.runAsync(() => commands([".edit.insert", { handleNewLine: true, where: "start", shift: "select", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.selectRegister-insert",
(_, argument) => _.runAsync(() => commands([".selectRegister"], [".edit.insert"])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.yank-delete",
(_, argument) => _.runAsync(() => commands([".selections.saveText"], [".edit.insert", { register: "_", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.yank-delete-insert",
(_, argument) => _.runAsync(() => commands([".selections.saveText"], [".modes.set", { input: "insert", ...argument }], [".edit.insert", { register: "_", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.edit.yank-replace",
(_, argument) => _.runAsync(() => commands([".selections.saveText", { register: "tmp", ...argument }], [".edit.insert"], [".updateRegister", { copyFrom: "tmp", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "history" module and returns its defined commands.
*/
async function loadHistoryModule(): Promise<CommandDescriptor[]> {
const {
recording_play,
recording_start,
recording_stop,
redo,
redo_selections,
repeat,
repeat_edit,
undo,
undo_selections,
} = await import("./history");
return [
new CommandDescriptor(
"dance.history.recording.play",
(_, argument) => _.runAsync((_) => recording_play(_, getRepetitions(_, argument), getRegister(_, argument, "arobase", Register.Flags.CanReadWriteMacros))),
CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.history.recording.start",
(_, argument) => _.runAsync((_) => recording_start(_, getRegister(_, argument, "arobase", Register.Flags.CanReadWriteMacros))),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.history.recording.stop",
(_, argument) => _.runAsync((_) => recording_stop(_, getRegister(_, argument, "arobase", Register.Flags.CanReadWriteMacros))),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.history.redo",
(_) => _.runAsync((_) => redo()),
CommandDescriptor.Flags.None,
),
new CommandDescriptor(
"dance.history.redo.selections",
(_) => _.runAsync((_) => redo_selections()),
CommandDescriptor.Flags.None,
),
new CommandDescriptor(
"dance.history.repeat",
(_, argument) => _.runAsync((_) => repeat(_, getRepetitions(_, argument), argument.include)),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.history.repeat.edit",
(_, argument) => _.runAsync((_) => repeat_edit(_, getRepetitions(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.history.undo",
(_) => _.runAsync((_) => undo()),
CommandDescriptor.Flags.None,
),
new CommandDescriptor(
"dance.history.undo.selections",
(_) => _.runAsync((_) => undo_selections()),
CommandDescriptor.Flags.None,
),
new CommandDescriptor(
"dance.history.repeat.seek",
(_, argument) => _.runAsync(() => commands([".history.repeat", { include: "dance\\.seek\\..+", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.history.repeat.selection",
(_, argument) => _.runAsync(() => commands([".history.repeat", { include: "dance\\.(seek\|select\|selections)\\..+", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "keybindings" module and returns its defined commands.
*/
async function loadKeybindingsModule(): Promise<CommandDescriptor[]> {
const {
setup,
} = await import("./keybindings");
return [
new CommandDescriptor(
"dance.keybindings.setup",
(_, argument) => _.runAsync((_) => setup(_, getRegister(_, argument, "dquote", Register.Flags.CanWrite))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
];
}
/**
* Loads the "misc" module and returns its defined commands.
*/
async function loadMiscModule(): Promise<CommandDescriptor[]> {
const {
cancel,
changeInput,
ignore,
openMenu,
run,
selectRegister,
updateCount,
updateRegister,
} = await import("./misc");
return [
new CommandDescriptor(
"dance.cancel",
(_) => _.runAsync((_) => cancel(_.extension)),
CommandDescriptor.Flags.None,
),
new CommandDescriptor(
"dance.changeInput",
(_, argument) => _.runAsync((_) => changeInput(argument.action)),
CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.ignore",
(_) => _.runAsync((_) => ignore()),
CommandDescriptor.Flags.None,
),
new CommandDescriptor(
"dance.openMenu",
(_, argument) => _.runAsync((_) => openMenu(_, getInputOr(argument), argument.menu, argument.prefix, argument.pass, argument.locked, argument.delay)),
CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.run",
(_, argument) => _.runAsync((_) => run(_, getInput(argument), getInputOr(argument), getCount(_, argument), getRepetitions(_, argument), getRegister(_, argument, "null", Register.Flags.None), argument.commands)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selectRegister",
(_, argument) => _.runAsync((_) => selectRegister(_, getInputOr(argument))),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.updateCount",
(_, argument) => _.runAsync((_) => updateCount(_, getCount(_, argument), _.extension, getInputOr(argument), argument.addDigits)),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.updateRegister",
(_, argument) => _.runAsync((_) => updateRegister(_, getRegister(_, argument, "dquote", Register.Flags.CanWrite), argument.copyFrom, getInputOr(argument))),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "modes" module and returns its defined commands.
*/
async function loadModesModule(): Promise<CommandDescriptor[]> {
const {
set,
set_temporarily,
} = await import("./modes");
return [
new CommandDescriptor(
"dance.modes.set",
(_, argument) => _.runAsync((_) => set(_, getInputOr(argument))),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.set.temporarily",
(_, argument) => _.runAsync((_) => set_temporarily(_, getInputOr(argument), getRepetitions(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.insert.after",
(_, argument) => _.runAsync(() => commands([".selections.faceForward" , { record: false, ...argument }], [".modes.set", { input: "insert", ...argument }], [".selections.reduce", { where: "end" , record: false, empty: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.insert.before",
(_, argument) => _.runAsync(() => commands([".selections.faceBackward", { record: false, ...argument }], [".modes.set", { input: "insert", ...argument }], [".selections.reduce", { where: "start", record: false, empty: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.insert.lineEnd",
(_, argument) => _.runAsync(() => commands([".select.lineEnd" , { shift: "jump", ...argument }], [".modes.set", { input: "insert", ...argument }], [".selections.reduce", { where: "end" , record: false, empty: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.insert.lineStart",
(_, argument) => _.runAsync(() => commands([".select.lineStart", { shift: "jump", skipBlank: true, ...argument }], [".modes.set", { input: "insert", ...argument }], [".selections.reduce", { where: "start", record: false, empty: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.set.insert",
(_, argument) => _.runAsync(() => commands([".modes.set", { input: "insert", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.set.normal",
(_, argument) => _.runAsync(() => commands([".modes.set", { input: "normal", ...argument }], ["hideSuggestWidget"])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.set.temporarily.insert",
(_, argument) => _.runAsync(() => commands([".modes.set.temporarily", { input: "insert", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.modes.set.temporarily.normal",
(_, argument) => _.runAsync(() => commands([".modes.set.temporarily", { input: "normal", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "search" module and returns its defined commands.
*/
async function loadSearchModule(): Promise<CommandDescriptor[]> {
const {
next,
search,
selection,
} = await import("./search");
return [
new CommandDescriptor(
"dance.search",
(_, argument) => _.runAsync((_) => search(_, getRegister<[Register.Flags.CanRead, Register.Flags.CanWrite]>(_, argument, "slash", Register.Flags.CanRead | Register.Flags.CanWrite), getRepetitions(_, argument), argument.add, getDirection(argument), argument.interactive, getShift(argument), getInput(argument), getSetInput(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.search.next",
(_, argument) => _.runAsync((_) => next(_, _.document, getRegister(_, argument, "slash", Register.Flags.CanRead), getRepetitions(_, argument), argument.add, getDirection(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.search.selection",
(_, argument) => _.runAsync((_) => selection(_.document, _.selections, getRegister(_, argument, "slash", Register.Flags.CanWrite), argument.smart)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.search.backward",
(_, argument) => _.runAsync(() => commands([".search", { direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.search.backward.extend",
(_, argument) => _.runAsync(() => commands([".search", { direction: -1, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.search.extend",
(_, argument) => _.runAsync(() => commands([".search", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.search.next.add",
(_, argument) => _.runAsync(() => commands([".search.next", { add: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.search.previous",
(_, argument) => _.runAsync(() => commands([".search.next", { direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.search.previous.add",
(_, argument) => _.runAsync(() => commands([".search.next", { direction: -1, add: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.search.selection.smart",
(_, argument) => _.runAsync(() => commands([".search.selection", { smart: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "seek" module and returns its defined commands.
*/
async function loadSeekModule(): Promise<CommandDescriptor[]> {
const {
enclosing,
object,
seek,
word,
} = await import("./seek");
return [
new CommandDescriptor(
"dance.seek",
(_, argument) => _.runAsync((_) => seek(_, getInputOr(argument), getRepetitions(_, argument), getDirection(argument), getShift(argument), argument.include)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.seek.enclosing",
(_, argument) => _.runAsync((_) => enclosing(_, getDirection(argument), getShift(argument), argument.open, argument.pairs)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.seek.object",
(_, argument) => _.runAsync((_) => object(_, getInputOr(argument), argument.inner, argument.where, getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.seek.word",
(_, argument) => _.runAsync((_) => word(_, getRepetitions(_, argument), argument.stopAtEnd, argument.ws, getDirection(argument), getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.seek.askObject",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.end",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ where: "end", ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.end.extend",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ where: "end" , shift: "extend", ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.inner",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ inner: true, ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.inner.end",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ inner: true, where: "end", ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.inner.end.extend",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ inner: true, where: "end" , shift: "extend", ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.inner.start",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ inner: true, where: "start", ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.inner.start.extend",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ inner: true, where: "start", shift: "extend", ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.start",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ where: "start", ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.askObject.start.extend",
(_, argument) => _.runAsync(() => commands([".openMenu", { input: "object", pass: [{ where: "start", shift: "extend", ...argument }], ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.backward",
(_, argument) => _.runAsync(() => commands([".seek", { direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.enclosing.backward",
(_, argument) => _.runAsync(() => commands([".seek.enclosing", { direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.enclosing.extend",
(_, argument) => _.runAsync(() => commands([".seek.enclosing", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.enclosing.extend.backward",
(_, argument) => _.runAsync(() => commands([".seek.enclosing", { shift: "extend", direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.extend",
(_, argument) => _.runAsync(() => commands([".seek", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.extend.backward",
(_, argument) => _.runAsync(() => commands([".seek", { shift: "extend", direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.included",
(_, argument) => _.runAsync(() => commands([".seek", { include: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.included.backward",
(_, argument) => _.runAsync(() => commands([".seek", { include: true, direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.included.extend",
(_, argument) => _.runAsync(() => commands([".seek", { include: true, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.included.extend.backward",
(_, argument) => _.runAsync(() => commands([".seek", { include: true, shift: "extend", direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.word.backward",
(_, argument) => _.runAsync(() => commands([".seek.word", { direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.word.extend",
(_, argument) => _.runAsync(() => commands([".seek.word", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.word.extend.backward",
(_, argument) => _.runAsync(() => commands([".seek.word", { shift: "extend", direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.word.ws",
(_, argument) => _.runAsync(() => commands([".seek.word", { ws: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.word.ws.backward",
(_, argument) => _.runAsync(() => commands([".seek.word", { ws: true, direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.word.ws.extend",
(_, argument) => _.runAsync(() => commands([".seek.word", { ws: true, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.word.ws.extend.backward",
(_, argument) => _.runAsync(() => commands([".seek.word", { ws: true, shift: "extend", direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.wordEnd",
(_, argument) => _.runAsync(() => commands([".seek.word", { stopAtEnd: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.wordEnd.extend",
(_, argument) => _.runAsync(() => commands([".seek.word", { stopAtEnd: true , shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.wordEnd.ws",
(_, argument) => _.runAsync(() => commands([".seek.word", { stopAtEnd: true , ws: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.seek.wordEnd.ws.extend",
(_, argument) => _.runAsync(() => commands([".seek.word", { stopAtEnd: true , ws: true, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "select" module and returns its defined commands.
*/
async function loadSelectModule(): Promise<CommandDescriptor[]> {
const {
buffer,
firstVisibleLine,
horizontally,
lastLine,
lastVisibleLine,
lineEnd,
lineStart,
line_above,
line_above_extend,
line_below,
line_below_extend,
middleVisibleLine,
to,
vertically,
} = await import("./select");
return [
new CommandDescriptor(
"dance.select.buffer",
(_) => _.runAsync((_) => buffer(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.firstVisibleLine",
(_, argument) => _.runAsync((_) => firstVisibleLine(_, getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.horizontally",
(_, argument) => _.runAsync((_) => horizontally(_, argument.avoidEol, getRepetitions(_, argument), getDirection(argument), getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.lastLine",
(_, argument) => _.runAsync((_) => lastLine(_, _.document, getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.lastVisibleLine",
(_, argument) => _.runAsync((_) => lastVisibleLine(_, getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.line.above",
(_, argument) => _.runAsync((_) => line_above(_, getCount(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.line.above.extend",
(_, argument) => _.runAsync((_) => line_above_extend(_, getCount(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.line.below",
(_, argument) => _.runAsync((_) => line_below(_, getCount(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.line.below.extend",
(_, argument) => _.runAsync((_) => line_below_extend(_, getCount(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.lineEnd",
(_, argument) => _.runAsync((_) => lineEnd(_, getCount(_, argument), getShift(argument), argument.lineBreak)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.lineStart",
(_, argument) => _.runAsync((_) => lineStart(_, getCount(_, argument), getShift(argument), argument.skipBlank)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.middleVisibleLine",
(_, argument) => _.runAsync((_) => middleVisibleLine(_, getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.to",
(_, argument) => _.runAsync((_) => to(_, getCount(_, argument), argument, getShift(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.vertically",
(_, argument) => _.runAsync((_) => vertically(_, _.selections, argument.avoidEol, getRepetitions(_, argument), getDirection(argument), getShift(argument), argument.by)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.select.documentEnd.extend",
(_, argument) => _.runAsync(() => commands([".select.lineEnd", { count: 2147483647, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.documentEnd.jump",
(_, argument) => _.runAsync(() => commands([".select.lineEnd", { count: 2147483647, shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.down.extend",
(_, argument) => _.runAsync(() => commands([".select.vertically", { direction: 1, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.down.jump",
(_, argument) => _.runAsync(() => commands([".select.vertically", { direction: 1, shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.firstLine.extend",
(_, argument) => _.runAsync(() => commands([".select.lineStart", { count: 0, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.firstLine.jump",
(_, argument) => _.runAsync(() => commands([".select.lineStart", { count: 0, shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.firstVisibleLine.extend",
(_, argument) => _.runAsync(() => commands([".select.firstVisibleLine", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.firstVisibleLine.jump",
(_, argument) => _.runAsync(() => commands([".select.firstVisibleLine", { shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lastLine.extend",
(_, argument) => _.runAsync(() => commands([".select.lastLine", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lastLine.jump",
(_, argument) => _.runAsync(() => commands([".select.lastLine", { shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lastVisibleLine.extend",
(_, argument) => _.runAsync(() => commands([".select.lastVisibleLine", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lastVisibleLine.jump",
(_, argument) => _.runAsync(() => commands([".select.lastVisibleLine", { shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.left.extend",
(_, argument) => _.runAsync(() => commands([".select.horizontally", { direction: -1, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.left.jump",
(_, argument) => _.runAsync(() => commands([".select.horizontally", { direction: -1, shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lineEnd.extend",
(_, argument) => _.runAsync(() => commands([".select.lineEnd", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lineStart.extend",
(_, argument) => _.runAsync(() => commands([".select.lineStart", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lineStart.jump",
(_, argument) => _.runAsync(() => commands([".select.lineStart", { shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lineStart.skipBlank.extend",
(_, argument) => _.runAsync(() => commands([".select.lineStart", { skipBlank: true, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.lineStart.skipBlank.jump",
(_, argument) => _.runAsync(() => commands([".select.lineStart", { skipBlank: true, shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.middleVisibleLine.extend",
(_, argument) => _.runAsync(() => commands([".select.middleVisibleLine", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.middleVisibleLine.jump",
(_, argument) => _.runAsync(() => commands([".select.middleVisibleLine", { shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.right.extend",
(_, argument) => _.runAsync(() => commands([".select.horizontally", { direction: 1, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.right.jump",
(_, argument) => _.runAsync(() => commands([".select.horizontally", { direction: 1, shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.to.extend",
(_, argument) => _.runAsync(() => commands([".select.to", { shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.to.jump",
(_, argument) => _.runAsync(() => commands([".select.to", { shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.up.extend",
(_, argument) => _.runAsync(() => commands([".select.vertically", { direction: -1, shift: "extend", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.select.up.jump",
(_, argument) => _.runAsync(() => commands([".select.vertically", { direction: -1, shift: "jump", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "selections" module and returns its defined commands.
*/
async function loadSelectionsModule(): Promise<CommandDescriptor[]> {
const {
changeDirection,
copy,
expandToLines,
filter,
merge,
open,
pipe,
reduce,
restore,
restore_withCurrent,
save,
saveText,
select,
split,
splitLines,
toggleIndices,
trimLines,
trimWhitespace,
} = await import("./selections");
return [
new CommandDescriptor(
"dance.selections.changeDirection",
(_, argument) => _.runAsync((_) => changeDirection(_, getDirection(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.copy",
(_, argument) => _.runAsync((_) => copy(_, _.document, _.selections, getRepetitions(_, argument), getDirection(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.expandToLines",
(_) => _.runAsync((_) => expandToLines(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.filter",
(_, argument) => _.runAsync((_) => filter(_, getInput(argument), getSetInput(argument), argument.defaultInput, argument.inverse, argument.interactive, getCount(_, argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.merge",
(_) => _.runAsync((_) => merge(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.open",
(_) => _.runAsync((_) => open(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.pipe",
(_, argument) => _.runAsync((_) => pipe(_, getRegister(_, argument, "pipe", Register.Flags.CanWrite), getInputOr(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.reduce",
(_, argument) => _.runAsync((_) => reduce(_, argument.where, argument.empty)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.restore",
(_, argument) => _.runAsync((_) => restore(_, getRegister(_, argument, "caret", Register.Flags.CanReadSelections))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.restore.withCurrent",
(_, argument) => _.runAsync((_) => restore_withCurrent(_, _.document, getRegister(_, argument, "caret", Register.Flags.CanReadSelections), argument.reverse)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.save",
(_, argument) => _.runAsync((_) => save(_, _.document, _.selections, getRegister(_, argument, "caret", Register.Flags.CanWriteSelections), argument.style, argument.until, argument.untilDelay)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.saveText",
(_, argument) => _.runAsync((_) => saveText(_.document, _.selections, getRegister(_, argument, "dquote", Register.Flags.CanWrite))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.select",
(_, argument) => _.runAsync((_) => select(_, argument.interactive, getInput(argument), getSetInput(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.split",
(_, argument) => _.runAsync((_) => split(_, argument.excludeEmpty, argument.interactive, getInput(argument), getSetInput(argument))),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.splitLines",
(_, argument) => _.runAsync((_) => splitLines(_, _.document, _.selections, getRepetitions(_, argument), argument.excludeEol)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.toggleIndices",
(_, argument) => _.runAsync((_) => toggleIndices(_, argument.display, argument.until)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.trimLines",
(_) => _.runAsync((_) => trimLines(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.trimWhitespace",
(_) => _.runAsync((_) => trimWhitespace(_)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.clear.main",
(_, argument) => _.runAsync(() => commands([".selections.filter", { input: "i !== count", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.clear.secondary",
(_, argument) => _.runAsync(() => commands([".selections.filter", { input: "i === count", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.copy.above",
(_, argument) => _.runAsync(() => commands([".selections.copy", { direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.faceBackward",
(_, argument) => _.runAsync(() => commands([".selections.changeDirection", { direction: -1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.faceForward",
(_, argument) => _.runAsync(() => commands([".selections.changeDirection", { direction: 1, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.filter.regexp",
(_, argument) => _.runAsync(() => commands([".selections.filter", { defaultInput: "/", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.filter.regexp.inverse",
(_, argument) => _.runAsync(() => commands([".selections.filter", { defaultInput: "/", inverse: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.hideIndices",
(_, argument) => _.runAsync(() => commands([".selections.toggleIndices", { display: false, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.pipe.append",
(_, argument) => _.runAsync(() => commands([".selections.pipe"], [".edit.insert", { register: "|", where: "end", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.pipe.prepend",
(_, argument) => _.runAsync(() => commands([".selections.pipe"], [".edit.insert", { register: "|", where: "start", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.pipe.replace",
(_, argument) => _.runAsync(() => commands([".selections.pipe"], [".edit.insert", { register: "|", ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.reduce.edges",
(_, argument) => _.runAsync(() => commands([".selections.reduce", { where: "both", empty: false, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.showIndices",
(_, argument) => _.runAsync(() => commands([".selections.toggleIndices", { display: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "selections.rotate" module and returns its defined commands.
*/
async function loadSelectionsRotateModule(): Promise<CommandDescriptor[]> {
const {
both,
contents,
selections,
} = await import("./selections.rotate");
return [
new CommandDescriptor(
"dance.selections.rotate.both",
(_, argument) => _.runAsync((_) => both(_, getRepetitions(_, argument), argument.reverse)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.rotate.contents",
(_, argument) => _.runAsync((_) => contents(_, getRepetitions(_, argument), argument.reverse)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.rotate.selections",
(_, argument) => _.runAsync((_) => selections(_, getRepetitions(_, argument), argument.reverse)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
new CommandDescriptor(
"dance.selections.rotate.both.reverse",
(_, argument) => _.runAsync(() => commands([".selections.rotate.both", { reverse: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.rotate.contents.reverse",
(_, argument) => _.runAsync(() => commands([".selections.rotate.contents", { reverse: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
new CommandDescriptor(
"dance.selections.rotate.selections.reverse",
(_, argument) => _.runAsync(() => commands([".selections.rotate.selections", { reverse: true, ...argument }])),
CommandDescriptor.Flags.RequiresActiveEditor | CommandDescriptor.Flags.DoNotReplay,
),
];
}
/**
* Loads the "view" module and returns its defined commands.
*/
async function loadViewModule(): Promise<CommandDescriptor[]> {
const {
line,
} = await import("./view");
return [
new CommandDescriptor(
"dance.view.line",
(_, argument) => _.runAsync((_) => line(_, argument.at)),
CommandDescriptor.Flags.RequiresActiveEditor,
),
];
}
/**
* Loads and returns all defined commands.
*/
export async function loadCommands(): Promise<Commands> {
const allModules = await Promise.all([
loadDevModule(),
loadEditModule(),
loadHistoryModule(),
loadKeybindingsModule(),
loadMiscModule(),
loadModesModule(),
loadSearchModule(),
loadSeekModule(),
loadSelectModule(),
loadSelectionsModule(),
loadSelectionsRotateModule(),
loadViewModule(),
]);
return Object.freeze(
Object.fromEntries(allModules.flat().map((desc) => [desc.identifier, desc])),
);
} | the_stack |
import { Component, State, Element, h } from '@stencil/core';
import '@visa/visa-charts-data-table';
import '@visa/keyboard-instructions';
@Component({
tag: 'app-alluvial-diagram',
styleUrl: 'app-alluvial-diagram.scss'
})
export class AppAlluvialDiagram {
@State() highestHeadingLevel: string | number = 'h3';
@State() data1: any;
@State() data2: any;
@State() data3: any;
@State() nodes: any;
@State() colorsArray: any = ['#E4E4E4', '#E4E4E4', '#E4E4E4', '#78029D', '#E4E4E4'];
@State() colors: any = ['#E4E4E4', '#E4E4E4', '#E4E4E4', '#D90000']; //['#2e3047', '#43455c', '#3c3f58']
@State() fillNodeConfig: any = false;
@State() compareNodeConfig: any = false;
@State() visibleLinkConfig: any = true;
@State() fillModeLinkConfig: any = 'group';
@State() opacityLinkConfig: any = 0.3;
@State() linkConfig: any = {
visible: this.visibleLinkConfig,
// fillMode: 'source',
fillMode: 'group',
opacity: 0.6
};
@State() nodeConfig: any = {
width: 15,
alignment: 'center',
padding: 10,
compare: this.compareNodeConfig,
fill: this.fillNodeConfig
};
@State() interactionKeys: any = ['group'];
@State() fillState: any = 'new';
@State() linkVisibilityState: any = true;
@State() stateTrigger: any = 0;
@State() width: number = 400;
@State() hoverElement: any = '';
@State() chartUpdates: string;
@State() barIntervalRatio = 0.15;
@State() padding: any = {
top: 50,
left: 140,
right: 110,
bottom: 50
};
@State() uniqueID: string = 'thisIsUnique';
@State() dataLabel: any = {
visible: true,
placement: 'auto',
labelAccessor: 'value',
format: '0.0a',
collisionHideOnly: false,
collisionPlacement: 'inside'
};
@State() tooltipLabel: any = {
labelAccessor: ['value'],
labelTitle: ['value'],
format: ['0,0[.0][a]']
};
// @State() clickElement: any = [];
@State() clickElement: any = [{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }];
@State() interactionState: any = ['group'];
@State() valueAccessor: any = 'value';
@State() groupAccessor: any = 'region';
@State() ordinalAccessor: any = 'country';
@State() hoverElementTest: any = '';
@State() clickElementTest: any = [];
@State() animations: any = { disabled: true };
@State() accessibility: any = {
elementDescriptionAccessor: 'note', // see Indonesia above
longDescription: 'An alluvial diagram which shows the movement of groups between 2018 and 2019.',
contextExplanation: 'This chart is standalone, and can be manipulated by the preceding buttons.',
executiveSummary: 'Medium is now the largest category in 2019.',
purpose: 'Examines the flow of groups, between cateogries, over years.',
structureNotes:
'The categories are sorted from high to low, with new at the bottom. Links are used to visualize the population of the group moving between categories year over year.',
statisticalNotes: 'Count of group members.',
onChangeFunc: d => {
this.onChangeFunc(d);
},
hideDataTableButton: true,
elementsAreInterface: true,
disableValidation: true
};
hoverStyle: any = {
color: '#979db7',
strokeWidth: 1.5
};
clickStyle: any = {
color: '#8fdfff',
strokeWidth: 2
};
// colors: any = ['#2e3047', '#43455c', '#3c3f58'];
// colors: any = ['#EDEEF3', '#A8AABB', '#6C6E86', '#3c3f58'];
linkStartData: any = [
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
];
dataStorage1: any = [
this.linkStartData,
[
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 301 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 275 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 281 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 1271 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 618 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 113 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 616 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 314 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 364 }
],
[
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 9091 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 681 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3681 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
],
[
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 9091 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 681 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3681 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
],
[
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 9091 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 681 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3681 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
],
[
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
],
[
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
],
[
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
]
// new column on
// [
// { group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
// { group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
// { group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
// { group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
// { group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
// { group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
// { group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
// // { group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 1133 },
// { group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
// { group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
// { group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
// { group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 },
// { group: 'Increased', source: 'Low 2019', target: 'High 2020', value: 3148 },
// { group: 'Decreased', source: 'High 2019', target: 'Medium 2020', value: 1279 },
// { group: 'New', source: 'Medium 2019', target: 'Low 2020', value: 3684 },
// ]
// [
// { group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
// { group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
// { group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
// { group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
// { group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
// { group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
// { group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
// { group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 1133 },
// { group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
// { group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
// { group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
// { group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
// ],
// [
// { group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
// { group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
// { group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
// { group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
// { group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
// { group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
// { group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
// { group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 1133 },
// { group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
// { group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
// { group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
// { group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
// ],
// [
// { group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
// { group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
// { group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
// { group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
// { group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
// { group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
// { group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
// { group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 1133 },
// { group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
// { group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
// { group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
// { group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
// ],
// this.linkStartData
];
dataStorage2: any = [
this.linkStartData,
[
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 },
{ group: 'Increased', source: 'Low 2019', target: 'High 2020', value: 3148 },
{ group: 'Decreased', source: 'High 2019', target: 'Medium 2020', value: 1279 },
{ group: 'Decreased', source: 'Medium 2019', target: 'Low 2020', value: 3684 },
{ group: 'Decreased', source: 'Medium 2019', target: 'High 2020', value: 2684 }
],
this.linkStartData,
[
{ group: 'Remained', source: 'test', target: 'High 2018', value: 3010 },
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
],
this.linkStartData,
[
{ group: 'Remained', source: 'test', target: 'High 2018', value: 3010 },
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 },
{ group: 'Increased', source: 'Low 2019', target: 'High 2020', value: 3148 },
{ group: 'Decreased', source: 'High 2019', target: 'Medium 2020', value: 1279 },
{ group: 'Decreased', source: 'Medium 2019', target: 'Low 2020', value: 3684 },
{ group: 'Decreased', source: 'Medium 2019', target: 'High 2020', value: 2684 }
]
];
dataStorage3: any = [
this.linkStartData,
[
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 },
{ group: 'Increased', source: 'Low 2019', target: 'new', value: 3148 },
{ group: 'Decreased', source: 'High 2019', target: 'new', value: 1279 },
{ group: 'Decreased', source: 'Medium 2019', target: 'new', value: 3684 },
{ group: 'Decreased', source: 'Medium 2019', target: 'new', value: 2684 },
{ group: 'Increased', source: 'new', target: 'High 2020', value: 3148 },
{ group: 'Decreased', source: 'new', target: 'Medium 2020', value: 1279 },
{ group: 'Decreased', source: 'new', target: 'Low 2020', value: 3684 },
{ group: 'Decreased', source: 'new', target: 'High 2020', value: 2684 }
],
this.linkStartData,
[
{ group: 'Decreased', source: 'High 2016', target: 'Low 2017', value: 1234 },
{ group: 'Remained', source: 'Medium 2016', target: 'Medium 2017', value: 2010 },
{ group: 'Decreased', source: 'High 2017', target: 'Low 2018', value: 1234 },
{ group: 'Remained', source: 'Medium 2017', target: 'Medium 2018', value: 2010 },
{ group: 'Increased', source: 'Low 2017', target: 'Medium 2018', value: 1234 },
{ group: 'Decreased', source: 'High 2017', target: 'Medium 2018', value: 3010 },
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
],
[
{ group: 'Decreased', source: 'High 2017', target: 'Low 2018', value: 1234 },
{ group: 'Remained', source: 'Medium 2017', target: 'Medium 2018', value: 2010 },
{ group: 'Increased', source: 'Low 2017', target: 'Medium 2018', value: 1234 },
{ group: 'Decreased', source: 'High 2017', target: 'Medium 2018', value: 3010 },
{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 },
{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 },
{ group: 'Decreased', source: 'High 2018', target: 'Low 2019', value: 2812 },
{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 },
{ group: 'Remained', source: 'Medium 2018', target: 'Medium 2019', value: 12712 },
{ group: 'Decreased', source: 'Medium 2018', target: 'Low 2019', value: 3367 },
{ group: 'Increased', source: 'Low 2018', target: 'High 2019', value: 68 },
{ group: 'Increased', source: 'Low 2018', target: 'Medium 2019', value: 8133 },
{ group: 'Remained', source: 'Low 2018', target: 'Low 2019', value: 6164 },
{ group: 'New', source: 'New 2018', target: 'High 2019', value: 3148 },
{ group: 'New', source: 'New 2018', target: 'Medium 2019', value: 7279 },
{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }
]
];
// nodeStartData: any = [
// { did: 'High 2018' },
// { did: 'Medium 2018' },
// { did: 'Low 2018' },
// { did: 'New 2018' },
// { did: 'High 2019' },
// { did: 'Medium 2019' },
// { did: 'Low 2019' }
// ];
// nodeDataStorage: any = [
// this.nodeStartData,
// // this.nodeStartData,
// // this.nodeStartData,
// // this.nodeStartData,
// // [
// // { did: 'High 2018' },
// // { did: 'Medium 2018' },
// // { did: 'Low 2018' },
// // { did: 'New 2018' },
// // { did: 'High 2019' },
// // { did: 'Low 2019' }
// // ],
// // this.nodeStartData,
// // new column on far right
// [
// { did: 'High 2018' },
// { did: 'Medium 2018' },
// { did: 'Low 2018' },
// { did: 'New 2018' },
// { did: 'High 2019' },
// { did: 'Medium 2019' },
// { did: 'Low 2019' },
// { did: 'High 2020' },
// { did: 'Medium 2020' },
// { did: 'Low 2020' },
// ],
// [
// { did: 'High 2018' },
// { did: 'Medium 2018' },
// { did: 'Low 2018' },
// { did: 'New 2018' },
// { did: 'High 2019' },
// { did: 'Medium 2019' },
// { did: 'Low 2019' },
// { did: 'Nothing' },
// { did: 'High 2020' },
// { did: 'Medium 2020' },
// { did: 'Low 2020' },
// ],
// [
// { did: 'High 2018' },
// { did: 'Medium 2018' },
// { did: 'Low 2018' },
// { did: 'New 2018' },
// { did: 'High 2019' },
// { did: 'Medium 2019' },
// { did: 'Low 2019' },
// { did: 'High 2020' },
// { did: 'Medium 2020' },
// { did: 'Low 2020' },
// ],
// this.nodeStartData
// ];
@Element()
appEl: HTMLElement;
componentWillLoad() {
this.data1 = this.dataStorage1[this.stateTrigger];
this.data2 = this.dataStorage2[this.stateTrigger];
this.data3 = this.dataStorage3[this.stateTrigger];
// this.nodes = this.nodeDataStorage[this.stateTrigger];
}
onClickFunc(ev) {
const d = ev.detail;
if (d) {
const newClicks = [...this.clickElement];
const index = this.clickElement.findIndex(o => {
let conditionsMet = false;
conditionsMet = o.index === d.index ? true : false;
// console.log('test', o.index);
return conditionsMet;
});
if (index > -1) {
newClicks.splice(index, 1);
} else {
newClicks.push(d);
}
this.clickElement = newClicks;
// console.log('newClicks', this.clickElement);
}
}
onHoverFunc(d) {
this.hoverElement = d.detail;
}
onMouseOut() {
this.hoverElement = '';
}
onChangeFunc(d) {
if (d.updated && (d.removed || d.added)) {
let updates = 'The bar chart has ';
if (d.removed) {
updates += 'removed ' + d.removed + ' bar' + (d.removed > 1 ? 's ' : ' ');
}
if (d.added) {
updates += (d.removed ? 'and ' : '') + 'added ' + d.added + (d.removed ? '' : d.added > 1 ? ' bars' : ' bar');
}
this.chartUpdates = updates;
} else if (d.updated) {
const newUpdate = "The chart's data has changed, but no bars were removed or added.";
this.chartUpdates =
newUpdate !== this.chartUpdates
? newUpdate
: "The chart's data has changed again, but no bars were removed or added.";
} else {
const newUpdate = "The chart's has updated, but no change to the data was made.";
this.chartUpdates =
newUpdate !== this.chartUpdates
? newUpdate
: "The chart's has updated again, but no change to the data was made.";
}
}
changeData(act) {
setTimeout(() => {
if (this.uniqueID !== 'POTENTIALLY_BUGGY_ID_CHANGE') {
this.uniqueID = 'POTENTIALLY_BUGGY_ID_CHANGE';
}
}, 10000);
const selectedActData = this['dataStorage' + act];
this.stateTrigger = this.stateTrigger < selectedActData.length - 1 ? this.stateTrigger + 1 : 0;
this['data' + act] = selectedActData[this.stateTrigger];
// this.nodes = this.nodeDataStorage[this.stateTrigger];
}
changeShowLinks() {
this.visibleLinkConfig = this.visibleLinkConfig !== true ? true : false;
this.fillNodeConfig = this.fillNodeConfig ? false : true;
}
changeCompareNodes() {
this.compareNodeConfig = this.compareNodeConfig ? false : true;
}
// changeLinkFillMode() {
// this.fillModeLinkConfig = this.fillModeLinkConfig === 'group' ? 'source' : 'group';
// }
changeLinkColor(band, toggleLinks) {
if (toggleLinks) {
this.visibleLinkConfig = this.visibleLinkConfig ? false : true;
this.linkVisibilityState = this.visibleLinkConfig;
this.fillNodeConfig = this.fillNodeConfig ? false : true;
}
if (band) {
band === 'increased'
? (this.fillState = 'increased')
: band === 'decreased'
? (this.fillState = 'decreased')
: band === 'remained'
? (this.fillState = 'remained')
: (this.fillState = 'new');
}
if (!this.linkVisibilityState) {
if (this.fillState === 'increased') {
this.colorsArray = ['#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#0051dc', '#0051dc'];
this.clickElement = [{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 }];
} else if (this.fillState === 'decreased') {
this.colorsArray = ['#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#D90000', '#E4E4E4', '#E4E4E4'];
this.clickElement = [{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 }];
} else if (this.fillState === 'remained') {
this.colorsArray = ['#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4'];
this.clickElement = [{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 }];
} else if (this.fillState === 'new') {
this.colorsArray = ['#E4E4E4', '#E4E4E4', '#E4E4E4', '#78029D', '#E4E4E4', '#E4E4E4', '#E4E4E4'];
this.clickElement = [{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }];
}
} else if (this.linkVisibilityState) {
if (this.fillState === 'increased') {
this.colorsArray = ['#E4E4E4', '#E4E4E4', '#0051dc', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4'];
this.clickElement = [{ group: 'Increased', source: 'Medium 2018', target: 'High 2019', value: 909 }];
} else if (this.fillState === 'decreased') {
this.colorsArray = ['#E4E4E4', '#D90000', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4'];
this.clickElement = [{ group: 'Decreased', source: 'High 2018', target: 'Medium 2019', value: 2754 }];
} else if (this.fillState === 'remained') {
this.colorsArray = ['#767676', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4', '#E4E4E4'];
this.clickElement = [{ group: 'Remained', source: 'High 2018', target: 'High 2019', value: 3010 }];
} else if (this.fillState === 'new') {
this.colorsArray = ['#E4E4E4', '#E4E4E4', '#E4E4E4', '#78029D', '#E4E4E4', '#E4E4E4', '#E4E4E4'];
this.clickElement = [{ group: 'New', source: 'New 2018', target: 'Low 2019', value: 3684 }];
}
}
}
changeDimension() {
this.padding =
this.padding.left === 60
? {
top: 50,
left: 150,
right: 180,
bottom: 40
}
: {
top: 50,
left: 60,
right: 30,
bottom: 40
};
this.width = this.width === 800 ? 700 : 800;
}
changeLabels() {
if (this.dataLabel.placement === 'inside') {
this.dataLabel = {
visible: true, // !this.dataLabel.visible,
placement: 'outside',
labelAccessor: 'value',
format: '0.0[a]'
};
this.padding = {
top: 50,
left: 140,
right: 110,
bottom: 50
};
} else {
this.dataLabel = {
visible: true, // !this.dataLabel.visible,
placement: 'inside',
labelAccessor: 'value',
format: '0.0[a]'
};
this.padding = {
top: 50,
left: 10,
right: 10,
bottom: 50
};
}
}
changeTooltip() {
this.tooltipLabel = { labelAccessor: ['value', 'test'], labelTitle: ['', ''], format: ['0,0[.0][a]', ''] };
}
changeInteraction() {
// this.valueAccessor !== 'value' ? (this.valueAccessor = 'value') : (this.valueAccessor = 'otherValue');
this.interactionState = this.interactionState[0] !== ['did'] ? ['did'] : ['source'];
console.log(this.interactionState);
}
changeValueAccessor() {
// this.valueAccessor !== 'value' ? (this.valueAccessor = 'value') : (this.valueAccessor = 'otherValue');
this.valueAccessor = this.valueAccessor !== 'value' ? 'value' : 'otherValue';
}
changeGroupAccessor() {
// this.valueAccessor !== 'value' ? (this.valueAccessor = 'value') : (this.valueAccessor = 'otherValue');
this.groupAccessor = this.groupAccessor !== 'region' ? 'region' : null;
}
changeInteractionKey() {
this.interactionState = this.interactionState[0] === ['group'] ? ['source'] : ['group'];
}
toggleTextures() {
const newAccess = { ...this.accessibility };
newAccess.hideTextures = !newAccess.hideTextures;
this.accessibility = newAccess;
}
toggleSmallLabels() {
const newAccess = { ...this.accessibility };
newAccess.showSmallLabels = !newAccess.showSmallLabels;
this.accessibility = newAccess;
}
onTestClickFunc(d) {
const index = this.clickElementTest.indexOf(d);
const newClicks = [...this.clickElementTest];
if (index > -1) {
newClicks.splice(index, 1);
} else {
newClicks.push(d);
}
this.clickElementTest = newClicks;
}
onTestHoverFunc(d) {
this.hoverElementTest = d;
}
onTestMouseOut() {
this.hoverElementTest = '';
}
handleInput = e => {
e.preventDefault();
this.highestHeadingLevel = e.cat[0].value;
};
render() {
return (
<div>
{/* <div role="alert" aria-live="polite"> */}
<p>{this.chartUpdates}</p>
<div>
<h4>I. Basic Links</h4>
<button
onClick={() => {
this.changeData(1);
}}
>
change data
</button>
<button
onClick={() => {
this.changeCompareNodes();
}}
>
toggle CompareNodes
</button>
<button
onClick={() => {
this.changeLabels();
}}
>
change label placement
</button>
<button
onClick={() => {
this.changeShowLinks();
}}
>
hide links
</button>
<button
onClick={() => {
this.changeInteractionKey();
}}
>
TEST change interaction key
</button>
<alluvial-diagram
linkData={this.data1}
// nodeData={this.nodes}
width={500}
height={450}
padding={this.padding}
colors={this.colors}
sourceAccessor={'source'}
targetAccessor={'target'}
valueAccessor={'value'}
groupAccessor={'group'}
linkConfig={this.linkConfig}
nodeConfig={this.nodeConfig}
nodeIDAccessor={'did'}
mainTitle={''}
subTitle={''}
dataLabel={this.dataLabel}
// interactionKeys={this.interactionState}
interactionKeys={this.interactionKeys}
hoverOpacity={0.2}
showTooltip={false}
hoverHighlight={this.hoverElement}
clickHighlight={this.clickElement}
onClickFunc={d => this.onClickFunc(d)}
onHoverFunc={d => this.onHoverFunc(d)}
onMouseOutFunc={() => this.onMouseOut()}
clickStyle={this.clickStyle}
// animationConfig={this.animations}
/>
</div>
<div>
<h4>II. New Columns on Edge</h4>
<button
onClick={() => {
this.changeData(2);
}}
>
change data
</button>
<button
onClick={() => {
this.changeCompareNodes();
}}
>
toggle CompareNodes
</button>
<button
onClick={() => {
this.changeLabels();
}}
>
change label placement
</button>
<alluvial-diagram
linkData={this.data2}
// nodeData={this.nodes}
width={500}
height={450}
padding={this.padding}
colors={['#717171']}
sourceAccessor={'source'}
targetAccessor={'target'}
valueAccessor={'value'}
groupAccessor={'group'}
linkConfig={{
...{
visible: this.visibleLinkConfig,
// fillMode: 'source',
fillMode: 'none',
opacity: 0.5
}
}}
nodeConfig={{
...{
width: 15,
alignment: 'center',
padding: 10,
compare: this.compareNodeConfig,
fill: this.fillNodeConfig
}
}}
nodeIDAccessor={'did'}
mainTitle={''}
subTitle={''}
dataLabel={this.dataLabel}
interactionKeys={this.interactionState}
hoverOpacity={0.2}
showTooltip={false}
hoverHighlight={this.hoverElement}
clickHighlight={this.clickElement}
onClickFunc={d => this.onClickFunc(d)}
onHoverFunc={d => this.onHoverFunc(d)}
onMouseOutFunc={() => this.onMouseOut()}
/>
</div>
<div>
<h4>III. New Node between Nodes</h4>
<button
onClick={() => {
this.changeData(3);
}}
>
change data
</button>
<button
onClick={() => {
this.changeCompareNodes();
}}
>
toggle CompareNodes
</button>
<button
onClick={() => {
this.changeLabels();
}}
>
change label placement
</button>
<alluvial-diagram
linkData={this.data3}
// nodeData={this.nodes}
width={500}
height={450}
padding={this.padding}
// colors={['#717171']}
sourceAccessor={'source'}
targetAccessor={'target'}
valueAccessor={'value'}
groupAccessor={'group'}
linkConfig={{
...{
visible: this.visibleLinkConfig,
fillMode: 'source',
// fillMode: 'none',
opacity: 0.8
}
}}
nodeConfig={{
...{
width: 15,
alignment: 'center',
padding: 10,
compare: this.compareNodeConfig,
fill: this.fillNodeConfig
}
}}
nodeIDAccessor={'did'}
mainTitle={''}
subTitle={''}
dataLabel={this.dataLabel}
interactionKeys={this.interactionState}
hoverOpacity={0.2}
showTooltip={false}
hoverHighlight={this.hoverElement}
clickHighlight={this.clickElement}
onClickFunc={d => this.onClickFunc(d)}
onHoverFunc={d => this.onHoverFunc(d)}
onMouseOutFunc={() => this.onMouseOut()}
/>
</div>
</div>
);
}
} | the_stack |
import {omit} from './util';
import {getCurrentLine} from './util-stacktrace';
import {attributesWithoutListener, registerListenerAttributes} from './Listeners';
import {toValueString} from './Console';
import Color from './Color';
import Font from './Font';
import * as symbols from './symbols';
import checkType from './checkType';
type AttrConverters = {[attr: string]: (value: any) => any};
interface ElementFn {
new(...args: any[]): any;
(...args: any[]): any;
[symbols.originalComponent]?: ElementFn;
[symbols.jsxType]?: boolean;
}
const COMMON_ATTR: AttrConverters = Object.freeze({
textColor: (value: any) => Color.from(value).toString(),
font: (value: any) => Font.from(value).toString(),
children: (value: any) => {
if (!(value instanceof Array)) {
throw new Error('Not an array: ' + toValueString(value));
}
return value;
}
});
const MARKUP: {[el: string]: AttrConverters} = Object.freeze({
br: {},
b: COMMON_ATTR,
span: COMMON_ATTR,
big: COMMON_ATTR,
i: COMMON_ATTR,
small: COMMON_ATTR,
strong: COMMON_ATTR,
ins: COMMON_ATTR,
del: COMMON_ATTR,
a: Object.assign({
href: (value: any) => {
if (typeof value !== 'string') {
throw new Error('Not a string: ' + toValueString(value));
}
return value;
}
}, COMMON_ATTR)
});
export function createJsxProcessor() {
return new JsxProcessor();
}
export default class JsxProcessor {
createElement(Type: ElementFn | string, attributes?: any, ...children: any[]) {
if (!(Type instanceof Function) && typeof Type !== 'string') {
throw new Error(`JSX: Unsupported type ${toValueString(Type)}`);
}
const typeName = Type instanceof Function ? Type.name : Type;
if (attributes?.children && children && children.length) {
throw new Error(`JSX: Children for type ${typeName} given twice.`);
}
// Children may be part of attributes or given as varargs or both.
// For JSX factories/functional components they should always be part of attributes
const rawChildren = children.length ? children : attributes?.children || [];
const {finalChildren, additionalAttributes} = parseChildren(rawChildren, Type);
const finalAttributes = {...attributes};
joinAttributes(finalAttributes, additionalAttributes, Type);
if (finalChildren) {
finalAttributes.children = finalChildren;
}
if (typeof Type === 'string') {
return this.createIntrinsicElement(Type, finalAttributes);
} else if (Type.prototype && Type.prototype[JSX.jsxFactory]) {
return this.createCustomComponent(Type, finalAttributes);
} else {
return this.createFunctionalComponent(Type, finalAttributes);
}
}
createCustomComponent(Type: ElementFn, attributes: any) {
return Type.prototype[JSX.jsxFactory].call(this, Type, attributes);
}
createFunctionalComponent(Type: ElementFn, attributes: any) {
try {
const result = Type.call(this, attributes);
Type[symbols.jsxType] = true;
if (result instanceof Object) {
result[symbols.jsxType] = Type;
}
return result;
} catch (ex) {
throw new Error(`JSX: "${ex.message}" ${getCurrentLine(ex)}`);
}
}
createIntrinsicElement(el: string, attributes: any) {
if (el in MARKUP) {
const encoded: any = {};
Object.keys(attributes || {}).forEach(attribute => {
const encoder = MARKUP[el][attribute];
if (!encoder) {
if (attribute === 'children') {
throw new Error(`Element "${el}" can not have children`);
} else {
throw new Error(`Element "${el}" does not support attribute "${attribute}"`);
}
}
try {
encoded[attribute] = encoder(attributes[attribute]);
} catch(ex) {
throw new Error(`Element "${el}" attribute "${attribute}" can not bet set: ${ex.message}`);
}
});
const text = joinTextContent(encoded.children, true);
const tagOpen = [el].concat(Object.keys(encoded || {}).filter(attr => attr !== 'children').map(
attribute => `${attribute}='${encoded[attribute]}'`
)).join(' ');
if (text) {
return `<${tagOpen}>${text}</${el}>`;
}
return `<${tagOpen}/>`;
}
throw new Error(`JSX: Unsupported type ${el}`);
}
createNativeObject(Type: any, attributes: any) {
if (attributes && 'children' in attributes) {
throw new Error(`JSX: ${Type.name} can not have children`);
}
const {data, ...properties} = attributesWithoutListener(attributes || {});
const result = new Type(properties);
registerListenerAttributes(result, attributes);
if (data) {
result.data = data;
}
return result;
}
getChildren(attributes: any) {
if (!attributes || !('children' in attributes)) {
return null;
}
return flattenChildren(attributes.children);
}
withoutChildren(attributes: any) {
return omit(attributes, ['children']);
}
withContentText(attributes: any, content: any[], property: string, markupEnabled: boolean) {
if (attributes && attributes[property] && content && content.length) {
throw new Error(`JSX: ${property} given twice`);
}
const text = attributes && attributes[property]
? attributes[property].toString()
: joinTextContent(content || [], markupEnabled);
return Object.assign(attributes || {}, text ? {[property]: text} : {});
}
withContentChildren(attributes: any, content: any[], property: string) {
if (attributes && attributes[property] && content && content.length) {
throw new Error(`JSX: ${property} given twice`);
}
const children = attributes && attributes[property] ? attributes[property] : (content || []);
return Object.assign(attributes || {}, children ? {[property]: children} : {});
}
withShorthands(
attributes: object,
shorthandsMapping: {[attr: string]: string},
merge: ((value1: any, value2: string) => any)
): object {
const shorthandsKeys = Object.keys(shorthandsMapping);
const shorthands = shorthandsKeys.filter(value => value in attributes);
if (!shorthands.length) {
return attributes;
}
const attrCopy: any = omit(attributes, shorthandsKeys);
shorthands.forEach(shorthand => {
const prop = shorthandsMapping[shorthand];
if (prop in attrCopy) {
attrCopy[prop] = merge(attrCopy[prop], shorthand);
} else {
attrCopy[prop] = shorthand;
}
});
return attrCopy;
}
makeFactories(dic: {[key: string]: ElementFn}) {
const result: {[key: string]: ElementFn} = {};
Object.keys(dic).forEach(key => {
result[key] = this.makeFactory(dic[key]) as ElementFn;
});
return result;
}
makeFactory(constructor: ElementFn): ElementFn {
if (arguments.length !== 1) {
throw new Error(`Expected exactly one argument, got ${arguments.length}`);
}
checkType(constructor, Function, 'first parameter');
if (!constructor.prototype || !constructor.prototype[JSX.jsxFactory]) {
throw new Error(`Function ${constructor.name} is not a valid constructor`);
}
if (constructor[symbols.originalComponent]) {
return this.makeFactory(constructor[symbols.originalComponent] as ElementFn);
}
return createFactoryProxy(this, constructor);
}
}
function createFactoryProxy(processor: JsxProcessor, constructor: ElementFn): ElementFn {
const handler: ProxyHandler<ElementFn> = {
apply(target, _thisArg, args) {
const [attributes, functionalComponent] = args;
if (args.length > 1) {
if (!(functionalComponent instanceof Function)) {
throw new TypeError('Second parameter must be a function');
}
if (functionalComponent.prototype && functionalComponent.prototype[JSX.jsxFactory]) {
throw new TypeError('Second parameter must be a factory');
}
}
const result = processor.createElement(proxy, attributes);
if (args.length > 1 && result instanceof Object) {
functionalComponent[JSX.jsxType] = true;
result[JSX.jsxType] = functionalComponent;
}
return result;
},
get(target, property, receiver) {
if (receiver === proxy) {
if (property === symbols.originalComponent) {
return constructor;
}
if (property === symbols.proxyHandler) {
return handler;
}
}
return Reflect.get(target, property, receiver);
}
};
/** @type {Factory} */
const proxy = new Proxy(constructor, handler);
return proxy;
}
/**
* Converts any value to a flat array.
*/
export function flattenChildren(children: unknown) {
if (children instanceof Array) {
let result: any[] = [];
for (const child of children) {
if (child && child.toArray) {
result = result.concat(flattenChildren(child.toArray()));
} else if (child instanceof Array) {
result = result.concat(flattenChildren(child));
} else {
result.push(child);
}
}
return result;
}
return [children];
}
export function joinTextContent(textArray: string[], markupEnabled: boolean) {
if (!textArray) {
return null;
}
if (markupEnabled) {
return textArray
.map(str => str + '')
.join('')
.replace(/\s+/g, ' ')
.replace(/\s*<br\s*\/>\s*/g, '<br/>');
}
return textArray.join('');
}
export const JSX = {
processor: null as JsxProcessor | null,
jsxFactory: symbols.jsxFactory,
jsxType: symbols.jsxType,
install(jsxProcessor: JsxProcessor) {
this.processor = jsxProcessor;
},
createElement() {
return this.processor!.createElement.apply(this.processor, arguments as any);
}
};
function parseChildren(rawChildren: any[], type: ElementFn | string) {
const children = rawChildren?.filter(value => !isAttributesObject(value));
const attributes = rawChildren
?.filter(isAttributesObject)
.reduce((prev, current) => joinAttributes(prev, current, type), {});
return {
finalChildren: children.length ? children : null,
additionalAttributes: omit(attributes, [symbols.jsxType, symbols.setterTargetType])
};
}
function isAttributesObject(value: any): value is {[symbols.setterTargetType]: Function} {
return value instanceof Object && value[symbols.setterTargetType] instanceof Function;
}
function joinAttributes(target: any, source: any, actualTargetType: ElementFn | string): any {
const expectedTargetType = source[symbols.setterTargetType];
const actualTargetTypeFn = typeof actualTargetType === 'string' ? String : actualTargetType;
if (expectedTargetType
&& actualTargetTypeFn.prototype[JSX.jsxFactory] // for SFC we can't know the future instance type
&& (actualTargetTypeFn.prototype !== expectedTargetType.prototype)
&& !(actualTargetTypeFn.prototype instanceof expectedTargetType)
) {
const firstKey = Object.keys(source)[0];
const typeName = actualTargetType instanceof Function
? actualTargetType.name
: actualTargetType;
throw new TypeError(
`Attribute "${firstKey}" is targeting ${expectedTargetType.name}, but is set on ${typeName}`
);
}
Object.keys(source).forEach(key => {
if (key in target) {
if (Array.isArray(target[key]) && Array.isArray(source[key])) {
target[key] = target[key].concat(source[key]);
} else {
throw new Error(`Attribute "${key}" is set multiple times`);
}
} else {
target[key] = source[key];
}
});
return target;
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreSites } from '@services/sites';
import {
AddonCalendar,
AddonCalendarDayName,
AddonCalendarEvent,
AddonCalendarEventBase,
AddonCalendarEventToDisplay,
AddonCalendarEventType,
AddonCalendarGetEventsEvent,
AddonCalendarProvider,
AddonCalendarReminderUnits,
AddonCalendarWeek,
AddonCalendarWeekDay,
} from './calendar';
import { CoreConfig } from '@services/config';
import { CoreUtils } from '@services/utils/utils';
import { CoreCourse } from '@features/course/services/course';
import { ContextLevel, CoreConstants } from '@/core/constants';
import moment from 'moment';
import { makeSingleton } from '@singletons';
import { AddonCalendarSyncInvalidateEvent } from './calendar-sync';
import { AddonCalendarOfflineEventDBRecord } from './database/calendar-offline';
import { CoreCategoryData } from '@features/courses/services/courses';
import { AddonCalendarReminderDBRecord } from './database/calendar';
import { CoreTimeUtils } from '@services/utils/time';
/**
* Context levels enumeration.
*/
export enum AddonCalendarEventIcons {
SITE = 'fas-globe',
CATEGORY = 'fas-cubes',
COURSE = 'fas-graduation-cap',
GROUP = 'fas-users',
USER = 'fas-user',
}
/**
* Service that provides some features regarding lists of courses and categories.
*/
@Injectable({ providedIn: 'root' })
export class AddonCalendarHelperProvider {
protected eventTypeIcons: string[] = [];
/**
* Returns event icon based on event type.
*
* @param eventType Type of the event.
* @return Event icon.
*/
getEventIcon(eventType: AddonCalendarEventType): string {
if (this.eventTypeIcons.length == 0) {
CoreUtils.enumKeys(AddonCalendarEventType).forEach((name) => {
const value = AddonCalendarEventType[name];
this.eventTypeIcons[value] = AddonCalendarEventIcons[name];
});
}
return this.eventTypeIcons[eventType] || '';
}
/**
* Calculate some day data based on a list of events for that day.
*
* @param day Day.
* @param events Events.
*/
calculateDayData(day: AddonCalendarWeekDay, events: AddonCalendarEventToDisplay[]): void {
day.hasevents = events.length > 0;
day.haslastdayofevent = false;
const types = {};
events.forEach((event) => {
types[event.formattedType || event.eventtype] = true;
if (event.islastday) {
day.haslastdayofevent = true;
}
});
day.calendareventtypes = Object.keys(types) as AddonCalendarEventType[];
}
/**
* Check if current user can create/edit events.
*
* @param courseId Course ID. If not defined, site calendar.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean: whether the user can create events.
*/
async canEditEvents(courseId?: number, siteId?: string): Promise<boolean> {
try {
const canEdit = await AddonCalendar.canEditEvents(siteId);
if (!canEdit) {
return false;
}
const types = await AddonCalendar.getAllowedEventTypes(courseId, siteId);
return Object.keys(types).length > 0;
} catch {
return false;
}
}
/**
* Classify events into their respective months and days. If an event duration covers more than one day,
* it will be included in all the days it lasts.
*
* @param events Events to classify.
* @return Object with the classified events.
*/
classifyIntoMonths(
offlineEvents: AddonCalendarOfflineEventDBRecord[],
): { [monthId: string]: { [day: number]: AddonCalendarEventToDisplay[] } } {
// Format data.
const events: AddonCalendarEventToDisplay[] = offlineEvents.map((event) =>
AddonCalendarHelper.formatOfflineEventData(event));
const result = {};
events.forEach((event) => {
const treatedDay = moment(new Date(event.timestart * 1000));
const endDay = moment(new Date((event.timestart + event.timeduration) * 1000));
// Add the event to all the days it lasts.
while (!treatedDay.isAfter(endDay, 'day')) {
const monthId = this.getMonthId(treatedDay);
const day = treatedDay.date();
if (!result[monthId]) {
result[monthId] = {};
}
if (!result[monthId][day]) {
result[monthId][day] = [];
}
result[monthId][day].push(event);
treatedDay.add(1, 'day'); // Treat next day.
}
});
return result;
}
/**
* Convenience function to format some event data to be rendered.
*
* @param event Event to format.
*/
async formatEventData(
event: AddonCalendarEvent | AddonCalendarEventBase | AddonCalendarGetEventsEvent,
): Promise<AddonCalendarEventToDisplay> {
const eventFormatted: AddonCalendarEventToDisplay = {
...event,
location: 'location' in event ? event.location : undefined,
eventcount: 'eventcount' in event ? event.eventcount || 0 : 0,
repeatid: event.repeatid || 0,
eventIcon: this.getEventIcon(event.eventtype),
formattedType: AddonCalendar.getEventType(event),
format: 1,
visible: 1,
offline: false,
};
if (event.modulename) {
eventFormatted.eventIcon = await CoreCourse.getModuleIconSrc(event.modulename);
eventFormatted.moduleIcon = eventFormatted.eventIcon;
eventFormatted.iconTitle = CoreCourse.translateModuleName(event.modulename);
}
eventFormatted.formattedType = AddonCalendar.getEventType(event);
// Calculate context.
if ('course' in event) {
eventFormatted.courseid = event.course?.id;
} else if ('courseid' in event) {
eventFormatted.courseid = event.courseid;
}
// Calculate context.
if ('category' in event) {
eventFormatted.categoryid = event.category?.id;
} else if ('categoryid' in event) {
eventFormatted.categoryid = event.categoryid;
}
if ('canedit' in event) {
eventFormatted.canedit = event.canedit;
}
if ('candelete' in event) {
eventFormatted.candelete = event.candelete;
}
this.formatEventContext(eventFormatted, eventFormatted.courseid, eventFormatted.categoryid);
return eventFormatted;
}
/**
* Convenience function to format some event data to be rendered.
*
* @param e Event to format.
*/
formatOfflineEventData(event: AddonCalendarOfflineEventDBRecord): AddonCalendarEventToDisplay {
const eventFormatted: AddonCalendarEventToDisplay = {
id: event.id,
name: event.name,
timestart: event.timestart,
eventtype: event.eventtype,
categoryid: event.categoryid,
courseid: event.courseid || event.groupcourseid,
groupid: event.groupid,
description: event.description,
location: event.location,
duration: event.duration,
timedurationuntil: event.timedurationuntil,
timedurationminutes: event.timedurationminutes,
// repeat: event.repeat,
eventcount: event.repeats || 0,
repeatid: event.repeatid || 0,
// repeateditall: event.repeateditall,
userid: event.userid,
timemodified: event.timecreated || 0,
eventIcon: this.getEventIcon(event.eventtype),
formattedType: event.eventtype,
format: 1,
visible: 1,
offline: true,
canedit: event.id < 0,
candelete: event.id < 0,
timeduration: 0,
};
// Calculate context.
const categoryId = event.categoryid;
const courseId = event.courseid || event.groupcourseid;
this.formatEventContext(eventFormatted, courseId, categoryId);
if (eventFormatted.duration == 1) {
eventFormatted.timeduration = (event.timedurationuntil || 0) - event.timestart;
} else if (eventFormatted.duration == 2) {
eventFormatted.timeduration = (event.timedurationminutes || 0) * CoreConstants.SECONDS_MINUTE;
} else {
eventFormatted.timeduration = 0;
}
return eventFormatted;
}
/**
* Modifies event data with the context information.
*
* @param eventFormatted Event formatted to be displayed.
* @param courseId Course Id if any.
* @param categoryId Category Id if any.
*/
protected formatEventContext(eventFormatted: AddonCalendarEventToDisplay, courseId?: number, categoryId?: number): void {
if (categoryId && categoryId > 0) {
eventFormatted.contextLevel = ContextLevel.COURSECAT;
eventFormatted.contextInstanceId = categoryId;
} else if (courseId && courseId > 0) {
eventFormatted.contextLevel = ContextLevel.COURSE;
eventFormatted.contextInstanceId = courseId;
} else {
eventFormatted.contextLevel = ContextLevel.USER;
eventFormatted.contextInstanceId = eventFormatted.userid;
}
}
/**
* Format reminders, adding calculated data.
*
* @param reminders Reminders.
* @param timestart Event timestart.
* @param siteId Site ID.
* @return Formatted reminders.
*/
async formatReminders(
reminders: AddonCalendarReminderDBRecord[],
timestart: number,
siteId?: string,
): Promise<AddonCalendarEventReminder[]> {
const defaultTime = await AddonCalendar.getDefaultNotificationTime(siteId);
const formattedReminders = <AddonCalendarEventReminder[]> reminders;
const eventTimestart = timestart;
let defaultTimeValue: number | undefined;
let defaultTimeUnit: AddonCalendarReminderUnits | undefined;
if (defaultTime > 0) {
const data = AddonCalendarProvider.convertSecondsToValueAndUnit(defaultTime);
defaultTimeValue = data.value;
defaultTimeUnit = data.unit;
}
return formattedReminders.map((reminder) => {
if (reminder.time === null) {
// Default time. Check if default notifications are disabled.
if (defaultTimeValue !== undefined && defaultTimeUnit) {
reminder.value = defaultTimeValue;
reminder.unit = defaultTimeUnit;
reminder.timestamp = eventTimestart - reminder.value * reminder.unit;
}
} else {
const data = AddonCalendarProvider.convertSecondsToValueAndUnit(reminder.time);
reminder.value = data.value;
reminder.unit = data.unit;
reminder.timestamp = eventTimestart - reminder.time;
}
if (reminder.value && reminder.unit) {
reminder.label = AddonCalendar.getUnitValueLabel(reminder.value, reminder.unit, reminder.time === null);
if (reminder.timestamp) {
reminder.sublabel = CoreTimeUtils.userDate(reminder.timestamp * 1000, 'core.strftimedatetime');
}
}
return reminder;
});
}
/**
* Get options (name & value) for each allowed event type.
*
* @param eventTypes Result of getAllowedEventTypes.
* @return Options.
*/
getEventTypeOptions(eventTypes: {[name: string]: boolean}): AddonCalendarEventTypeOption[] {
const options: AddonCalendarEventTypeOption[] = [];
if (eventTypes.user) {
options.push({ name: 'core.user', value: AddonCalendarEventType.USER });
}
if (eventTypes.group) {
options.push({ name: 'core.group', value: AddonCalendarEventType.GROUP });
}
if (eventTypes.course) {
options.push({ name: 'core.course', value: AddonCalendarEventType.COURSE });
}
if (eventTypes.category) {
options.push({ name: 'core.category', value: AddonCalendarEventType.CATEGORY });
}
if (eventTypes.site) {
options.push({ name: 'core.site', value: AddonCalendarEventType.SITE });
}
return options;
}
/**
* Get the month "id".
*
* @param moment Month moment.
* @return The "id".
*/
getMonthId(moment: moment.Moment): string {
return `${moment.year()}#${moment.month() + 1}`;
}
/**
* Get the day "id".
*
* @param day Day moment.
* @return The "id".
*/
getDayId(moment: moment.Moment): string {
return `${this.getMonthId(moment)}#${moment.date()}`;
}
/**
* Get weeks of a month in offline (with no events).
*
* The result has the same structure than getMonthlyEvents, but it only contains fields that are actually used by the app.
*
* @param year Year to get.
* @param month Month to get.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the response.
*/
async getOfflineMonthWeeks(
year: number,
month: number,
siteId?: string,
): Promise<{ daynames: Partial<AddonCalendarDayName>[]; weeks: AddonCalendarWeek[] }> {
const site = await CoreSites.getSite(siteId);
// Get starting week day user preference, fallback to site configuration.
let startWeekDayStr = site.getStoredConfig('calendar_startwday') || '1';
startWeekDayStr = await CoreConfig.get(AddonCalendarProvider.STARTING_WEEK_DAY, startWeekDayStr);
const startWeekDay = parseInt(startWeekDayStr, 10);
const today = moment();
const isCurrentMonth = today.year() == year && today.month() == month - 1;
const weeks: AddonCalendarWeek[] = [];
let date = moment({ year, month: month - 1, date: 1 });
for (let mday = 1; mday <= date.daysInMonth(); mday++) {
date = moment({ year, month: month - 1, date: mday });
// Add new week and calculate prepadding.
if (!weeks.length || date.day() == startWeekDay) {
const prepaddingLength = (date.day() - startWeekDay + 7) % 7;
const prepadding: number[] = [];
for (let i = 0; i < prepaddingLength; i++) {
prepadding.push(i);
}
weeks.push({ prepadding, postpadding: [], days: [] });
}
// Calculate postpadding of last week.
if (mday == date.daysInMonth()) {
const postpaddingLength = (startWeekDay - date.day() + 6) % 7;
const postpadding: number[] = [];
for (let i = 0; i < postpaddingLength; i++) {
postpadding.push(i);
}
weeks[weeks.length - 1].postpadding = postpadding;
}
// Add day to current week.
weeks[weeks.length - 1].days.push({
events: [],
hasevents: false,
mday: date.date(),
isweekend: date.day() == 0 || date.day() == 6,
istoday: isCurrentMonth && today.date() == date.date(),
calendareventtypes: [],
// Added to match the type. And possibly unused.
popovertitle: '',
ispast: today.date() > date.date(),
seconds: date.seconds(),
minutes: date.minutes(),
hours: date.hours(),
wday: date.weekday(),
year: year,
yday: date.dayOfYear(),
timestamp: date.date(),
haslastdayofevent: false,
neweventtimestamp: 0,
previousperiod: 0, // Previousperiod.
nextperiod: 0, // Nextperiod.
navigation: '', // Navigation.
});
}
return { weeks, daynames: [{ dayno: startWeekDay }] };
}
/**
* Check if the data of an event has changed.
*
* @param data Current data.
* @param original Original data.
* @return True if data has changed, false otherwise.
*/
hasEventDataChanged(data: AddonCalendarOfflineEventDBRecord, original?: AddonCalendarOfflineEventDBRecord): boolean {
if (!original) {
// There is no original data, assume it hasn't changed.
return false;
}
// Check the fields that don't depend on any other.
if (data.name != original.name || data.timestart != original.timestart || data.eventtype != original.eventtype ||
data.description != original.description || data.location != original.location ||
data.duration != original.duration || data.repeat != original.repeat) {
return true;
}
// Check data that depends on eventtype.
if ((data.eventtype == AddonCalendarEventType.CATEGORY && data.categoryid != original.categoryid) ||
(data.eventtype == AddonCalendarEventType.COURSE && data.courseid != original.courseid) ||
(data.eventtype == AddonCalendarEventType.GROUP && data.groupcourseid != original.groupcourseid &&
data.groupid != original.groupid)) {
return true;
}
// Check data that depends on duration.
if ((data.duration == 1 && data.timedurationuntil != original.timedurationuntil) ||
(data.duration == 2 && data.timedurationminutes != original.timedurationminutes)) {
return true;
}
if (data.repeat && data.repeats != original.repeats) {
return true;
}
return false;
}
/**
* Filter events to be shown on the events list.
*
* @param events Events without filtering.
* @param filter Filter from popover.
* @param categories Categories indexed by ID.
* @return Filtered events.
*/
getFilteredEvents(
events: AddonCalendarEventToDisplay[],
filter: AddonCalendarFilter | undefined,
categories: { [id: number]: CoreCategoryData },
): AddonCalendarEventToDisplay[] {
// Do not filter.
if (!filter || !filter.filtered) {
return events;
}
const courseId = filter.courseId ? Number(filter.courseId) : undefined;
if (!courseId || courseId < 0) {
// Filter only by type.
return events.filter((event) => filter[event.formattedType]);
}
const categoryId = filter.categoryId ? Number(filter.categoryId) : undefined;
return events.filter((event) => filter[event.formattedType] &&
this.shouldDisplayEvent(event, categories, courseId, categoryId));
}
/**
* Check if an event should be displayed based on the filter.
*
* @param event Event object.
* @param categories Categories indexed by ID.
* @param courseId Course ID to filter.
* @param categoryId Category ID the course belongs to.
* @return Whether it should be displayed.
*/
protected shouldDisplayEvent(
event: AddonCalendarEventToDisplay,
categories: { [id: number]: CoreCategoryData },
courseId: number,
categoryId?: number,
): boolean {
if (event.eventtype == 'user' || event.eventtype == 'site') {
// User or site event, display it.
return true;
}
if (event.eventtype == 'category' && categories) {
if (!event.categoryid || !Object.keys(categories).length || !categoryId) {
// We can't tell if the course belongs to the category, display them all.
return true;
}
if (event.categoryid == categoryId) {
// The event is in the same category as the course, display it.
return true;
}
// Check parent categories.
let category = categories[categoryId];
while (category) {
if (!category.parent) {
// Category doesn't have parent, stop.
break;
}
if (event.categoryid == category.parent) {
return true;
}
category = categories[category.parent];
}
return false;
}
const eventCourse = (event.course && event.course.id) || event.courseid;
// Show the event if it is from site home or if it matches the selected course.
return !!eventCourse && (eventCourse == CoreSites.getCurrentSiteHomeId() || eventCourse == courseId);
}
/**
* Refresh the month & day for several created/edited/deleted events, and invalidate the months & days
* for their repeated events if needed.
*
* @param events Events that have been touched and number of times each event is repeated.
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async refreshAfterChangeEvents(events: AddonCalendarSyncInvalidateEvent[], siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const fetchTimestarts: number[] = [];
const invalidateTimestarts: number[] = [];
let promises: Promise<unknown>[] = [];
// Always fetch upcoming events.
promises.push(AddonCalendar.getUpcomingEvents(undefined, undefined, true, site.id));
promises = promises.concat(events.map(async (eventData) => {
if (eventData.repeated <= 1) {
// Not repeated.
fetchTimestarts.push(eventData.timestart);
return AddonCalendar.invalidateEvent(eventData.id);
}
if (eventData.repeatid) {
// Being edited or deleted.
// We need to calculate the days to invalidate because the event date could have changed.
// We don't know if the repeated events are before or after this one, invalidate them all.
fetchTimestarts.push(eventData.timestart);
for (let i = 1; i < eventData.repeated; i++) {
invalidateTimestarts.push(eventData.timestart + CoreConstants.SECONDS_DAY * 7 * i);
invalidateTimestarts.push(eventData.timestart - CoreConstants.SECONDS_DAY * 7 * i);
}
// Get the repeated events to invalidate them.
const repeatedEvents =
await AddonCalendar.getLocalEventsByRepeatIdFromLocalDb(eventData.repeatid, site.id);
await CoreUtils.allPromises(repeatedEvents.map((event) =>
AddonCalendar.invalidateEvent(event.id)));
return;
}
// Being added.
let time = eventData.timestart;
fetchTimestarts.push(time);
while (eventData.repeated > 1) {
time += CoreConstants.SECONDS_DAY * 7;
eventData.repeated--;
invalidateTimestarts.push(time);
}
return;
}));
try {
await CoreUtils.allPromisesIgnoringErrors(promises);
} finally {
const treatedMonths = {};
const treatedDays = {};
const finalPromises: Promise<unknown>[] =[AddonCalendar.invalidateAllUpcomingEvents()];
// Fetch months and days.
fetchTimestarts.map((fetchTime) => {
const day = moment(new Date(fetchTime * 1000));
const monthId = this.getMonthId(day);
if (!treatedMonths[monthId]) {
// Month not refetch or invalidated already, do it now.
treatedMonths[monthId] = true;
finalPromises.push(AddonCalendar.getMonthlyEvents(
day.year(),
day.month() + 1,
undefined,
undefined,
true,
site.id,
));
}
const dayId = monthId + '#' + day.date();
if (!treatedDays[dayId]) {
// Dat not refetch or invalidated already, do it now.
treatedDays[dayId] = true;
finalPromises.push(AddonCalendar.getDayEvents(
day.year(),
day.month() + 1,
day.date(),
undefined,
undefined,
true,
site.id,
));
}
});
// Invalidate months and days.
invalidateTimestarts.map((fetchTime) => {
const day = moment(new Date(fetchTime * 1000));
const monthId = this.getMonthId(day);
if (!treatedMonths[monthId]) {
// Month not refetch or invalidated already, do it now.
treatedMonths[monthId] = true;
finalPromises.push(AddonCalendar.invalidateMonthlyEvents(day.year(), day.month() + 1, site.id));
}
const dayId = monthId + '#' + day.date();
if (!treatedDays[dayId]) {
// Dat not refetch or invalidated already, do it now.
treatedDays[dayId] = true;
finalPromises.push(AddonCalendar.invalidateDayEvents(
day.year(),
day.month() + 1,
day.date(),
site.id,
));
}
});
await CoreUtils.allPromisesIgnoringErrors(finalPromises);
}
}
/**
* Refresh the month & day for a created/edited/deleted event, and invalidate the months & days
* for their repeated events if needed.
*
* @param event Event that has been touched.
* @param repeated Number of times the event is repeated.
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
refreshAfterChangeEvent(
event: {
id: number;
repeatid?: number;
timestart: number;
},
repeated: number,
siteId?: string,
): Promise<void> {
return this.refreshAfterChangeEvents(
[{
id: event.id,
repeatid: event.repeatid,
timestart: event.timestart,
repeated: repeated,
}],
siteId,
);
}
/**
* Sort events by timestart.
*
* @param events List to sort.
*/
sortEvents(events: (AddonCalendarEventToDisplay)[]): (AddonCalendarEventToDisplay)[] {
return events.sort((a, b) => {
if (a.timestart == b.timestart) {
return a.timeduration - b.timeduration;
}
return a.timestart - b.timestart;
});
}
}
export const AddonCalendarHelper = makeSingleton(AddonCalendarHelperProvider);
/**
* Calculated data for Calendar filtering.
*/
export type AddonCalendarFilter = {
filtered: boolean; // If filter enabled (some filters applied).
courseId: number | undefined; // Course Id to filter.
categoryId?: number; // Category Id to filter.
course: boolean; // Filter to show course events.
group: boolean; // Filter to show group events.
site: boolean; // Filter to show show site events.
user: boolean; // Filter to show user events.
category: boolean; // Filter to show category events.
};
export type AddonCalendarEventTypeOption = {
name: string;
value: AddonCalendarEventType;
};
/**
* Formatted event reminder.
*/
export type AddonCalendarEventReminder = AddonCalendarReminderDBRecord & {
value?: number; // Amount of time.
unit?: AddonCalendarReminderUnits; // Units.
timestamp?: number; // Timestamp (in seconds).
label?: string; // Label to represent the reminder.
sublabel?: string; // Sub label.
}; | the_stack |
import {runIfMain} from "../../../../deps/mocha.ts"
import "../../../../deps/chai.ts"
import {Connection} from "../../../../../src/index.ts";
import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../../../utils/test-utils.ts";
import {Post} from "./entity/Post.ts";
import {PostWithOptions} from "./entity/PostWithOptions.ts";
import {PostWithoutTypes} from "./entity/PostWithoutTypes.ts";
describe("database schema > column types > cockroachdb", () => {
let connections: Connection[];
const encoder = new TextEncoder();
before(async () => {
connections = await createTestingConnections({
entities: [Post, PostWithOptions, PostWithoutTypes],
enabledDrivers: ["cockroachdb"],
});
});
beforeEach(() => reloadTestingDatabases(connections));
after(() => closeTestingConnections(connections));
it("all types should work correctly - persist and hydrate", () => Promise.all(connections.map(async connection => {
const postRepository = connection.getRepository(Post);
const queryRunner = connection.createQueryRunner();
const table = await queryRunner.getTable("post");
await queryRunner.release();
const post = new Post();
post.id = 1;
post.name = "Post";
post.integer = "2147483647";
post.int4 = "2147483647";
post.int = "2147483647";
post.smallint = "32767";
post.int2 = "32767";
post.bigint = "8223372036854775807";
post.int8 = "8223372036854775807";
post.int64 = "8223372036854775807";
post.doublePrecision = 15.357;
post.float8 = 15.357;
post.real = 5.5;
post.float4 = 5.5;
post.numeric = "50";
post.decimal = "50";
post.dec = "50";
post.char = "A";
post.character = "A";
post.varchar = "This is varchar";
post.charVarying = "This is char varying";
post.characterVarying = "This is character varying";
post.text = "This is text";
post.string = "This is string";
// TODO(uki00a) not fully tested yet.
post.bytes = encoder.encode("This is bytes");/* Buffer.alloc(13, "This is bytes"); */
post.bytea = encoder.encode("This is bytea");/* Buffer.alloc(13, "This is bytea"); */
post.blob = encoder.encode("This is blob");/* Buffer.alloc(12, "This is blob"); */
post.date = "2017-06-21";
post.interval = "1 year 2 months 3 days 4 hours 5 minutes 6 seconds";
post.time = "05:40:00.000001";
post.timeWithoutTimeZone = "05:40:00.000001";
post.timestamp = new Date();
post.timestamp.setMilliseconds(0);
post.timestampWithTimeZone = new Date();
post.timestampWithTimeZone.setMilliseconds(0);
post.timestampWithoutTimeZone = new Date();
post.timestampWithoutTimeZone.setMilliseconds(0);
post.timestamptz = new Date();
post.timestamptz.setMilliseconds(0);
post.boolean = true;
post.bool = false;
post.inet = "192.168.100.128";
post.uuid = "0e37df36-f698-11e6-8dd4-cb9ced3df976";
post.jsonb = { id: 1, name: "Post" };
post.json = { id: 1, name: "Post" };
post.array = ["1", "2", "3"];
post.simpleArray = ["A", "B", "C"];
post.simpleJson = { param: "VALUE" };
await postRepository.save(post);
const loadedPost = (await postRepository.findOne(1))!;
loadedPost.id.should.be.equal(post.id);
loadedPost.name.should.be.equal(post.name);
loadedPost.integer.should.be.equal(post.integer);
loadedPost.int4.should.be.equal(post.int4);
loadedPost.int.should.be.equal(post.int);
loadedPost.smallint.should.be.equal(post.smallint);
loadedPost.int2.should.be.equal(post.int2);
loadedPost.bigint.should.be.equal(post.bigint);
loadedPost.int8.should.be.equal(post.int8);
loadedPost.int64.should.be.equal(post.int64);
loadedPost.doublePrecision.should.be.equal(post.doublePrecision);
loadedPost.float8.should.be.equal(post.float8);
loadedPost.real.should.be.equal(post.real);
loadedPost.float4.should.be.equal(post.float4);
loadedPost.numeric.should.be.equal(post.numeric);
loadedPost.decimal.should.be.equal(post.decimal);
loadedPost.dec.should.be.equal(post.dec);
loadedPost.char.should.be.equal(post.char);
loadedPost.character.should.be.equal(post.character);
loadedPost.varchar.should.be.equal(post.varchar);
loadedPost.characterVarying.should.be.equal(post.characterVarying);
loadedPost.text.should.be.equal(post.text);
loadedPost.bytes.toString().should.be.equal(post.bytes.toString());
loadedPost.bytea.toString().should.be.equal(post.bytea.toString());
loadedPost.blob.toString().should.be.equal(post.blob.toString());
loadedPost.date.should.be.equal(post.date);
// loadedPost.interval.years.should.be.equal(1);
// loadedPost.interval.months.should.be.equal(2);
// loadedPost.interval.days.should.be.equal(3);
// loadedPost.interval.hours.should.be.equal(4);
// loadedPost.interval.minutes.should.be.equal(5);
// loadedPost.interval.seconds.should.be.equal(6);
loadedPost.time.should.be.equal(post.time);
loadedPost.timeWithoutTimeZone.should.be.equal(post.timeWithoutTimeZone);
loadedPost.timestamp.valueOf().should.be.equal(post.timestamp.valueOf());
loadedPost.timestampWithTimeZone.getTime().should.be.equal(post.timestampWithTimeZone.getTime());
loadedPost.timestampWithoutTimeZone.getTime().should.be.equal(post.timestampWithoutTimeZone.getTime());
loadedPost.timestamptz.valueOf().should.be.equal(post.timestamptz.valueOf());
loadedPost.boolean.should.be.equal(post.boolean);
loadedPost.bool.should.be.equal(post.bool);
loadedPost.inet.should.be.equal(post.inet);
loadedPost.uuid.should.be.eql(post.uuid);
loadedPost.jsonb.should.be.eql(post.jsonb);
loadedPost.json.should.be.eql(post.json);
loadedPost.array[0].should.be.equal(post.array[0]);
loadedPost.array[1].should.be.equal(post.array[1]);
loadedPost.array[2].should.be.equal(post.array[2]);
loadedPost.simpleArray[0].should.be.equal(post.simpleArray[0]);
loadedPost.simpleArray[1].should.be.equal(post.simpleArray[1]);
loadedPost.simpleArray[2].should.be.equal(post.simpleArray[2]);
loadedPost.simpleJson.param.should.be.equal(post.simpleJson.param);
table!.findColumnByName("id")!.type.should.be.equal("int8");
table!.findColumnByName("name")!.type.should.be.equal("varchar");
table!.findColumnByName("integer")!.type.should.be.equal("int8");
table!.findColumnByName("int4")!.type.should.be.equal("int4");
table!.findColumnByName("int")!.type.should.be.equal("int8");
table!.findColumnByName("smallint")!.type.should.be.equal("int2");
table!.findColumnByName("int2")!.type.should.be.equal("int2");
table!.findColumnByName("bigint")!.type.should.be.equal("int8");
table!.findColumnByName("int8")!.type.should.be.equal("int8");
table!.findColumnByName("int64")!.type.should.be.equal("int8");
table!.findColumnByName("doublePrecision")!.type.should.be.equal("float8");
table!.findColumnByName("float8")!.type.should.be.equal("float8");
table!.findColumnByName("real")!.type.should.be.equal("float4");
table!.findColumnByName("float4")!.type.should.be.equal("float4");
table!.findColumnByName("numeric")!.type.should.be.equal("decimal");
table!.findColumnByName("decimal")!.type.should.be.equal("decimal");
table!.findColumnByName("dec")!.type.should.be.equal("decimal");
table!.findColumnByName("char")!.type.should.be.equal("char");
table!.findColumnByName("character")!.type.should.be.equal("char");
table!.findColumnByName("varchar")!.type.should.be.equal("varchar");
table!.findColumnByName("characterVarying")!.type.should.be.equal("varchar");
table!.findColumnByName("charVarying")!.type.should.be.equal("varchar");
table!.findColumnByName("text")!.type.should.be.equal("string");
table!.findColumnByName("string")!.type.should.be.equal("string");
table!.findColumnByName("bytes")!.type.should.be.equal("bytes");
table!.findColumnByName("bytea")!.type.should.be.equal("bytes");
table!.findColumnByName("blob")!.type.should.be.equal("bytes");
table!.findColumnByName("date")!.type.should.be.equal("date");
table!.findColumnByName("interval")!.type.should.be.equal("interval");
table!.findColumnByName("time")!.type.should.be.equal("time");
table!.findColumnByName("timeWithoutTimeZone")!.type.should.be.equal("time");
table!.findColumnByName("timestamp")!.type.should.be.equal("timestamp");
table!.findColumnByName("timestampWithTimeZone")!.type.should.be.equal("timestamptz");
table!.findColumnByName("timestampWithoutTimeZone")!.type.should.be.equal("timestamp");
table!.findColumnByName("timestamptz")!.type.should.be.equal("timestamptz");
table!.findColumnByName("boolean")!.type.should.be.equal("bool");
table!.findColumnByName("bool")!.type.should.be.equal("bool");
table!.findColumnByName("inet")!.type.should.be.equal("inet");
table!.findColumnByName("uuid")!.type.should.be.equal("uuid");
table!.findColumnByName("jsonb")!.type.should.be.equal("jsonb");
table!.findColumnByName("json")!.type.should.be.equal("jsonb");
table!.findColumnByName("array")!.type.should.be.equal("int8");
table!.findColumnByName("array")!.isArray!.should.be.true;
table!.findColumnByName("simpleArray")!.type.should.be.equal("string");
table!.findColumnByName("simpleJson")!.type.should.be.equal("string");
})));
it("all types should work correctly - persist and hydrate when options are specified on columns", () => Promise.all(connections.map(async connection => {
const postRepository = connection.getRepository(PostWithOptions);
const queryRunner = connection.createQueryRunner();
const table = await queryRunner.getTable("post_with_options");
await queryRunner.release();
const post = new PostWithOptions();
post.id = 1;
post.numeric = "50.00";
post.decimal = "50.00";
post.dec = "50.00";
post.char = "AAA";
post.character = "AAA";
post.varchar = "This is varchar";
post.characterVarying = "This is character varying";
post.charVarying = "This is char varying";
post.string = "This is string";
await postRepository.save(post);
const loadedPost = (await postRepository.findOne(1))!;
loadedPost.id.should.be.equal(post.id);
loadedPost.numeric.should.be.equal(post.numeric);
loadedPost.decimal.should.be.equal(post.decimal);
loadedPost.char.should.be.equal(post.char);
loadedPost.character.should.be.equal(post.character);
loadedPost.varchar.should.be.equal(post.varchar);
loadedPost.characterVarying.should.be.equal(post.characterVarying);
loadedPost.charVarying.should.be.equal(post.charVarying);
loadedPost.string.should.be.equal(post.string);
table!.findColumnByName("id")!.type.should.be.equal("int8");
table!.findColumnByName("numeric")!.type.should.be.equal("decimal");
table!.findColumnByName("numeric")!.precision!.should.be.equal(5);
table!.findColumnByName("numeric")!.scale!.should.be.equal(2);
table!.findColumnByName("decimal")!.type.should.be.equal("decimal");
table!.findColumnByName("decimal")!.precision!.should.be.equal(5);
table!.findColumnByName("decimal")!.scale!.should.be.equal(2);
table!.findColumnByName("dec")!.type.should.be.equal("decimal");
table!.findColumnByName("dec")!.precision!.should.be.equal(5);
table!.findColumnByName("dec")!.scale!.should.be.equal(2);
table!.findColumnByName("char")!.type.should.be.equal("char");
table!.findColumnByName("char")!.length!.should.be.equal("3");
table!.findColumnByName("character")!.type.should.be.equal("char");
table!.findColumnByName("character")!.length!.should.be.equal("3");
table!.findColumnByName("varchar")!.type.should.be.equal("varchar");
table!.findColumnByName("varchar")!.length!.should.be.equal("30");
table!.findColumnByName("characterVarying")!.type.should.be.equal("varchar");
table!.findColumnByName("characterVarying")!.length!.should.be.equal("30");
table!.findColumnByName("charVarying")!.type.should.be.equal("varchar");
table!.findColumnByName("charVarying")!.length!.should.be.equal("30");
table!.findColumnByName("string")!.type.should.be.equal("string");
table!.findColumnByName("string")!.length!.should.be.equal("30");
})));
it("all types should work correctly - persist and hydrate when types are not specified on columns", () => Promise.all(connections.map(async connection => {
const postRepository = connection.getRepository(PostWithoutTypes);
const queryRunner = connection.createQueryRunner();
const table = await queryRunner.getTable("post_without_types");
await queryRunner.release();
const post = new PostWithoutTypes();
post.id = 1;
post.name = "Post";
post.boolean = true;
post.datetime = new Date();
post.datetime.setMilliseconds(0);
await postRepository.save(post);
const loadedPost = (await postRepository.findOne(1))!;
loadedPost.id.should.be.equal(post.id);
loadedPost.name.should.be.equal(post.name);
loadedPost.boolean.should.be.equal(post.boolean);
loadedPost.datetime.valueOf().should.be.equal(post.datetime.valueOf());
table!.findColumnByName("id")!.type.should.be.equal("int8");
table!.findColumnByName("name")!.type.should.be.equal("varchar");
table!.findColumnByName("boolean")!.type.should.be.equal("bool");
table!.findColumnByName("datetime")!.type.should.be.equal("timestamp");
})));
});
runIfMain(import.meta); | the_stack |
import { Bson } from "../deps.ts";
import { WriteConcern } from "./types/read_write_concern.ts";
export type Document = Bson.Document;
export interface Server {
host: string;
port: number;
domainSocket?: string;
}
export interface ConnectOptions {
compression?: string[];
certFile?: string;
keyFile?: string;
keyFilePassword?: string;
tls?: boolean;
safe?: boolean;
credential?: Credential;
db: string;
servers: Server[];
retryWrites?: boolean;
appname?: string;
}
export interface CountOptions {
limit?: number;
skip?: number;
hint?: Document | string;
comment?: Document;
readConcern?: Document;
collation?: Document;
}
export interface FindOptions {
findOne?: boolean;
skip?: number;
limit?: number;
projection?: Document;
sort?: Document;
noCursorTimeout?: boolean;
}
export interface ListDatabaseInfo {
name: string;
sizeOnDisk?: number;
empty?: false;
}
export interface InsertOptions {
/**
* Optional. If true, then when an insert of a document fails, return without inserting any remaining documents listed in the inserts array.
* If false, then when an insert of a document fails, continue to insert the remaining documents. Defaults to true.
*/
ordered?: boolean;
/**
* Optional. A document that expresses the write concern of the insert command. Omit to use the default write concern.
* Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.
*/
writeConcern?: Document;
/**
* Optional. Enables insert to bypass document validation during the operation. This lets you insert documents that do not meet the validation requirements.
*/
bypassDocumentValidation?: boolean;
/**
* Optional. A user-provided comment to attach to this command.
*/
comment?: Document;
}
export interface UpdateOptions {
/**
* Optional. A document expressing the write concern of the update command. Omit to use the default write concern.
*/
writeConcern?: Document;
/**
* Optional. If true, then when an update statement fails, return without performing the remaining update statements.
* If false, then when an update fails, continue with the remaining update statements, if any. Defaults to true.
*/
ordered?: boolean;
/**
* Optional. If true, updates all documents that meet the query criteria.
* If false, limit the update to one document that meet the query criteria. Defaults to false.
*/
multi?: boolean;
/**
* optional list of array filters referenced in filtered positional operators
*/
arrayFilters?: Document[];
/**
* Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
*/
collation?: Document;
/**
* Allow driver to bypass schema validation in MongoDB 3.2 or higher
*/
bypassDocumentValidation?: boolean;
/**
* An optional hint for query optimization. See the update (https://docs.mongodb.com/manual/reference/command/update/#update-command-hint) command reference for more information.
*/
hint?: Document;
/**
* When true, creates a new document if no document matches the query.
*/
upsert?: boolean;
/**
* The write concern timeout.
*/
wtimeout?: number;
/**
* If true, will throw if bson documents start with $ or include a . in any key value
*/
checkKeys?: boolean;
/**
* Serialize functions on any object.
*/
serializeFunctions?: boolean;
/**
* Specify if the BSON serializer should ignore undefined fields.
*/
ignoreUndefined?: boolean;
/**
* Optional. A user-provided comment to attach to this command.
*/
comment?: Document;
/**
* optional session to use for this operation
*/
// session?: ClientSession
}
/**
* Options for controlling the collation of strings in a query
*
* @see https://docs.mongodb.com/manual/reference/collation/
*/
export interface CollationOptions {
locale: string;
caseLevel?: boolean;
caseFirst?: string;
strength?: number;
numericOrdering?: boolean;
alternate?: string;
maxVariable?: string;
backwards?: boolean;
}
/**
* Options for the findAndModify operation
*
* @see https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/
*/
export interface FindAndModifyOptions<T = Document> {
/**
* Control the order in which documents are found.
* findAndModify only modifies the first document found, so controlling the
* sort order may ensure, that the right document is first
*/
sort?: Document;
/**
* The update to execute on the found document.
*
* Either update or remove have to be specified
*/
update?: UpdateFilter<T>;
/**
* Remove the found document
*/
remove?: boolean;
/**
* Return the new state after the update
*/
new?: boolean;
/**
* the fields to return.
*/
fields?: Document;
/**
* perform an upsert, i.e. update if a document matches, insert otherwise.
*/
upsert?: boolean;
/**
* do not validate the document during the operation
*/
bypassDocumentValidation?: boolean;
/**
* The write concern to apply to the write operation
*/
writeConcern?: WriteConcern;
/**
* The collation options to apply to string handling (e.g. during sort)
*/
collation?: CollationOptions;
/**
* Filters determining which elements to modify in an array, when modifying
* array values
*/
arrayFilters?: Document[];
/**
* The maximum time of milliseconds the operation is allowed to take
*/
maxTimeMS?: number;
}
export interface DeleteOptions {
/**
* Optional. If true, then when a delete statement fails, return without performing the remaining delete statements.
* If false, then when a delete statement fails, continue with the remaining delete statements, if any. Defaults to true.
*/
ordered?: boolean;
/**
* Optional. A document expressing the write concern of the delete command. Omit to use the default write concern.
*/
writeConcern?: Document;
/**
* Optional. Specifies the collation to use for the operation.
* See https://docs.mongodb.com/manual/reference/command/delete/#deletes-array-collation
*/
collation?: Document;
/**
* Optional. A user-provided comment to attach to this command.
*/
comment?: Document;
/**
* The number of matching documents to delete. Specify either a 0 to delete all matching documents or 1 to delete a single document.
*/
limit?: number;
/**
* Optional. A document or string that specifies the index to use to support the query predicate.
* The option can take an index specification document or the index name string.
* If you specify an index that does not exist, the operation errors.
*/
hint?: Document | string;
}
export interface DropOptions {
/**
* Optional. A document expressing the write concern of the drop command. Omit to use the default write concern.
*/
writeConcern?: Document;
/**
* Optional. A user-provided comment to attach to this command.
*/
// deno-lint-ignore no-explicit-any
comment?: any;
}
export interface DistinctOptions {
/**
* The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
*/
readPreference?: string;
/**
* Number of milliseconds to wait before aborting the query.
*/
maxTimeMS?: number;
/**
* pecify collation settings for operation. See aggregation documentation(https://docs.mongodb.com/manual/reference/command/aggregate).
*/
collation?: Document;
/**
* optional session to use for this operation
*/
// session?:ClientSession;
}
export interface AggregateOptions {
/**
* The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
*/
readPreference?: string;
/**
* @default 1000
* The number of documents to return per batch. See aggregation documentation(https://docs.mongodb.com/manual/reference/command/aggregate).
*/
batchSize?: number;
/**
* @default false
* Explain returns the aggregation execution plan (requires mongodb 2.6 >).
*/
explain?: boolean;
/**
* @default false
* allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
*/
allowDiskUse?: boolean;
/**
* maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
*/
maxTimeMS?: number;
/**
* @default false
* Allow driver to bypass schema validation in MongoDB 3.2 or higher.
*/
bypassDocumentValidation?: boolean;
/**
* @default false
* Return document results as raw BSON buffers.
*/
raw?: boolean;
/**
* @default true
* Promotes Long values to number if they fit inside the 53 bits resolution.
*/
promoteLongs?: boolean;
/**
* @default true
* Promotes BSON values to native types where possible, set to false to only receive wrapper types.
*/
promoteValues?: boolean;
/**
* @default false
* Promotes Binary BSON values to native Node Buffers.
*/
promoteBuffers?: boolean;
/**
* Specify collation settings for operation. See aggregation documentation(https://docs.mongodb.com/manual/reference/command/aggregate).
*/
collation?: Document;
/**
* Add a comment to an aggregation command
*/
comment?: string;
/**
* Add an index selection hint to an aggregation command
*/
hint?: string | Document;
/**
* optional session to use for this operation
*/
// session?:ClientSession;
}
export interface CreateUserOptions {
/**
* The name of the new user.
*/
username?: string;
/**
* The user’s password. The pwd field is not required if you run createUser on the $external database to create users who have credentials stored externally to MongoDB.
*/
password?: string;
/**
* Optional. Any arbitrary information. This field can be used to store any data an admin wishes to associate with this particular user. For example, this could be the user’s full name or employee id.
*/
customData?: Document;
/**
* The roles granted to the user. Can specify an empty array [] to create users without roles.
*/
roles?: (string | {
role: string;
db: string;
})[];
/**
* Optional. Indicates whether the server or the client digests the password.
* See https://docs.mongodb.com/manual/reference/command/createUser/#dbcmd.createUser
*/
digestPassword?: boolean;
/**
* Optional. The level of write concern for the creation operation. The writeConcern document takes the same fields as the getLastError command.
*/
writeConcern?: Document;
/**
* Optional. The authentication restrictions the server enforces on the created user. Specifies a list of IP addresses and CIDR ranges from which the user is allowed to connect to the server or from which the server can accept users.
*/
authenticationRestrictions?: Document[];
/**
* Optional. Specify the specific SCRAM mechanism or mechanisms for creating SCRAM user credentials.
*/
mechanisms?: ("SCRAM-SHA-1" | "SCRAM-SHA-256")[];
/**
* Optional. A user-provided comment to attach to this command.
*/
comment?: Document;
}
export interface Credential {
/**
* The username to authenticate with. This applies to all mechanisms but may be omitted when authenticating via MONGODB-X509.
*/
username?: string;
/**
* The password to authenticate with. This does not apply to all mechanisms.
*/
password?: string;
/**
* The database used to authenticate. This applies to all mechanisms and defaults to "admin" in SCRAM authentication mechanisms and "$external" for GSSAPI, MONGODB-X509 and PLAIN.
*/
db?: string;
/**
* Which authentication mechanism to use. If not provided, one will be negotiated with the server.
*/
mechanism?: "SCRAM-SHA-1" | "SCRAM-SHA-256" | "MONGODB-X509";
}
export interface IndexOptions {
/**
* Specifies the index’s fields. For each field, specify a key-value pair in which
* the key is the name of the field to index and the value is either the index direction
* or index type. If specifying direction, specify 1 for ascending or -1 for descending.
*/
key: Document;
/**
* A name that uniquely identifies the index.
*/
name: string;
/**
* Optional. Deprecated in MongoDB 4.2.
*/
background?: boolean;
/**
* Optional. Creates a unique index so that the collection will not accept insertion
* or update of documents where the index key value matches an existing value in the index.
* Specify true to create a unique index. The default value is false.
*/
unique?: boolean;
/**
* Optional. If specified, the index only references documents that match the filter expression.
* See Partial Indexes for more information.
*/
partialFilterExpression?: Document;
/**
* Optional. If true, the index only references documents with the specified field.
* These indexes use less space but behave differently in some situations (particularly sorts).
* The default value is false. See Sparse Indexes for more information.
*/
sparse?: boolean;
/**
* Optional. Specifies a value, in seconds, as a TTL to control how long MongoDB retains
* documents in this collection. See Expire Data from Collections by Setting TTL for
* more information on this functionality. This applies only to TTL indexes.
*/
expireAfterSeconds?: number;
/**
* Optional. A flag that determines whether the index is hidden from the query planner.
* A hidden index is not evaluated as part of query plan selection. Default is false.
*/
hidden?: boolean;
/**
* Optional. Allows users to configure the storage engine on a per-index basis when creating an index.
*/
storageEngine?: Document;
/**
* Optional. For text indexes, a document that contains field and weight pairs.
* The weight is an integer ranging from 1 to 99,999 and denotes the significance
* of the field relative to the other indexed fields in terms of the score.
* You can specify weights for some or all the indexed fields.
* See Control Search Results with Weights to adjust the scores.
* The default value is 1.
*/
weights?: Document;
/**
* Optional. For text indexes, the language that determines the list of
* stop words and the rules for the stemmer and tokenizer.
* See Text Search Languages for the available languages and Specify a Language
* for Text Index for more information and examples. The default value is english.
*/
// deno-lint-ignore camelcase
default_language?: string;
/**
* Optional. For text indexes, the name of the field, in the collection’s documents,
* that contains the override language for the document. The default value is language.
* See Use any Field to Specify the Language for a Document for an example.
*/
// deno-lint-ignore camelcase
language_override?: string;
/**
* Optional. The text index version number. Users can use this option to override the default version number.
*/
textIndexVersion?: number;
/**
* Optional. The 2dsphere index version number. Users can use this option to override the default version number.
*/
"2dsphereIndexVersion"?: number;
/**
* Optional. For 2d indexes, the number of precision of the stored geohash value of the location data.
* The bits value ranges from 1 to 32 inclusive. The default value is 26.
*/
bits?: number;
/**
* Optional. For 2d indexes, the lower inclusive boundary for the longitude and latitude values. The default value is -180.0.
*/
min?: number;
/**
* Optional. For 2d indexes, the upper inclusive boundary for the longitude and latitude values. The default value is 180.0.
*/
max?: number;
/**
* For geoHaystack indexes, specify the number of units within which to group the location values;
* i.e. group in the same bucket those location values that are within the specified number
* of units to each other. The value must be greater than 0.
*/
bucketSize?: number;
/**
* Optional. Specifies the collation for the index.
*/
collation?: Document;
/**
* Allows users to include or exclude specific field paths from a wildcard index using
* the { "$**" : 1} key pattern. This option is only valid if creating a wildcard index
* on all document fields. You cannot specify this option if creating a wildcard index
* on a specific field path and its subfields, e.g. { "path.to.field.$**" : 1 }
*/
wildcardProjection?: Document;
}
export interface CreateIndexOptions {
/**
* Specifies the indexes to create. Each document in the array specifies a separate index.
*/
indexes: IndexOptions[];
/** Optional. A document expressing the write concern. Omit to use the default write concern. */
writeConcern?: Document;
/**
* Optional. The minimum number of data-bearing voting replica set members (i.e. commit quorum),
* including the primary, that must report a successful index build before the primary marks the indexes as ready.
* A “voting” member is any replica set member where members[n].votes is greater than 0.
*/
commitQuorum?: number | string;
/** Optional. A user-provided comment to attach to this command. Once set */
comment?: Document;
}
export interface DropIndexOptions {
/**
* Specifies the indexes to drop.
* To drop all but the _id index from the collection, specify "*".
* To drop a single index, specify either the index name, the index specification document (unless the index is a text index), or an array of the index name.
* To drop a text index, specify the index names instead of the index specification document.
* To drop multiple indexes (Available starting in MongoDB 4.2), specify an array of the index names.
* See https://docs.mongodb.com/manual/reference/command/dropIndexes/#mongodb-dbcommand-dbcmd.dropIndexes
*/
index: string | IndexOptions | string[];
/** Optional. A document expressing the write concern. Omit to use the default write concern. */
writeConcern?: Document;
/** Optional. A user-provided comment to attach to this command. Once set */
comment?: Document;
}
type BitwiseType = Bson.Binary | Array<number> | number;
type IntegerType = number | Bson.Int32 | Bson.Long;
type NumericType = IntegerType | Bson.Decimal128 | Bson.Double;
interface RootFilterOperators<T> extends Document {
$and?: Filter<T>[];
$nor?: Filter<T>[];
$or?: Filter<T>[];
$text?: {
$search: string;
$language?: string;
$caseSensitive?: boolean;
$diacriticSensitive?: boolean;
};
$where?: string;
$comment?: string | Document;
}
/**
* Operators for use in the search query.
*
* @see https://docs.mongodb.com/manual/reference/operator/query/
*/
interface FilterOperators<TValue> extends Document {
$eq?: TValue;
$gt?: TValue;
$gte?: TValue;
$in?: Array<TValue>;
$lt?: TValue;
$lte?: TValue;
$ne?: TValue;
$nin?: TValue extends (infer T)[] ? T[] : Array<TValue>;
$not?: FilterOperators<TValue>;
$exists?: boolean;
$expr?: Document;
$jsonSchema?: Document;
$mod?: TValue extends number ? [number, number] : never;
$regex?: string | RegExp | Bson.BSONRegExp;
$geoIntersects?: { $geometry: Document };
$geoWithin?: Document;
$near?: Document;
$nearSphere?: TValue;
// deno-lint-ignore no-explicit-any
$all?: Array<any>;
// deno-lint-ignore no-explicit-any
$size?: TValue extends Array<any> ? number : never;
$bitsAllClear?: BitwiseType;
$bitsAllSet?: BitwiseType;
$bitsAnyClear?: BitwiseType;
$elemMatch?: Document;
$rand?: Record<string, never>;
}
/**
* Operators for use in the update query.
*
* @see https://docs.mongodb.com/manual/reference/operator/update/
*/
interface UpdateOperators<T> extends Document {
$currentDate?: DocumentOperator<
T,
Bson.Timestamp | Date,
true | { $type: "date" | "timestamp" }
>;
$inc?: DocumentOperator<T, NumericType>;
$min?: DocumentOperator<T>;
$max?: DocumentOperator<T>;
$mul?: DocumentOperator<T, NumericType>;
$rename?: DocumentOperator<Omit<T, "_id">, string>;
$set?: DocumentOperator<T>;
$setOnInsert?: DocumentOperator<T>;
// deno-lint-ignore no-explicit-any
$unset?: DocumentOperator<T, any, "" | true | 1>;
// deno-lint-ignore no-explicit-any
$pop?: DocumentOperator<T, Array<any>, (1 | -1)>;
$pull?: {
// deno-lint-ignore no-explicit-any
[Key in KeysOfType<T, Array<any>>]?:
| Flatten<T[Key]>
| FilterOperators<Flatten<T[Key]>>;
};
$pullAll?: {
// deno-lint-ignore no-explicit-any
[Key in KeysOfType<T, Array<any>>]?: T[Key];
};
$push?: {
// deno-lint-ignore no-explicit-any
[Key in KeysOfType<T, Array<any>>]?: {
$each?: T[Key];
$slice?: number;
$position?: number;
$sort?: 1 | -1;
};
};
$bit?: DocumentOperator<
T,
NumericType,
{ and: IntegerType } | { or: IntegerType } | { xor: IntegerType }
>;
}
/**
* Operators for use in the aggregation query.
*
* @see https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/
*/
type AggregateOperators =
| "$addFields"
| "$bucket"
| "$bucketAuto"
| "$collStats"
| "$count"
| "$currentOp"
| "$facet"
| "$geoNear"
| "$graphLookup"
| "$group"
| "$indexStats"
| "$limit"
| "$listLocalSessions"
| "$listSessions"
| "$lookup"
| "$match"
| "$merge"
| "$out"
| "$planCacheStats"
| "$project"
| "$redact"
| "$replaceRoot"
| "$replaceWith"
| "$sample"
| "$search"
| "$set"
| "$setWindowFields"
| "$skip"
| "$sort"
| "$sortByCount"
| "$unset"
| "$unwind";
// deno-lint-ignore no-explicit-any
type DocumentOperator<T, OnlyType = any, Value = OnlyType> = IsAny<
OnlyType,
(Partial<T> & Document),
{
[key in KeysOfType<T, OnlyType>]?: Value;
}
>;
// deno-lint-ignore no-explicit-any
type NotImplementedOperators<Operators extends string, Value = any> = {
[Key in Operators]?: Value;
};
export type Filter<T> =
& NotImplementedOperators<"$type">
& RootFilterOperators<T>
& {
[Key in keyof T]?: T[Key] | FilterOperators<T[Key]>;
};
export type UpdateFilter<T> =
& NotImplementedOperators<"$addToSet">
& UpdateOperators<T>
& Partial<T>;
export type AggregatePipeline<T> =
& NotImplementedOperators<AggregateOperators>
& Document
& {
["$match"]?: Filter<T>;
};
type Flatten<T> = T extends Array<infer Item> ? Item : T;
type IsAny<T, Y, N> = 0 extends (1 & T) ? Y : N;
// deno-lint-ignore no-explicit-any
export type InsertDocument<TDocument extends { _id?: any }> =
& Omit<TDocument, "_id">
& {
_id?: TDocument["_id"] | Bson.ObjectId;
};
type KeysOfType<T, Type> = {
[Key in keyof T]: NonNullable<T[Key]> extends Type ? Key : never;
}[keyof T];
/** The document returned by the buildInfo command. */
export interface BuildInfo {
/**
* A string that conveys version information about the `mongod` instance.
* If you need to present version information to a human, this field is preferable to `versionArray`.
*
* This string will take the format `<major>.<minor>.<patch>` in the case of a release,
* but development builds may contain additional information.
*/
version: string;
/** The commit identifier that identifies the state of the code used to build the mongod. */
gitVersion: string;
/**
* @deprecated since 3.2
* `buildInfo.sysInfo` no longer contains useful information.
*/
sysInfo: string;
loaderFlags: string;
compilerFlags: string;
/**
* The memory allocator that mongod uses. By default this is tcmalloc.
*/
allocator: string;
/**
* An array that conveys version information about the mongod instance.
* See version for a more readable version of this string.
*/
versionArray: number[];
/**
* An embedded document describing the version of the TLS/SSL library that mongod
* was built with and is currently using.
*/
openssl: Document;
/**
* A string that reports the JavaScript engine used in the mongod instance.
* By default, this is mozjs after version 3.2, and previously V8.
*/
javascriptEngine: string;
/**
* A number that reflects the target processor architecture of the mongod binary.
*/
bits: number;
/**
* A boolean. true when built with debugging options.
*/
debug: boolean;
/**
* A number that reports the Maximum BSON Document Size.
*/
maxBsonObjectSize: number;
/**
* A list of storage engines available to the mongod server.
*/
storageEngines: string[];
ok: number;
}
export const enum ReadPreference {
Primary = "primary",
PrimaryPreferred = "primaryPreferred",
Secondary = "secondary",
SecondaryPreferred = "secondaryPreferred",
Nearest = "nearest",
} | the_stack |
import React, {useEffect, useState} from 'react';
import {
Button,
Card,
CardContent,
CardHeader,
CardOptions,
CardTitle,
Divider,
Notification,
Spacing,
TableContainer,
} from "@gui-elements/index";
import SuggestionList from "./SuggestionList";
import SuggestionHeader from "./SuggestionHeader";
import {
generateRuleAsync,
getSuggestionsAsync,
prefixesAsync,
schemaExampleValuesAsync, useApiDetails,
} from "../../store";
import {
IAddedSuggestion,
IPrefix,
ISuggestionCandidate,
ITransformedSuggestion,
IVocabularyInfo
} from "./suggestion.typings";
import silkApi from "../../../api/silkRestApi";
import VocabularyMatchingDialog from "./VocabularyMatchingDialog";
import {IInitFrontend, useInitFrontend} from "../../../api/silkRestApi.hooks";
import {extractSearchWords, matchesAllWords} from "@gui-elements/src/components/Typography/Highlighter";
import ErrorView from "../../components/ErrorView";
import _ from "lodash";
interface ISuggestionListContext {
// Can be deleted when popup issue gone
portalContainer: HTMLElement | undefined;
// sharing example values for source data
exampleValues: {
[key: string]: string[]
};
// Table global search
search: string;
// indicator shows the swap state, by default it's true source->target
isFromDataset: boolean;
// Needed to create DM links
frontendInitData?: IInitFrontend
// Flag if vocabularies are available to match against
vocabulariesAvailable: boolean
// Fetch target property suggestions from the vocabulary cache
fetchTargetPropertySuggestions?: (textQuery: string) => Promise<ISuggestionCandidate[]>,
}
export const SuggestionListContext = React.createContext<ISuggestionListContext>({
portalContainer: undefined,
exampleValues: {},
search: '',
isFromDataset: true,
vocabulariesAvailable: false,
});
interface IProps {
ruleId: string
targetClassUris: string[]
onAskDiscardChanges: (ruleId: string) => any
onClose: () => any
selectedVocabs: string[]
setSelectedVocabs: (vocabs: string[]) => any
}
/** The mapping suggestion widget */
export default function SuggestionContainer({ruleId, targetClassUris, onAskDiscardChanges, onClose, selectedVocabs, setSelectedVocabs}: IProps) {
// Loading indicator
const [loading, setLoading] = useState(false);
const [vocabularies, setVocabularies] = useState<IVocabularyInfo[] | undefined>(undefined)
const [showMatchingDialog, setShowMatchingDialog] = useState<boolean>(false)
const [error, setError] = useState<any[]>([]);
const [data, setData] = useState<ITransformedSuggestion[]>([]);
const [filteredData, setFilteredData] = useState<ITransformedSuggestion[]>([]);
const [search, setSearch] = useState('');
const [submittedSearch, setSubmittedSearch] = useState('');
const [isFromDataset, setIsFromDataset] = useState(true);
const [exampleValues, setExampleValues] = useState({});
const [prefixList, setPrefixList] = useState<IPrefix[]>([]);
const vocabulariesAvailable = vocabularies !== undefined && vocabularies.length > 0
const noVocabsAvailable = vocabularies && vocabularies.length === 0
const frontendInitData = useInitFrontend()
const apiDetails = useApiDetails()
// Updates the current error array depending on the type of the added error object
const setErrorSafe = (newErrors: any | any[], keepOldErrors: boolean = true) => {
// Convert different error formats
const convertError = (err: any) => err?.error ?? err
if(Array.isArray(newErrors)) {
setError((oldErrors) => [
...(keepOldErrors && oldErrors ? oldErrors : []),
...newErrors.map(err => convertError(err))
])
} else if(typeof newErrors === "object") {
setError((oldErrors) => [
...(keepOldErrors ? oldErrors : []),
convertError(newErrors)
])
}
}
const {baseUrl, project, transformTask} = apiDetails
useEffect(() => {
fetchVocabularyInfos()
}, [])
const handleSelectedVocabs = (selected: IVocabularyInfo[]) => {
setSelectedVocabs(selected.map((v) => v.uri))
}
// Fetch vocabulary information for the transform task, i.e. the available vocabs.
const fetchVocabularyInfos = () => {
silkApi.retrieveTransformVocabularyInfos(baseUrl as string, project as string, transformTask as string)
.then(({ data }) => {
setVocabularies(data.vocabularies)
})
.catch(err => {
// TODO: error handling
setVocabularies([])
})
}
// Fetch target properties from the available target properties based on a text query
const fetchTargetPropertySuggestions = async (textQuery: string): Promise<ISuggestionCandidate[]> => {
const maxResults = 20
try {
const {data} = await silkApi.retrieveTransformTargetProperties(baseUrl as string, project as string, transformTask as string, ruleId,
textQuery, maxResults, selectedVocabs)
if (Array.isArray(data)) {
return data.map(tp => {
return {
uri: tp.value,
label: tp.label,
confidence: 0,
type: tp.extra.type,
graph: tp.extra.graph, // TODO: This might be prefixed
description: tp.description
}
})
} else {
return []
}
} catch (err) {
// TODO: What to display on error?
return []
}
}
// React to search input
useEffect(() => {
if(data.length > 0) {
handleFilter(data)
}
}, [search, data])
// As soon as the initial vocabularies are loaded, fetch the actual data, i.e. source paths, matchings etc.
useEffect(() => {
if(vocabularies) {
(async function () {
setLoading(true);
try {
await Promise.all([
loadVocabularyMatches(isFromDataset, false, vocabulariesAvailable),
loadExampleValues(),
loadPrefixes()
])
} catch (e) {
setErrorSafe(e)
} finally {
setLoading(false);
}
})()
}
}, [vocabularies]);
// Swapping between source and target (vocabulary) view
const handleSwapAction = async () => {
setIsFromDataset(!isFromDataset);
setError([]);
try {
await loadVocabularyMatches(!isFromDataset, true, vocabulariesAvailable);
} catch (e) {
setErrorSafe(e, false);
}
};
// Fetches necessary data to generate the mapping suggestions
const loadVocabularyMatches = (matchFromDataset: boolean, setLoader: boolean, executeMatching: boolean, selectedVocabularies?: string[]) => {
const vocabs = selectedVocabularies ? selectedVocabularies : selectedVocabs
setData([])
setError([])
return new Promise((resolve, reject) => {
setLoader && setLoading(true)
getSuggestionsAsync(
{
targetClassUris,
ruleId,
matchFromDataset,
nrCandidates: 20,
targetVocabularies: vocabs && vocabs.length > 0 ? vocabs : undefined,
},
executeMatching
).subscribe(
({suggestions, warnings}) => {
try {
if (warnings.length) {
reject(warnings);
}
setData(suggestions);
handleFilter(suggestions);
resolve(suggestions);
} finally {
setLoader && setLoading(false)
}
},
(error) => {
setLoader && setLoading(false)
reject(error);
}
)
});
};
// Load example values for the source paths. This will be shown in an info box / tooltip
const loadExampleValues = () => {
return new Promise((resolve, reject) => {
schemaExampleValuesAsync(ruleId).subscribe(
(data) => {
setExampleValues(data);
resolve(data);
},
err => {
reject(err);
}
);
})
};
// Load prefixes. These are needed for generating target properties automatically based on the the source name.
const loadPrefixes = () => {
return new Promise((resolve, reject) => {
prefixesAsync().subscribe(
data => {
const arr: any[] = Object.keys(data).map(key => {
return {
key,
uri: data[key]
}
});
setPrefixList(arr);
resolve(arr);
},
err => {
reject(err);
}
)
});
};
// Add mapping suggestions, i.e. generate mapping rules from selected mapping suggestions.
const handleAdd = (selectedRows: IAddedSuggestion[], selectedPrefix?: string) => {
setLoading(true);
setError([]);
const correspondences = selectedRows
.map(suggestion => {
const {source, targetUri, type} = suggestion;
const correspondence = {
sourcePath: source,
targetProperty: targetUri || undefined,
type,
};
if (!isFromDataset) {
correspondence.sourcePath = targetUri;
correspondence.targetProperty = source || undefined;
}
return correspondence
});
generateRuleAsync(correspondences, ruleId, selectedPrefix).subscribe(
() => onClose(),
err => {
// If we have a list of failedRules, we want to show them, otherwise something
// else failed
const errorBody = _.get(err, 'response.body');
const error: any[] = err.failedRules
? err.failedRules
: [{error: {...errorBody, ...err}}];
error.filter(err => err?.error).forEach(err => err.error.titlePrefix = 'There has been a problem generating the mapping rules: ')
setErrorSafe(error);
setLoading(false)
},
() => setLoading(false)
);
}
// Search value submitted for filtering the mapping suggestion table based on a multi-word text query
const handleSearch = (value: string) => {
setSearch(value);
};
// Extracts the relevant text of a source or target item used for text filtering
const itemText = (item: ITransformedSuggestion | ISuggestionCandidate): string => {
const title = item.label ? `${item.label} ${item.uri}` : item.uri
const description = item.description || ""
return `${title} ${description}`
}
/** Filters the table based on the search query. */
const handleFilter = (inputMappingSuggestions: ITransformedSuggestion[]) => {
let filtered: ITransformedSuggestion[] = inputMappingSuggestions
if (search.trim() !== "") {
filtered = []
const searchWords = extractSearchWords(search, true);
inputMappingSuggestions.forEach((suggestion) => {
const sourceText = itemText(suggestion)
let targetCandidate = suggestion.candidates.length > 0 && suggestion.candidates[0]
const targetCandidateText = targetCandidate ? itemText(targetCandidate) : ""
const matchText = `${sourceText} ${targetCandidateText}`.toLowerCase()
if (matchesAllWords(matchText, searchWords)) {
filtered.push(suggestion);
}
});
}
setFilteredData(filtered);
setSubmittedSearch(search);
};
// Actions regarding vocabulary matching, e.g. matching dialog
const mappingOptions = <CardOptions>
{ vocabulariesAvailable && (
<Button onClick={() => setShowMatchingDialog(true)} data-test-id={'find_matches'}>
{selectedVocabs.length > 0 && vocabularies ? `Selected vocabularies (${selectedVocabs.length}/${vocabularies.length})`: "Select vocabularies"}
</Button>
)}
</CardOptions>
// Error widget that displays errors that have occurred
const errorWidget = (!loading && !!error.length) && <>
{error.map(err => <ErrorView
{...err}
/>)}
<Spacing size="small" />
</>
// Widget that shows infos about the vocabularies, e.g. that no vocab is loaded.
const vocabularyInfoNotification = (noVocabsAvailable) && <>
<Notification>There is currently no vocabulary loaded for this transformation. Vocabulary matching is not available.</Notification>
<Spacing size="small" />
</>
// Execute vocabulary matching from vocabulary matching dialog
const executeVocabMatchingFromDialog = async (vocabs) => {
try {
await loadVocabularyMatches(isFromDataset, true, true, vocabs)
} catch (e) {
setErrorSafe(e, false)
}
}
const askForDiscardFn = () => onAskDiscardChanges(ruleId)
return (
<Card>
<CardHeader>
<CardTitle>
Mapping Suggestions
</CardTitle>
{mappingOptions}
</CardHeader>
<Divider />
<CardContent>
{errorWidget}
{vocabularyInfoNotification}
{
<SuggestionListContext.Provider value={{
portalContainer: document.body,
exampleValues,
search: submittedSearch,
isFromDataset,
frontendInitData,
vocabulariesAvailable,
fetchTargetPropertySuggestions,
}}>
<SuggestionHeader onSearch={handleSearch} />
<Spacing size="tiny" />
<TableContainer>
<SuggestionList
rows={filteredData}
prefixList={prefixList}
onSwapAction={handleSwapAction}
onAdd={handleAdd}
onClose={onClose}
onAskDiscardChanges={askForDiscardFn}
loading={loading}
/>
</TableContainer>
{showMatchingDialog && vocabulariesAvailable &&
<VocabularyMatchingDialog
availableVocabularies={vocabularies as IVocabularyInfo[]}
onClose={() => setShowMatchingDialog(false)}
executeMatching={executeVocabMatchingFromDialog}
onSelection={handleSelectedVocabs}
preselection={selectedVocabs}
/>
}
</SuggestionListContext.Provider>
}
</CardContent>
</Card>
)
} | the_stack |
import {
CdmCorpusDefinition,
CdmDataTypeReference,
CdmDocumentDefinition,
CdmEntityAttributeDefinition,
CdmEntityDefinition,
CdmEntityReference,
CdmFolderDefinition,
CdmManifestDefinition,
CdmObject,
cdmObjectType,
CdmOperationAddCountAttribute,
CdmOperationAddSupportingAttribute,
CdmOperationAddTypeAttribute,
CdmOperationExcludeAttributes,
CdmOperationCollection,
CdmOperationArrayExpansion,
CdmOperationCombineAttributes,
CdmOperationRenameAttributes,
CdmOperationReplaceAsForeignKey,
CdmOperationIncludeAttributes,
cdmOperationType,
CdmProjection,
CdmPurposeReference,
CdmTypeAttributeDefinition
} from '../../../internal';
import { LocalAdapter } from '../../../Storage';
import { testHelper } from '../../testHelper';
describe('Cdm/Projection/ProjectionObjectModel', () => {
const foundationJsonPath: string = 'cdm:/foundations.cdm.json';
/**
* The path between TestDataPath and TestName.
*/
const testsSubpath: string = 'Cdm/Projection';
/**
* Basic test to save projection based entities and then try to reload them and validate that the projections were persisted correctly
*/
it('TestProjectionUsingObjectModel', async () => {
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestProjectionUsingObjectModel');
corpus.storage.mount('local', new LocalAdapter(testHelper.getActualOutputFolderPath(testsSubpath, 'TestProjectionUsingObjectModel')));
const localRoot: CdmFolderDefinition = corpus.storage.fetchRootFolder('local');
const manifestDefault: CdmManifestDefinition = createDefaultManifest(corpus, localRoot);
const entityTestSource: CdmEntityDefinition = createEntityTestSource(corpus, manifestDefault, localRoot);
const entityTestEntityProjection: CdmEntityDefinition = createEntityTestEntityProjection(corpus, manifestDefault, localRoot);
const entityTestEntityNestedProjection: CdmEntityDefinition = createEntityTestEntityNestedProjection(corpus, manifestDefault, localRoot);
const entityTestEntityAttributeProjection: CdmEntityDefinition = createEntityTestEntityAttributeProjection(corpus, manifestDefault, localRoot);
const entityTestOperationCollection: CdmEntityDefinition = createEntityTestOperationCollection(corpus, manifestDefault, localRoot);
// Save manifest and entities.
await manifestDefault.saveAsAsync(`${manifestDefault.manifestName}.manifest.cdm.json`, true);
const expected: string = 'TestSource';
const expectedType: cdmObjectType = cdmObjectType.projectionDef;
let actual: string;
let actualType: cdmObjectType = cdmObjectType.error;
// Try to read back the newly persisted manifest and projection based entities
const manifestReadBack: CdmManifestDefinition = await corpus.fetchObjectAsync<CdmManifestDefinition>(`local:/${manifestDefault.manifestName}.manifest.cdm.json`);
expect(manifestReadBack.entities.length)
.toEqual(5);
expect(manifestReadBack.entities.allItems[0].entityName)
.toEqual(entityTestSource.entityName);
expect(manifestReadBack.entities.allItems[1].entityName)
.toEqual(entityTestEntityProjection.entityName);
expect(manifestReadBack.entities.allItems[2].entityName)
.toEqual(entityTestEntityNestedProjection.entityName);
expect(manifestReadBack.entities.allItems[3].entityName)
.toEqual(entityTestEntityAttributeProjection.entityName);
// Read back the newly persisted manifest and projection based entity TestEntityProjection and validate
const entityTestEntityProjectionReadBack: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityTestEntityProjection.entityName}.cdm.json/${entityTestEntityProjection.entityName}`, manifestReadBack);
expect(entityTestEntityProjectionReadBack)
.toBeTruthy();
actual = ((entityTestEntityProjectionReadBack.extendsEntity.explicitReference as CdmProjection).source as CdmEntityReference).namedReference;
actualType = (entityTestEntityProjectionReadBack.extendsEntity.explicitReference as CdmProjection).getObjectType();
expect(actual)
.toEqual(expected);
expect(actualType)
.toEqual(expectedType);
// Read back the newly persisted manifest and projection based entity TestEntityNestedProjection and validate
const entityTestEntityNestedProjectionReadBack: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityTestEntityNestedProjection.entityName}.cdm.json/${entityTestEntityNestedProjection.entityName}`, manifestReadBack);
expect(entityTestEntityNestedProjectionReadBack)
.toBeTruthy();
actual = (((entityTestEntityNestedProjectionReadBack.extendsEntity.explicitReference as CdmProjection).source.explicitReference as CdmProjection).source.explicitReference as CdmProjection).source.namedReference;
actualType = ((entityTestEntityNestedProjectionReadBack.extendsEntity.explicitReference as CdmProjection).source.explicitReference as CdmProjection).source.explicitReference.objectType;
expect(actual)
.toEqual(expected);
expect(actualType)
.toEqual(expectedType);
// Read back the newly persisted manifest and projection based entity TestEntityAttributeProjection and validate
const entityTestEntityAttributeProjectionReadBack: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityTestEntityAttributeProjection.entityName}.cdm.json/${entityTestEntityAttributeProjection.entityName}`, manifestReadBack);
expect(entityTestEntityAttributeProjectionReadBack)
.toBeTruthy();
actual = (((entityTestEntityAttributeProjectionReadBack.attributes.allItems[0] as CdmEntityAttributeDefinition).entity.explicitReference as CdmProjection).source as CdmEntityReference).namedReference;
actualType = ((entityTestEntityAttributeProjectionReadBack.attributes.allItems[0] as CdmEntityAttributeDefinition).entity.explicitReference as CdmProjection).getObjectType();
expect(actual)
.toEqual(expected);
expect(actualType)
.toEqual(expectedType);
// Read back operations collections and validate
const entityTestOperationCollectionReadBack: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityTestOperationCollection.entityName}.cdm.json/${entityTestOperationCollection.entityName}`, manifestReadBack);
expect(entityTestOperationCollectionReadBack)
.toBeTruthy();
const actualOperationCount: number = (entityTestOperationCollectionReadBack.extendsEntity.explicitReference as CdmProjection).operations.length;
expect(actualOperationCount)
.toEqual(9);
const operations: CdmOperationCollection = (entityTestOperationCollectionReadBack.extendsEntity.explicitReference as CdmProjection).operations;
expect(operations.allItems[0].type)
.toEqual(cdmOperationType.addCountAttribute);
expect(operations.allItems[1].type)
.toEqual(cdmOperationType.addSupportingAttribute);
expect(operations.allItems[2].type)
.toEqual(cdmOperationType.addTypeAttribute);
expect(operations.allItems[3].type)
.toEqual(cdmOperationType.excludeAttributes);
expect(operations.allItems[4].type)
.toEqual(cdmOperationType.arrayExpansion);
expect(operations.allItems[5].type)
.toEqual(cdmOperationType.combineAttributes);
expect(operations.allItems[6].type)
.toEqual(cdmOperationType.renameAttributes);
expect(operations.allItems[7].type)
.toEqual(cdmOperationType.replaceAsForeignKey);
expect(operations.allItems[8].type)
.toEqual(cdmOperationType.includeAttributes);
});
/**
* Create a default manifest
*/
function createDefaultManifest(corpus: CdmCorpusDefinition, localRoot: CdmFolderDefinition) : CdmManifestDefinition {
const manifestName: string = 'default';
const manifestDocName: string = `${manifestName}.manifest.cdm.json`;
const manifestDefault: CdmManifestDefinition = corpus.MakeObject<CdmManifestDefinition>(cdmObjectType.manifestDef, manifestName);
localRoot.documents.push(manifestDefault, manifestDocName);
return manifestDefault;
}
/**
* Create a simple entity called 'TestSource' with a single attribute
*/
function createEntityTestSource(corpus: CdmCorpusDefinition, manifestDefault: CdmManifestDefinition, localRoot: CdmFolderDefinition) : CdmEntityDefinition {
const entityName: string = 'TestSource';
const entityTestSource: CdmEntityDefinition = corpus.MakeObject<CdmEntityDefinition>(cdmObjectType.entityDef, entityName);
const attributeName: string = 'TestAttribute';
const entityTestAttribute: CdmTypeAttributeDefinition = corpus.MakeObject<CdmTypeAttributeDefinition>(cdmObjectType.typeAttributeDef, attributeName, false);
entityTestAttribute.dataType = corpus.MakeRef<CdmDataTypeReference>(cdmObjectType.dataTypeRef, 'string', true);
entityTestAttribute.purpose = corpus.MakeRef<CdmPurposeReference>(cdmObjectType.purposeRef, 'hasA', true);
entityTestAttribute.displayName = attributeName;
entityTestSource.attributes.push(entityTestAttribute);
const entityTestSourceDoc: CdmDocumentDefinition = corpus.MakeObject<CdmDocumentDefinition>(cdmObjectType.documentDef, `${entityName}.cdm.json`, false);
entityTestSourceDoc.imports.push(foundationJsonPath);
entityTestSourceDoc.definitions.push(entityTestSource);
localRoot.documents.push(entityTestSourceDoc, entityTestSourceDoc.name);
manifestDefault.entities.push(entityTestSource);
return entityTestSource;
}
/**
* Create a simple projection object
*/
function createProjection(corpus: CdmCorpusDefinition) : CdmProjection {
const projection: CdmProjection = corpus.MakeObject<CdmProjection>(cdmObjectType.projectionDef);
projection.source = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, 'TestSource', true);
return projection;
}
/**
* Create a 3-level nested projection object
*/
function createNestedProjection(corpus: CdmCorpusDefinition): CdmProjection {
const projection3: CdmProjection = corpus.MakeObject<CdmProjection>(cdmObjectType.projectionDef);
projection3.source = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, 'TestSource', true);
const inlineProjectionEntityRef3: CdmEntityReference = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, undefined);
inlineProjectionEntityRef3.explicitReference = projection3;
const projection2: CdmProjection = corpus.MakeObject<CdmProjection>(cdmObjectType.projectionDef);
projection2.source = inlineProjectionEntityRef3;
const inlineProjectionEntityRef2: CdmEntityReference = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, undefined);
inlineProjectionEntityRef2.explicitReference = projection2;
const projection1: CdmProjection = corpus.MakeObject<CdmProjection>(cdmObjectType.projectionDef);
projection1.source = inlineProjectionEntityRef2;
return projection1;
}
/**
* Create an entity 'TestEntityProjection' that extends from a projection
*/
function createEntityTestEntityProjection(corpus: CdmCorpusDefinition, manifestDefault: CdmManifestDefinition, localRoot: CdmFolderDefinition) : CdmEntityDefinition {
const entityName: string = 'TestEntityProjection';
const inlineProjectionEntityRef: CdmEntityReference = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, undefined);
inlineProjectionEntityRef.explicitReference = createProjection(corpus);
const entityTestEntityProjection: CdmEntityDefinition = corpus.MakeObject<CdmEntityDefinition>(cdmObjectType.entityDef, entityName);
entityTestEntityProjection.extendsEntity = inlineProjectionEntityRef;
const entityTestEntityProjectionDoc: CdmDocumentDefinition = corpus.MakeObject<CdmDocumentDefinition>(cdmObjectType.documentDef, `${entityName}.cdm.json`, false);
entityTestEntityProjectionDoc.imports.push(foundationJsonPath);
entityTestEntityProjectionDoc.imports.push('TestSource.cdm.json');
entityTestEntityProjectionDoc.definitions.push(entityTestEntityProjection);
localRoot.documents.push(entityTestEntityProjectionDoc, entityTestEntityProjectionDoc.name);
manifestDefault.entities.push(entityTestEntityProjection);
return entityTestEntityProjection;
}
/**
* Create an entity 'TestEntityNestedProjection' that extends from a projection
*/
function createEntityTestEntityNestedProjection(corpus: CdmCorpusDefinition, manifestDefault: CdmManifestDefinition, localRoot: CdmFolderDefinition) : CdmEntityDefinition {
const entityName: string = 'TestEntityNestedProjection';
const inlineProjectionEntityRef: CdmEntityReference = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, undefined);
inlineProjectionEntityRef.explicitReference = createNestedProjection(corpus);
const entityTestEntityNestedProjection: CdmEntityDefinition = corpus.MakeObject<CdmEntityDefinition>(cdmObjectType.entityDef, entityName);
entityTestEntityNestedProjection.extendsEntity = inlineProjectionEntityRef;
const entityTestEntityNestedProjectionDoc: CdmDocumentDefinition = corpus.MakeObject<CdmDocumentDefinition>(cdmObjectType.documentDef, `${entityName}.cdm.json`, false);
entityTestEntityNestedProjectionDoc.imports.push(foundationJsonPath);
entityTestEntityNestedProjectionDoc.imports.push('TestSource.cdm.json');
entityTestEntityNestedProjectionDoc.definitions.push(entityTestEntityNestedProjection);
localRoot.documents.push(entityTestEntityNestedProjectionDoc, entityTestEntityNestedProjectionDoc.name);
manifestDefault.entities.push(entityTestEntityNestedProjection);
return entityTestEntityNestedProjection;
}
/**
* Create an entity 'TestEntityAttributeProjection' that contains an entity attribute with a projection as a source entity
*/
function createEntityTestEntityAttributeProjection(corpus: CdmCorpusDefinition, manifestDefault: CdmManifestDefinition, localRoot: CdmFolderDefinition) : CdmEntityDefinition {
const entityName: string = 'TestEntityAttributeProjection';
const inlineProjectionEntityRef: CdmEntityReference = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, undefined);
inlineProjectionEntityRef.explicitReference = createProjection(corpus);
const entityTestEntityAttributeProjection: CdmEntityDefinition = corpus.MakeObject<CdmEntityDefinition>(cdmObjectType.entityDef, entityName);
const attributeName: string = 'TestAttribute';
const entityTestEntityAttribute: CdmEntityAttributeDefinition = corpus.MakeObject<CdmEntityAttributeDefinition>(cdmObjectType.entityAttributeDef, attributeName, false);
entityTestEntityAttribute.entity = inlineProjectionEntityRef;
entityTestEntityAttributeProjection.attributes.push(entityTestEntityAttribute);
const entityTestEntityAttributeProjectionDoc: CdmDocumentDefinition = corpus.MakeObject<CdmDocumentDefinition>(cdmObjectType.documentDef, `${entityName}.cdm.json`, false);
entityTestEntityAttributeProjectionDoc.imports.push(foundationJsonPath);
entityTestEntityAttributeProjectionDoc.imports.push('TestSource.cdm.json');
entityTestEntityAttributeProjectionDoc.definitions.push(entityTestEntityAttributeProjection);
localRoot.documents.push(entityTestEntityAttributeProjectionDoc, entityTestEntityAttributeProjectionDoc.name);
manifestDefault.entities.push(entityTestEntityAttributeProjection);
return entityTestEntityAttributeProjection;
}
/**
* Create a projection object with operations
*/
function createProjectionWithOperationCollection(corpus: CdmCorpusDefinition, owner: CdmObject) : CdmProjection {
const projection: CdmProjection = corpus.MakeObject<CdmProjection>(cdmObjectType.projectionDef);
projection.source = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, 'TestSource', true);
// AddCountAttribute Operation
const addCountAttributeOp: CdmOperationAddCountAttribute = new CdmOperationAddCountAttribute(corpus.ctx);
addCountAttributeOp.countAttribute = corpus.MakeObject<CdmTypeAttributeDefinition>(cdmObjectType.typeAttributeDef);
projection.operations.push(addCountAttributeOp);
// AddSupportingAttribute Operation
const addSupportingAttributeOp: CdmOperationAddSupportingAttribute = new CdmOperationAddSupportingAttribute(corpus.ctx);
addSupportingAttributeOp.supportingAttribute = corpus.MakeObject<CdmTypeAttributeDefinition>(cdmObjectType.typeAttributeDef);
projection.operations.push(addSupportingAttributeOp);
// AddTypeAttribute Operation
const addTypeAttributeOp: CdmOperationAddTypeAttribute = new CdmOperationAddTypeAttribute(corpus.ctx);
addTypeAttributeOp.typeAttribute = corpus.MakeObject<CdmTypeAttributeDefinition>(cdmObjectType.typeAttributeDef);
projection.operations.push(addTypeAttributeOp);
// ExcludeAttributes Operation
const excludeAttributesOp: CdmOperationExcludeAttributes = new CdmOperationExcludeAttributes(corpus.ctx);
excludeAttributesOp.excludeAttributes = [];
excludeAttributesOp.excludeAttributes.push('testAttribute1');
projection.operations.push(excludeAttributesOp);
// ArrayExpansion Operation
const arrayExpansionOp: CdmOperationArrayExpansion = new CdmOperationArrayExpansion(corpus.ctx);
arrayExpansionOp.startOrdinal = 0;
arrayExpansionOp.endOrdinal = 1;
projection.operations.push(arrayExpansionOp);
// CombineAttributes Operation
const combineAttributesOp: CdmOperationCombineAttributes = new CdmOperationCombineAttributes(corpus.ctx);
combineAttributesOp.select = [];
combineAttributesOp.mergeInto = corpus.MakeObject<CdmTypeAttributeDefinition>(cdmObjectType.typeAttributeDef);
combineAttributesOp.select.push('testAttribute1');
projection.operations.push(combineAttributesOp);
// RenameAttributes Operation
const renameAttributesOp: CdmOperationRenameAttributes = new CdmOperationRenameAttributes(corpus.ctx);
renameAttributesOp.renameFormat = '{m}';
projection.operations.push(renameAttributesOp);
// ReplaceAsForeignKey Operation
const replaceAsForeignKeyOp: CdmOperationReplaceAsForeignKey = new CdmOperationReplaceAsForeignKey(corpus.ctx);
replaceAsForeignKeyOp.reference = 'testAttribute1';
replaceAsForeignKeyOp.replaceWith = corpus.MakeObject<CdmTypeAttributeDefinition>(cdmObjectType.typeAttributeDef, 'testForeignKey', false);
projection.operations.push(replaceAsForeignKeyOp);
// IncludeAttributes Operation
const includeAttributesOp: CdmOperationIncludeAttributes = new CdmOperationIncludeAttributes(corpus.ctx);
includeAttributesOp.includeAttributes = [];
includeAttributesOp.includeAttributes.push('testAttribute1');
projection.operations.push(includeAttributesOp);
return projection;
}
/**
* Create an entity 'TestOperationCollection' that extends from a projection with a collection of operations
*/
function createEntityTestOperationCollection(corpus: CdmCorpusDefinition, manifestDefault: CdmManifestDefinition, localRoot: CdmFolderDefinition) : CdmEntityDefinition {
const entityName: string = 'TestOperationCollection';
const inlineProjectionEntityRef: CdmEntityReference = corpus.MakeObject<CdmEntityReference>(cdmObjectType.entityRef, undefined);
const entityTestOperationCollection: CdmEntityDefinition = corpus.MakeObject<CdmEntityDefinition>(cdmObjectType.entityDef, entityName);
inlineProjectionEntityRef.explicitReference = createProjectionWithOperationCollection(corpus, entityTestOperationCollection);
entityTestOperationCollection.extendsEntity = inlineProjectionEntityRef;
const entityTestOperationCollectionDoc: CdmDocumentDefinition = corpus.MakeObject<CdmDocumentDefinition>(cdmObjectType.documentDef, `${entityName}.cdm.json`, false);
entityTestOperationCollectionDoc.imports.push(foundationJsonPath);
entityTestOperationCollectionDoc.imports.push('TestSource.cdm.json');
entityTestOperationCollectionDoc.definitions.push(entityTestOperationCollection);
localRoot.documents.push(entityTestOperationCollectionDoc, entityTestOperationCollectionDoc.name);
manifestDefault.entities.push(entityTestOperationCollection);
return entityTestOperationCollection;
}
}); | the_stack |
import * as coreClient from "@azure/core-client";
/** The resource model definition representing SKU */
export interface Sku {
/** The name of the SKU. Ex - P3. It is typically a letter+number code */
name: string;
/** This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. */
tier?: SkuTier;
/** The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. */
size?: string;
/** If the service has different generations of hardware, for the same SKU, then that can be captured here. */
family?: string;
/** If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. */
capacity?: number;
}
/** Identity for the resource. */
export interface Identity {
/** The identity type. */
type?: ResourceIdentityType;
/**
* The tenant ID of resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly tenantId?: string;
/**
* The principal ID of resource identity.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly principalId?: string;
/** The list of user assigned identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName} */
userAssignedIdentities?: { [propertyName: string]: UserAssignedIdentity };
}
/** User-assigned managed identity. */
export interface UserAssignedIdentity {
/**
* Azure Active Directory principal ID associated with this Identity.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly principalId?: string;
/**
* Client App Id associated with this identity.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly clientId?: string;
}
/** Metadata pertaining to creation and last modification of the resource. */
export interface SystemData {
/** The identity that created the resource. */
createdBy?: string;
/** The type of identity that created the resource. */
createdByType?: CreatedByType;
/** The timestamp of resource creation (UTC). */
createdAt?: Date;
/** The identity that last modified the resource. */
lastModifiedBy?: string;
/** The type of identity that last modified the resource. */
lastModifiedByType?: CreatedByType;
/** The timestamp of resource last modification (UTC) */
lastModifiedAt?: Date;
}
/** Properties of Cognitive Services account. */
export interface AccountProperties {
/**
* Gets the status of the cognitive services account at the time the operation was called.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ProvisioningState;
/**
* Endpoint of the created account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly endpoint?: string;
/**
* The internal identifier (deprecated, do not use this property).
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly internalId?: string;
/**
* Gets the capabilities of the cognitive services account. Each item indicates the capability of a specific feature. The values are read-only and for reference only.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly capabilities?: SkuCapability[];
/**
* If the resource is migrated from an existing key.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly isMigrated?: boolean;
/** Resource migration token. */
migrationToken?: string;
/**
* Sku change info of account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly skuChangeInfo?: SkuChangeInfo;
/** Optional subdomain name used for token-based authentication. */
customSubDomainName?: string;
/** A collection of rules governing the accessibility from specific network locations. */
networkAcls?: NetworkRuleSet;
/** The encryption properties for this resource. */
encryption?: Encryption;
/** The storage accounts for this resource. */
userOwnedStorage?: UserOwnedStorage[];
/**
* The private endpoint connection associated with the Cognitive Services account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly privateEndpointConnections?: PrivateEndpointConnection[];
/** Whether or not public endpoint access is allowed for this account. Value is optional but if passed in, must be 'Enabled' or 'Disabled' */
publicNetworkAccess?: PublicNetworkAccess;
/** The api properties for special APIs. */
apiProperties?: ApiProperties;
/**
* Gets the date of cognitive services account creation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly dateCreated?: string;
/**
* The call rate limit Cognitive Services account.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly callRateLimit?: CallRateLimit;
/** NOTE: This property will not be serialized. It can only be populated by the server. */
readonly quotaLimit?: QuotaLimit;
restrictOutboundNetworkAccess?: boolean;
allowedFqdnList?: string[];
disableLocalAuth?: boolean;
/**
* Dictionary of <string>
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly endpoints?: { [propertyName: string]: string };
restore?: boolean;
}
/** SkuCapability indicates the capability of a certain feature. */
export interface SkuCapability {
/** The name of the SkuCapability. */
name?: string;
/** The value of the SkuCapability. */
value?: string;
}
/** Sku change info of account. */
export interface SkuChangeInfo {
/** Gets the count of downgrades. */
countOfDowngrades?: number;
/** Gets the count of upgrades after downgrades. */
countOfUpgradesAfterDowngrades?: number;
/** Gets the last change date. */
lastChangeDate?: string;
}
/** A set of rules governing the network accessibility. */
export interface NetworkRuleSet {
/** The default action when no rule from ipRules and from virtualNetworkRules match. This is only used after the bypass property has been evaluated. */
defaultAction?: NetworkRuleAction;
/** The list of IP address rules. */
ipRules?: IpRule[];
/** The list of virtual network rules. */
virtualNetworkRules?: VirtualNetworkRule[];
}
/** A rule governing the accessibility from a specific ip address or ip range. */
export interface IpRule {
/** An IPv4 address range in CIDR notation, such as '124.56.78.91' (simple IP address) or '124.56.78.0/24' (all addresses that start with 124.56.78). */
value: string;
}
/** A rule governing the accessibility from a specific virtual network. */
export interface VirtualNetworkRule {
/** Full resource id of a vnet subnet, such as '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. */
id: string;
/** Gets the state of virtual network rule. */
state?: string;
/** Ignore missing vnet service endpoint or not. */
ignoreMissingVnetServiceEndpoint?: boolean;
}
/** Properties to configure Encryption */
export interface Encryption {
/** Properties of KeyVault */
keyVaultProperties?: KeyVaultProperties;
/** Enumerates the possible value of keySource for Encryption */
keySource?: KeySource;
}
/** Properties to configure keyVault Properties */
export interface KeyVaultProperties {
/** Name of the Key from KeyVault */
keyName?: string;
/** Version of the Key from KeyVault */
keyVersion?: string;
/** Uri of KeyVault */
keyVaultUri?: string;
identityClientId?: string;
}
/** The user owned storage for Cognitive Services account. */
export interface UserOwnedStorage {
/** Full resource id of a Microsoft.Storage resource. */
resourceId?: string;
identityClientId?: string;
}
/** Properties of the PrivateEndpointConnectProperties. */
export interface PrivateEndpointConnectionProperties {
/** The resource of private end point. */
privateEndpoint?: PrivateEndpoint;
/** A collection of information about the state of the connection between service consumer and provider. */
privateLinkServiceConnectionState: PrivateLinkServiceConnectionState;
/**
* The provisioning state of the private endpoint connection resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: PrivateEndpointConnectionProvisioningState;
/** The private link resource group ids. */
groupIds?: string[];
}
/** The Private Endpoint resource. */
export interface PrivateEndpoint {
/**
* The ARM identifier for Private Endpoint
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
}
/** A collection of information about the state of the connection between service consumer and provider. */
export interface PrivateLinkServiceConnectionState {
/** Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. */
status?: PrivateEndpointServiceConnectionStatus;
/** The reason for approval/rejection of the connection. */
description?: string;
/** A message indicating if changes on the service provider require any updates on the consumer. */
actionsRequired?: string;
}
/** Common fields that are returned in the response for all Azure Resource Manager resources */
export interface Resource {
/**
* Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The name of the resource
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
}
/** The api properties for special APIs. */
export interface ApiProperties {
/** Describes unknown properties. The value of an unknown property can be of "any" type. */
[property: string]: any;
/** (QnAMaker Only) The runtime endpoint of QnAMaker. */
qnaRuntimeEndpoint?: string;
/** (QnAMaker Only) The Azure Search endpoint key of QnAMaker. */
qnaAzureSearchEndpointKey?: string;
/** (QnAMaker Only) The Azure Search endpoint id of QnAMaker. */
qnaAzureSearchEndpointId?: string;
/** (Bing Search Only) The flag to enable statistics of Bing Search. */
statisticsEnabled?: boolean;
/** (Personalization Only) The flag to enable statistics of Bing Search. */
eventHubConnectionString?: string;
/** (Personalization Only) The storage account connection string. */
storageAccountConnectionString?: string;
/** (Metrics Advisor Only) The Azure AD Client Id (Application Id). */
aadClientId?: string;
/** (Metrics Advisor Only) The Azure AD Tenant Id. */
aadTenantId?: string;
/** (Metrics Advisor Only) The super user of Metrics Advisor. */
superUser?: string;
/** (Metrics Advisor Only) The website name of Metrics Advisor. */
websiteName?: string;
}
/** The call rate limit Cognitive Services account. */
export interface CallRateLimit {
/** The count value of Call Rate Limit. */
count?: number;
/** The renewal period in seconds of Call Rate Limit. */
renewalPeriod?: number;
rules?: ThrottlingRule[];
}
export interface ThrottlingRule {
key?: string;
renewalPeriod?: number;
count?: number;
minCount?: number;
dynamicThrottlingEnabled?: boolean;
matchPatterns?: RequestMatchPattern[];
}
export interface RequestMatchPattern {
path?: string;
method?: string;
}
export interface QuotaLimit {
count?: number;
renewalPeriod?: number;
rules?: ThrottlingRule[];
}
/** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */
export interface ErrorResponse {
/** The error object. */
error?: ErrorDetail;
}
/** The error detail. */
export interface ErrorDetail {
/**
* The error code.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly code?: string;
/**
* The error message.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly message?: string;
/**
* The error target.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly target?: string;
/**
* The error details.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly details?: ErrorDetail[];
/**
* The error additional info.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/** The resource management error additional info. */
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The additional info.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly info?: Record<string, unknown>;
}
/** The list of cognitive services accounts operation response. */
export interface AccountListResult {
/** The link used to get the next page of accounts. */
nextLink?: string;
/**
* Gets the list of Cognitive Services accounts and their properties.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: Account[];
}
/** The access keys for the cognitive services account. */
export interface ApiKeys {
/** Gets the value of key 1. */
key1?: string;
/** Gets the value of key 2. */
key2?: string;
}
/** Regenerate key parameters. */
export interface RegenerateKeyParameters {
/** key name to generate (Key1|Key2) */
keyName: KeyName;
}
/** The Get Skus operation response. */
export interface ResourceSkuListResult {
/** The list of skus available for the subscription. */
value: ResourceSku[];
/** The uri to fetch the next page of Skus. */
nextLink?: string;
}
/** Describes an available Cognitive Services SKU. */
export interface ResourceSku {
/** The type of resource the SKU applies to. */
resourceType?: string;
/** The name of SKU. */
name?: string;
/** Specifies the tier of Cognitive Services account. */
tier?: string;
/** The Kind of resources that are supported in this SKU. */
kind?: string;
/** The set of locations that the SKU is available. */
locations?: string[];
/** The restrictions because of which SKU cannot be used. This is empty if there are no restrictions. */
restrictions?: ResourceSkuRestrictions[];
}
/** Describes restrictions of a SKU. */
export interface ResourceSkuRestrictions {
/** The type of restrictions. */
type?: ResourceSkuRestrictionsType;
/** The value of restrictions. If the restriction type is set to location. This would be different locations where the SKU is restricted. */
values?: string[];
/** The information about the restriction where the SKU cannot be used. */
restrictionInfo?: ResourceSkuRestrictionInfo;
/** The reason for restriction. */
reasonCode?: ResourceSkuRestrictionsReasonCode;
}
export interface ResourceSkuRestrictionInfo {
/** Locations where the SKU is restricted */
locations?: string[];
/** List of availability zones where the SKU is restricted. */
zones?: string[];
}
/** The list of cognitive services accounts operation response. */
export interface AccountSkuListResult {
/** Gets the list of Cognitive Services accounts and their properties. */
value?: AccountSku[];
}
/** Cognitive Services resource type and SKU. */
export interface AccountSku {
/** Resource Namespace and Type */
resourceType?: string;
/** The SKU of Cognitive Services account. */
sku?: Sku;
}
/** The response to a list usage request. */
export interface UsageListResult {
/** The list of usages for Cognitive Service account. */
value?: Usage[];
}
/** The usage data for a usage request. */
export interface Usage {
/** The unit of the metric. */
unit?: UnitType;
/** The name information for the metric. */
name?: MetricName;
/** The quota period used to summarize the usage values. */
quotaPeriod?: string;
/** Maximum value for this metric. */
limit?: number;
/** Current value for this metric. */
currentValue?: number;
/** Next reset time for current quota. */
nextResetTime?: string;
/** Cognitive Services account quota usage status. */
status?: QuotaUsageStatus;
}
/** A metric name. */
export interface MetricName {
/** The name of the metric. */
value?: string;
/** The friendly name of the metric. */
localizedValue?: string;
}
/** A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. */
export interface OperationListResult {
/**
* List of operations supported by the resource provider
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: Operation[];
/**
* URL to get the next set of operation list results (if there are any).
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Details of a REST API operation, returned from the Resource Provider Operations API */
export interface Operation {
/**
* The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for ARM/control-plane operations.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly isDataAction?: boolean;
/** Localized display information for this particular operation. */
display?: OperationDisplay;
/**
* The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly origin?: Origin;
/**
* Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly actionType?: ActionType;
}
/** Localized display information for this particular operation. */
export interface OperationDisplay {
/**
* The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute".
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provider?: string;
/**
* The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections".
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly resource?: string;
/**
* The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine".
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly operation?: string;
/**
* The short, localized friendly description of the operation; suitable for tool tips and detailed views.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly description?: string;
}
/** Check SKU availability parameter. */
export interface CheckSkuAvailabilityParameter {
/** The SKU of the resource. */
skus: string[];
/** The Kind of the resource. */
kind: string;
/** The Type of the resource. */
type: string;
}
/** Check SKU availability result list. */
export interface SkuAvailabilityListResult {
/** Check SKU availability result list. */
value?: SkuAvailability[];
}
/** SKU availability. */
export interface SkuAvailability {
/** The Kind of the resource. */
kind?: string;
/** The Type of the resource. */
type?: string;
/** The SKU of Cognitive Services account. */
skuName?: string;
/** Indicates the given SKU is available or not. */
skuAvailable?: boolean;
/** Reason why the SKU is not available. */
reason?: string;
/** Additional error message. */
message?: string;
}
/** The list of cognitive services accounts operation response. */
export interface CommitmentTierListResult {
/** The link used to get the next page of CommitmentTier. */
nextLink?: string;
/**
* Gets the list of Cognitive Services accounts CommitmentTier and their properties.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: CommitmentTier[];
}
/** Cognitive Services account commitment tier. */
export interface CommitmentTier {
/** The Kind of the resource. */
kind?: string;
/** The name of the SKU. Ex - P3. It is typically a letter+number code */
skuName?: string;
/** Account hosting model. */
hostingModel?: HostingModel;
/** Commitment plan type. */
planType?: string;
/** Commitment period commitment tier. */
tier?: string;
/** Commitment period commitment max count. */
maxCount?: number;
/** Cognitive Services account commitment quota. */
quota?: CommitmentQuota;
/** Cognitive Services account commitment cost. */
cost?: CommitmentCost;
}
/** Cognitive Services account commitment quota. */
export interface CommitmentQuota {
/** Commitment quota quantity. */
quantity?: number;
/** Commitment quota unit. */
unit?: string;
}
/** Cognitive Services account commitment cost. */
export interface CommitmentCost {
/** Commitment meter Id. */
commitmentMeterId?: string;
/** Overage meter Id. */
overageMeterId?: string;
}
/** Check Domain availability parameter. */
export interface CheckDomainAvailabilityParameter {
/** The subdomain name to use. */
subdomainName: string;
/** The Type of the resource. */
type: string;
/** The Kind of the resource. */
kind?: string;
}
/** Domain availability. */
export interface DomainAvailability {
/** Indicates the given SKU is available or not. */
isSubdomainAvailable?: boolean;
/** Reason why the SKU is not available. */
reason?: string;
/** The subdomain name to use. */
subdomainName?: string;
/** The Type of the resource. */
type?: string;
/** The Kind of the resource. */
kind?: string;
}
/** A list of private endpoint connections */
export interface PrivateEndpointConnectionListResult {
/** Array of private endpoint connections */
value?: PrivateEndpointConnection[];
}
/** A list of private link resources */
export interface PrivateLinkResourceListResult {
/** Array of private link resources */
value?: PrivateLinkResource[];
}
/** Properties of a private link resource. */
export interface PrivateLinkResourceProperties {
/**
* The private link resource group id.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly groupId?: string;
/**
* The private link resource required member names.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly requiredMembers?: string[];
/** The private link resource Private link DNS zone name. */
requiredZoneNames?: string[];
/**
* The private link resource display name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly displayName?: string;
}
/** The list of cognitive services accounts operation response. */
export interface DeploymentListResult {
/** The link used to get the next page of Deployment. */
nextLink?: string;
/**
* Gets the list of Cognitive Services accounts Deployment and their properties.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: Deployment[];
}
/** Properties of Cognitive Services account deployment. */
export interface DeploymentProperties {
/**
* Gets the status of the resource at the time the operation was called.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: DeploymentProvisioningState;
/** Properties of Cognitive Services account deployment model. */
model?: DeploymentModel;
/** Properties of Cognitive Services account deployment model. */
scaleSettings?: DeploymentScaleSettings;
}
/** Properties of Cognitive Services account deployment model. */
export interface DeploymentModel {
/** Deployment model format. */
format?: string;
/** Deployment model name. */
name?: string;
/** Deployment model version. */
version?: string;
}
/** Properties of Cognitive Services account deployment model. */
export interface DeploymentScaleSettings {
/** Deployment scale type. */
scaleType?: DeploymentScaleType;
/** Deployment capacity. */
capacity?: number;
}
/** The list of cognitive services accounts operation response. */
export interface CommitmentPlanListResult {
/** The link used to get the next page of CommitmentPlan. */
nextLink?: string;
/**
* Gets the list of Cognitive Services accounts CommitmentPlan and their properties.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: CommitmentPlan[];
}
/** Properties of Cognitive Services account commitment plan. */
export interface CommitmentPlanProperties {
/** Account hosting model. */
hostingModel?: HostingModel;
/** Commitment plan type. */
planType?: string;
/** Cognitive Services account commitment period. */
current?: CommitmentPeriod;
/** AutoRenew commitment plan. */
autoRenew?: boolean;
/** Cognitive Services account commitment period. */
next?: CommitmentPeriod;
/**
* Cognitive Services account commitment period.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly last?: CommitmentPeriod;
}
/** Cognitive Services account commitment period. */
export interface CommitmentPeriod {
/** Commitment period commitment tier. */
tier?: string;
/** Commitment period commitment count. */
count?: number;
/**
* Cognitive Services account commitment quota.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly quota?: CommitmentQuota;
/**
* Commitment period start date.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly startDate?: string;
/**
* Commitment period end date.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly endDate?: string;
}
/** The resource model definition for an Azure Resource Manager resource with an etag. */
export type AzureEntityResource = Resource & {
/**
* Resource Etag.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly etag?: string;
};
/** A private link resource */
export type PrivateLinkResource = Resource & {
/** Resource properties. */
properties?: PrivateLinkResourceProperties;
};
/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */
export type ProxyResource = Resource & {};
/** The Private Endpoint Connection resource. */
export type PrivateEndpointConnection = AzureEntityResource & {
/** Resource properties. */
properties?: PrivateEndpointConnectionProperties;
/**
* Metadata pertaining to creation and last modification of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
/** The location of the private endpoint connection */
location?: string;
};
/** Cognitive Services account is an Azure resource representing the provisioned account, it's type, location and SKU. */
export type Account = AzureEntityResource & {
/** The Kind of the resource. */
kind?: string;
/** The resource model definition representing SKU */
sku?: Sku;
/** Identity for the resource. */
identity?: Identity;
/**
* Metadata pertaining to creation and last modification of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
/** Resource tags. */
tags?: { [propertyName: string]: string };
/** The geo-location where the resource lives */
location?: string;
/** Properties of Cognitive Services account. */
properties?: AccountProperties;
};
/** Cognitive Services account deployment. */
export type Deployment = ProxyResource & {
/**
* Metadata pertaining to creation and last modification of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
/**
* Resource Etag.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly etag?: string;
/** Properties of Cognitive Services account deployment. */
properties?: DeploymentProperties;
};
/** Cognitive Services account commitment plan. */
export type CommitmentPlan = ProxyResource & {
/**
* Metadata pertaining to creation and last modification of the resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
/**
* Resource Etag.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly etag?: string;
/** Properties of Cognitive Services account commitment plan. */
properties?: CommitmentPlanProperties;
};
/** Known values of {@link SkuTier} that the service accepts. */
export enum KnownSkuTier {
Free = "Free",
Basic = "Basic",
Standard = "Standard",
Premium = "Premium",
Enterprise = "Enterprise"
}
/**
* Defines values for SkuTier. \
* {@link KnownSkuTier} can be used interchangeably with SkuTier,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Free** \
* **Basic** \
* **Standard** \
* **Premium** \
* **Enterprise**
*/
export type SkuTier = string;
/** Known values of {@link CreatedByType} that the service accepts. */
export enum KnownCreatedByType {
User = "User",
Application = "Application",
ManagedIdentity = "ManagedIdentity",
Key = "Key"
}
/**
* Defines values for CreatedByType. \
* {@link KnownCreatedByType} can be used interchangeably with CreatedByType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **User** \
* **Application** \
* **ManagedIdentity** \
* **Key**
*/
export type CreatedByType = string;
/** Known values of {@link ProvisioningState} that the service accepts. */
export enum KnownProvisioningState {
Accepted = "Accepted",
Creating = "Creating",
Deleting = "Deleting",
Moving = "Moving",
Failed = "Failed",
Succeeded = "Succeeded",
ResolvingDNS = "ResolvingDNS"
}
/**
* Defines values for ProvisioningState. \
* {@link KnownProvisioningState} can be used interchangeably with ProvisioningState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Accepted** \
* **Creating** \
* **Deleting** \
* **Moving** \
* **Failed** \
* **Succeeded** \
* **ResolvingDNS**
*/
export type ProvisioningState = string;
/** Known values of {@link NetworkRuleAction} that the service accepts. */
export enum KnownNetworkRuleAction {
Allow = "Allow",
Deny = "Deny"
}
/**
* Defines values for NetworkRuleAction. \
* {@link KnownNetworkRuleAction} can be used interchangeably with NetworkRuleAction,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Allow** \
* **Deny**
*/
export type NetworkRuleAction = string;
/** Known values of {@link KeySource} that the service accepts. */
export enum KnownKeySource {
MicrosoftCognitiveServices = "Microsoft.CognitiveServices",
MicrosoftKeyVault = "Microsoft.KeyVault"
}
/**
* Defines values for KeySource. \
* {@link KnownKeySource} can be used interchangeably with KeySource,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Microsoft.CognitiveServices** \
* **Microsoft.KeyVault**
*/
export type KeySource = string;
/** Known values of {@link PrivateEndpointServiceConnectionStatus} that the service accepts. */
export enum KnownPrivateEndpointServiceConnectionStatus {
Pending = "Pending",
Approved = "Approved",
Rejected = "Rejected"
}
/**
* Defines values for PrivateEndpointServiceConnectionStatus. \
* {@link KnownPrivateEndpointServiceConnectionStatus} can be used interchangeably with PrivateEndpointServiceConnectionStatus,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Pending** \
* **Approved** \
* **Rejected**
*/
export type PrivateEndpointServiceConnectionStatus = string;
/** Known values of {@link PrivateEndpointConnectionProvisioningState} that the service accepts. */
export enum KnownPrivateEndpointConnectionProvisioningState {
Succeeded = "Succeeded",
Creating = "Creating",
Deleting = "Deleting",
Failed = "Failed"
}
/**
* Defines values for PrivateEndpointConnectionProvisioningState. \
* {@link KnownPrivateEndpointConnectionProvisioningState} can be used interchangeably with PrivateEndpointConnectionProvisioningState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Succeeded** \
* **Creating** \
* **Deleting** \
* **Failed**
*/
export type PrivateEndpointConnectionProvisioningState = string;
/** Known values of {@link PublicNetworkAccess} that the service accepts. */
export enum KnownPublicNetworkAccess {
Enabled = "Enabled",
Disabled = "Disabled"
}
/**
* Defines values for PublicNetworkAccess. \
* {@link KnownPublicNetworkAccess} can be used interchangeably with PublicNetworkAccess,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Enabled** \
* **Disabled**
*/
export type PublicNetworkAccess = string;
/** Known values of {@link ResourceSkuRestrictionsReasonCode} that the service accepts. */
export enum KnownResourceSkuRestrictionsReasonCode {
QuotaId = "QuotaId",
NotAvailableForSubscription = "NotAvailableForSubscription"
}
/**
* Defines values for ResourceSkuRestrictionsReasonCode. \
* {@link KnownResourceSkuRestrictionsReasonCode} can be used interchangeably with ResourceSkuRestrictionsReasonCode,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **QuotaId** \
* **NotAvailableForSubscription**
*/
export type ResourceSkuRestrictionsReasonCode = string;
/** Known values of {@link UnitType} that the service accepts. */
export enum KnownUnitType {
Count = "Count",
Bytes = "Bytes",
Seconds = "Seconds",
Percent = "Percent",
CountPerSecond = "CountPerSecond",
BytesPerSecond = "BytesPerSecond",
Milliseconds = "Milliseconds"
}
/**
* Defines values for UnitType. \
* {@link KnownUnitType} can be used interchangeably with UnitType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Count** \
* **Bytes** \
* **Seconds** \
* **Percent** \
* **CountPerSecond** \
* **BytesPerSecond** \
* **Milliseconds**
*/
export type UnitType = string;
/** Known values of {@link QuotaUsageStatus} that the service accepts. */
export enum KnownQuotaUsageStatus {
Included = "Included",
Blocked = "Blocked",
InOverage = "InOverage",
Unknown = "Unknown"
}
/**
* Defines values for QuotaUsageStatus. \
* {@link KnownQuotaUsageStatus} can be used interchangeably with QuotaUsageStatus,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Included** \
* **Blocked** \
* **InOverage** \
* **Unknown**
*/
export type QuotaUsageStatus = string;
/** Known values of {@link Origin} that the service accepts. */
export enum KnownOrigin {
User = "user",
System = "system",
UserSystem = "user,system"
}
/**
* Defines values for Origin. \
* {@link KnownOrigin} can be used interchangeably with Origin,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **user** \
* **system** \
* **user,system**
*/
export type Origin = string;
/** Known values of {@link ActionType} that the service accepts. */
export enum KnownActionType {
Internal = "Internal"
}
/**
* Defines values for ActionType. \
* {@link KnownActionType} can be used interchangeably with ActionType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Internal**
*/
export type ActionType = string;
/** Known values of {@link HostingModel} that the service accepts. */
export enum KnownHostingModel {
Web = "Web",
ConnectedContainer = "ConnectedContainer",
DisconnectedContainer = "DisconnectedContainer"
}
/**
* Defines values for HostingModel. \
* {@link KnownHostingModel} can be used interchangeably with HostingModel,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Web** \
* **ConnectedContainer** \
* **DisconnectedContainer**
*/
export type HostingModel = string;
/** Known values of {@link DeploymentProvisioningState} that the service accepts. */
export enum KnownDeploymentProvisioningState {
Accepted = "Accepted",
Creating = "Creating",
Deleting = "Deleting",
Moving = "Moving",
Failed = "Failed",
Succeeded = "Succeeded"
}
/**
* Defines values for DeploymentProvisioningState. \
* {@link KnownDeploymentProvisioningState} can be used interchangeably with DeploymentProvisioningState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Accepted** \
* **Creating** \
* **Deleting** \
* **Moving** \
* **Failed** \
* **Succeeded**
*/
export type DeploymentProvisioningState = string;
/** Known values of {@link DeploymentScaleType} that the service accepts. */
export enum KnownDeploymentScaleType {
Manual = "Manual"
}
/**
* Defines values for DeploymentScaleType. \
* {@link KnownDeploymentScaleType} can be used interchangeably with DeploymentScaleType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Manual**
*/
export type DeploymentScaleType = string;
/** Defines values for ResourceIdentityType. */
export type ResourceIdentityType =
| "None"
| "SystemAssigned"
| "UserAssigned"
| "SystemAssigned, UserAssigned";
/** Defines values for KeyName. */
export type KeyName = "Key1" | "Key2";
/** Defines values for ResourceSkuRestrictionsType. */
export type ResourceSkuRestrictionsType = "Location" | "Zone";
/** Optional parameters. */
export interface AccountsCreateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the create operation. */
export type AccountsCreateResponse = Account;
/** Optional parameters. */
export interface AccountsUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the update operation. */
export type AccountsUpdateResponse = Account;
/** Optional parameters. */
export interface AccountsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface AccountsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type AccountsGetResponse = Account;
/** Optional parameters. */
export interface AccountsListByResourceGroupOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroup operation. */
export type AccountsListByResourceGroupResponse = AccountListResult;
/** Optional parameters. */
export interface AccountsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type AccountsListResponse = AccountListResult;
/** Optional parameters. */
export interface AccountsListKeysOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listKeys operation. */
export type AccountsListKeysResponse = ApiKeys;
/** Optional parameters. */
export interface AccountsRegenerateKeyOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the regenerateKey operation. */
export type AccountsRegenerateKeyResponse = ApiKeys;
/** Optional parameters. */
export interface AccountsListSkusOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listSkus operation. */
export type AccountsListSkusResponse = AccountSkuListResult;
/** Optional parameters. */
export interface AccountsListUsagesOptionalParams
extends coreClient.OperationOptions {
/** An OData filter expression that describes a subset of usages to return. The supported parameter is name.value (name of the metric, can have an or of multiple names). */
filter?: string;
}
/** Contains response data for the listUsages operation. */
export type AccountsListUsagesResponse = UsageListResult;
/** Optional parameters. */
export interface AccountsListByResourceGroupNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroupNext operation. */
export type AccountsListByResourceGroupNextResponse = AccountListResult;
/** Optional parameters. */
export interface AccountsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type AccountsListNextResponse = AccountListResult;
/** Optional parameters. */
export interface DeletedAccountsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type DeletedAccountsGetResponse = Account;
/** Optional parameters. */
export interface DeletedAccountsPurgeOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface DeletedAccountsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type DeletedAccountsListResponse = AccountListResult;
/** Optional parameters. */
export interface DeletedAccountsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type DeletedAccountsListNextResponse = AccountListResult;
/** Optional parameters. */
export interface ResourceSkusListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type ResourceSkusListResponse = ResourceSkuListResult;
/** Optional parameters. */
export interface ResourceSkusListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type ResourceSkusListNextResponse = ResourceSkuListResult;
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationListResult;
/** Optional parameters. */
export interface OperationsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type OperationsListNextResponse = OperationListResult;
/** Optional parameters. */
export interface CheckSkuAvailabilityOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the checkSkuAvailability operation. */
export type CheckSkuAvailabilityResponse = SkuAvailabilityListResult;
/** Optional parameters. */
export interface CheckDomainAvailabilityOptionalParams
extends coreClient.OperationOptions {
/** The Kind of the resource. */
kind?: string;
}
/** Contains response data for the checkDomainAvailability operation. */
export type CheckDomainAvailabilityResponse = DomainAvailability;
/** Optional parameters. */
export interface CommitmentTiersListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type CommitmentTiersListResponse = CommitmentTierListResult;
/** Optional parameters. */
export interface CommitmentTiersListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type CommitmentTiersListNextResponse = CommitmentTierListResult;
/** Optional parameters. */
export interface PrivateEndpointConnectionsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type PrivateEndpointConnectionsListResponse = PrivateEndpointConnectionListResult;
/** Optional parameters. */
export interface PrivateEndpointConnectionsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface PrivateEndpointConnectionsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type PrivateEndpointConnectionsCreateOrUpdateResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface PrivateEndpointConnectionsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface PrivateLinkResourcesListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type PrivateLinkResourcesListResponse = PrivateLinkResourceListResult;
/** Optional parameters. */
export interface DeploymentsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type DeploymentsListResponse = DeploymentListResult;
/** Optional parameters. */
export interface DeploymentsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type DeploymentsGetResponse = Deployment;
/** Optional parameters. */
export interface DeploymentsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type DeploymentsCreateOrUpdateResponse = Deployment;
/** Optional parameters. */
export interface DeploymentsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface DeploymentsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type DeploymentsListNextResponse = DeploymentListResult;
/** Optional parameters. */
export interface CommitmentPlansListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type CommitmentPlansListResponse = CommitmentPlanListResult;
/** Optional parameters. */
export interface CommitmentPlansGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type CommitmentPlansGetResponse = CommitmentPlan;
/** Optional parameters. */
export interface CommitmentPlansCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type CommitmentPlansCreateOrUpdateResponse = CommitmentPlan;
/** Optional parameters. */
export interface CommitmentPlansDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface CommitmentPlansListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type CommitmentPlansListNextResponse = CommitmentPlanListResult;
/** Optional parameters. */
export interface CognitiveServicesManagementClientOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import _ from 'lodash'
import la from 'lazy-ass'
import Debug from 'debug'
import Bluebird from 'bluebird'
import chokidar from 'chokidar'
import pluralize from 'pluralize'
import { ProjectBase, OpenProjectLaunchOptions } from './project-base'
import browsers from './browsers'
import specsUtil from './util/specs'
import preprocessor from './plugins/preprocessor'
import runEvents from './plugins/run_events'
import * as session from './session'
import { getSpecUrl } from './project_utils'
import errors from './errors'
import type { Browser, FoundBrowser, PlatformName } from '@packages/launcher'
import type { AutomationMiddleware } from './automation'
import { fs } from './util/fs'
import path from 'path'
import os from 'os'
const debug = Debug('cypress:server:open_project')
interface LaunchOpts {
browser?: FoundBrowser
url?: string
automationMiddleware?: AutomationMiddleware
onBrowserClose?: (...args: unknown[]) => void
onError?: (err: Error) => void
}
interface SpecsByType {
component: Cypress.Spec[]
integration: Cypress.Spec[]
}
export interface LaunchArgs {
_: [string] // Cypress App binary location
config: Record<string, unknown>
cwd: string
browser?: Browser['name']
configFile?: string
exit?: boolean
project: string // projectRoot
projectRoot: string // same as above
testingType: Cypress.TestingType
invokedFromCli: boolean
os: PlatformName
onFocusTests?: () => any
/**
* in run mode, the path of the project run
* path is relative if specified with --project,
* absolute if implied by current working directory
*/
runProject?: string
}
// @see https://github.com/cypress-io/cypress/issues/18094
async function win32BitWarning (onWarning: (error: Error) => void) {
if (os.platform() !== 'win32' || os.arch() !== 'ia32') return
// adapted from https://github.com/feross/arch/blob/master/index.js
let useEnv = false
try {
useEnv = !!(process.env.SYSTEMROOT && await fs.stat(process.env.SYSTEMROOT))
} catch (err) {
// pass
}
const sysRoot = useEnv ? process.env.SYSTEMROOT! : 'C:\\Windows'
// If %SystemRoot%\SysNative exists, we are in a WOW64 FS Redirected application.
let hasX64 = false
try {
hasX64 = !!(await fs.stat(path.join(sysRoot, 'sysnative')))
} catch (err) {
// pass
}
onWarning(errors.get('WIN32_DEPRECATION', hasX64))
}
export class OpenProject {
openProject: ProjectBase<any> | null = null
relaunchBrowser: ((...args: unknown[]) => void) | null = null
specsWatcher: chokidar.FSWatcher | null = null
componentSpecsWatcher: chokidar.FSWatcher | null = null
resetOpenProject () {
this.openProject = null
this.relaunchBrowser = null
}
tryToCall (method: keyof ProjectBase<any>) {
return (...args: unknown[]) => {
if (this.openProject && this.openProject[method]) {
return this.openProject[method](...args)
}
return Bluebird.resolve(null)
}
}
reset () {
this.resetOpenProject()
}
getConfig () {
return this.openProject!.getConfig()
}
getRecordKeys = this.tryToCall('getRecordKeys')
getRuns = this.tryToCall('getRuns')
requestAccess = this.tryToCall('requestAccess')
getProject () {
return this.openProject
}
changeUrlToSpec (spec: Cypress.Cypress['spec']) {
if (!this.openProject) {
return
}
const newSpecUrl = getSpecUrl({
absoluteSpecPath: spec.absolute,
specType: spec.specType,
browserUrl: this.openProject.cfg.browserUrl,
integrationFolder: this.openProject.cfg.integrationFolder || 'integration',
componentFolder: this.openProject.cfg.componentFolder || 'component',
projectRoot: this.openProject.projectRoot,
})
this.openProject.changeToUrl(newSpecUrl)
}
launch (browser, spec: Cypress.Cypress['spec'], options: LaunchOpts = {
onError: () => undefined,
}) {
if (!this.openProject) {
throw Error('Cannot launch runner if openProject is undefined!')
}
debug('resetting project state, preparing to launch browser %s for spec %o options %o',
browser.name, spec, options)
la(_.isPlainObject(browser), 'expected browser object:', browser)
// reset to reset server and socket state because
// of potential domain changes, request buffers, etc
this.openProject!.reset()
const url = getSpecUrl({
absoluteSpecPath: spec.absolute,
specType: spec.specType,
browserUrl: this.openProject.cfg.browserUrl,
integrationFolder: this.openProject.cfg.integrationFolder || 'integration',
componentFolder: this.openProject.cfg.componentFolder || 'component?',
projectRoot: this.openProject.projectRoot,
})
debug('open project url %s', url)
const cfg = this.openProject.getConfig()
_.defaults(options, {
browsers: cfg.browsers,
userAgent: cfg.userAgent,
proxyUrl: cfg.proxyUrl,
proxyServer: cfg.proxyServer,
socketIoRoute: cfg.socketIoRoute,
chromeWebSecurity: cfg.chromeWebSecurity,
isTextTerminal: cfg.isTextTerminal,
downloadsFolder: cfg.downloadsFolder,
})
// if we don't have the isHeaded property
// then we're in interactive mode and we
// can assume its a headed browser
// TODO: we should clean this up
if (!_.has(browser, 'isHeaded')) {
browser.isHeaded = true
browser.isHeadless = false
}
// set the current browser object on options
// so we can pass it down
options.browser = browser
options.url = url
this.openProject.setCurrentSpecAndBrowser(spec, browser)
const automation = this.openProject.getAutomation()
// use automation middleware if its
// been defined here
let am = options.automationMiddleware
if (am) {
automation.use(am)
}
if (!am || !am.onBeforeRequest) {
automation.use({
onBeforeRequest (message, data) {
if (message === 'take:screenshot') {
data.specName = spec.name
return data
}
},
})
}
const afterSpec = () => {
if (!this.openProject || cfg.isTextTerminal || !cfg.experimentalInteractiveRunEvents) {
return Bluebird.resolve()
}
return runEvents.execute('after:spec', cfg, spec)
}
const { onBrowserClose } = options
options.onBrowserClose = () => {
if (spec && spec.absolute) {
preprocessor.removeFile(spec.absolute, cfg)
}
afterSpec()
.catch((err) => {
this.openProject!.options.onError(err)
})
if (onBrowserClose) {
return onBrowserClose()
}
}
options.onError = this.openProject.options.onError
this.relaunchBrowser = () => {
debug(
'launching browser: %o, spec: %s',
browser,
spec.relative,
)
return Bluebird.try(() => {
if (!cfg.isTextTerminal && cfg.experimentalInteractiveRunEvents) {
return runEvents.execute('before:spec', cfg, spec)
}
// clear all session data before each spec
session.clearSessions()
})
.then(() => {
return browsers.open(browser, options, automation)
})
}
return this.relaunchBrowser()
}
getSpecs (cfg) {
return specsUtil.findSpecs(cfg)
.then((specs: Cypress.Spec[] = []) => {
// TODO merge logic with "run.js"
if (debug.enabled) {
const names = _.map(specs, 'name')
debug(
'found %s using spec pattern \'%s\': %o',
pluralize('spec', names.length, true),
cfg.testFiles,
names,
)
}
const componentTestingEnabled = _.get(cfg, 'resolved.testingType.value', 'e2e') === 'component'
if (componentTestingEnabled) {
// separate specs into integration and component lists
// note: _.remove modifies the array in place and returns removed elements
const component = _.remove(specs, { specType: 'component' })
return {
integration: specs,
component,
}
}
// assumes all specs are integration specs
return {
integration: specs.filter((x) => x.specType === 'integration'),
component: [],
}
})
}
getSpecChanges (options: OpenProjectLaunchOptions = {}) {
let currentSpecs: SpecsByType
_.defaults(options, {
onChange: () => { },
onError: () => { },
})
const sendIfChanged = (specs: SpecsByType = { component: [], integration: [] }) => {
// dont do anything if the specs haven't changed
if (_.isEqual(specs, currentSpecs)) {
return
}
currentSpecs = specs
return options?.onChange?.(specs)
}
const checkForSpecUpdates = _.debounce(() => {
if (!this.openProject) {
return this.stopSpecsWatcher()
}
debug('check for spec updates')
return get()
.then(sendIfChanged)
.catch(options?.onError)
}, 250, { leading: true })
const createSpecsWatcher = (cfg) => {
// TODO I keep repeating this to get the resolved value
// probably better to have a single function that does this
const componentTestingEnabled = _.get(cfg, 'resolved.testingType.value', 'e2e') === 'component'
debug('createSpecWatch component testing enabled', componentTestingEnabled)
if (!this.specsWatcher) {
debug('watching integration test files: %s in %s', cfg.testFiles, cfg.integrationFolder)
this.specsWatcher = chokidar.watch(cfg.testFiles, {
cwd: cfg.integrationFolder,
ignored: cfg.ignoreTestFiles,
ignoreInitial: true,
})
this.specsWatcher.on('add', checkForSpecUpdates)
this.specsWatcher.on('unlink', checkForSpecUpdates)
}
if (componentTestingEnabled && !this.componentSpecsWatcher) {
debug('watching component test files: %s in %s', cfg.testFiles, cfg.componentFolder)
this.componentSpecsWatcher = chokidar.watch(cfg.testFiles, {
cwd: cfg.componentFolder,
ignored: cfg.ignoreTestFiles,
ignoreInitial: true,
})
this.componentSpecsWatcher.on('add', checkForSpecUpdates)
this.componentSpecsWatcher.on('unlink', checkForSpecUpdates)
}
}
const get = (): Bluebird<SpecsByType> => {
if (!this.openProject) {
return Bluebird.resolve({
component: [],
integration: [],
})
}
const cfg = this.openProject.getConfig()
createSpecsWatcher(cfg)
return this.getSpecs(cfg)
}
// immediately check the first time around
return checkForSpecUpdates()
}
stopSpecsWatcher () {
debug('stop spec watcher')
if (this.specsWatcher) {
this.specsWatcher.close()
this.specsWatcher = null
}
if (this.componentSpecsWatcher) {
this.componentSpecsWatcher.close()
this.componentSpecsWatcher = null
}
}
closeBrowser () {
return browsers.close()
}
closeOpenProjectAndBrowsers () {
return this.closeBrowser()
.then(() => {
return this.openProject?.close()
})
.then(() => {
this.resetOpenProject()
return null
})
}
close () {
debug('closing opened project')
this.stopSpecsWatcher()
return this.closeOpenProjectAndBrowsers()
}
async create (path: string, args: LaunchArgs, options: OpenProjectLaunchOptions) {
debug('open_project create %s', path)
_.defaults(options, {
onReloadBrowser: () => {
if (this.relaunchBrowser) {
return this.relaunchBrowser()
}
},
})
if (!_.isUndefined(args.configFile)) {
options.configFile = args.configFile
}
options = _.extend({}, args.config, options, { args })
// open the project and return
// the config for the project instance
debug('opening project %s', path)
debug('and options %o', options)
// store the currently open project
this.openProject = new ProjectBase({
testingType: args.testingType === 'component' ? 'component' : 'e2e',
projectRoot: path,
options: {
...options,
testingType: args.testingType,
},
})
await win32BitWarning(options.onWarning)
try {
await this.openProject.initializeConfig()
await this.openProject.open()
} catch (err: any) {
if (err.isCypressErr && err.portInUse) {
errors.throw(err.type, err.port)
} else {
// rethrow and handle elsewhere
throw (err)
}
}
return this
}
// for testing purposes
__reset () {
this.resetOpenProject()
}
}
export const openProject = new OpenProject() | the_stack |
import MathHelper from './MathHelper';
import Vector2 from './Vector2';
// import Line from './Line';
// import Vertex from './Vertex';
// import Ring from './Ring';
import { getChargeText } from './UtilityFunctions';
/**
* A class wrapping a canvas element.
*
* @property {HTMLElement} canvas The HTML element for the canvas associated with this CanvasWrapper instance.
* @property {CanvasRenderingContext2D} ctx The CanvasRenderingContext2D of the canvas associated with this CanvasWrapper instance.
* @property {Object} colors The colors object as defined in the SmilesDrawer options.
* @property {Object} opts The SmilesDrawer options.
* @property {Number} drawingWidth The width of the canvas.
* @property {Number} drawingHeight The height of the canvas.
* @property {Number} offsetX The horizontal offset required for centering the drawing.
* @property {Number} offsetY The vertical offset required for centering the drawing.
* @property {Number} fontLarge The large font size in pt.
* @property {Number} fontSmall The small font size in pt.
*/
class CanvasWrapper {
public canvas: any;
public ctx: any;
public themeManager: any;
public opts: any;
public drawingWidth: any;
public drawingHeight: any;
public offsetX: any;
public offsetY: any;
public fontLarge: any;
public fontSmall: any;
public hydrogenWidth: any;
public halfHydrogenWidth: any;
public halfBondThickness: any;
public devicePixelRatio: any;
public backingStoreRatio: any;
public ratio: any;
public colors: any;
/**
* The constructor for the class CanvasWrapper.
*
* @param {(String|HTMLElement)} target The canvas id or the canvas HTMLElement.
* @param {ThemeManager} themeManager Theme manager for setting proper colors.
* @param {Object} options The smiles drawer options object.
*/
constructor(target, themeManager, options) {
if (typeof target === 'string' || target instanceof String) {
this.canvas = document.getElementById(target.toString());
} else {
this.canvas = target;
}
this.ctx = this.canvas.getContext('2d');
this.themeManager = themeManager;
this.opts = options;
this.drawingWidth = 0.0;
this.drawingHeight = 0.0;
this.offsetX = 0.0;
this.offsetY = 0.0;
this.fontLarge = this.opts.fontSizeLarge + 'pt Helvetica, Arial, sans-serif';
this.fontSmall = this.opts.fontSizeSmall + 'pt Helvetica, Arial, sans-serif';
this.updateSize(this.opts.width, this.opts.height);
this.ctx.font = this.fontLarge;
this.hydrogenWidth = this.ctx.measureText('H').width;
this.halfHydrogenWidth = this.hydrogenWidth / 2.0;
this.halfBondThickness = this.opts.bondThickness / 2.0;
// TODO: Find out why clear was here.
// this.clear();
}
/**
* Update the width and height of the canvas
*
* @param {Number} width
* @param {Number} height
*/
updateSize(width, height) {
this.devicePixelRatio = window.devicePixelRatio || 1;
this.backingStoreRatio = this.ctx.webkitBackingStorePixelRatio || this.ctx.mozBackingStorePixelRatio ||
this.ctx.msBackingStorePixelRatio || this.ctx.oBackingStorePixelRatio ||
this.ctx.backingStorePixelRatio || 1;
this.ratio = this.devicePixelRatio / this.backingStoreRatio;
if (this.ratio !== 1) {
this.canvas.width = width * this.ratio;
this.canvas.height = height * this.ratio;
this.canvas.style.width = width + 'px';
this.canvas.style.height = height + 'px';
this.ctx.setTransform(this.ratio, 0, 0, this.ratio, 0, 0);
} else {
this.canvas.width = width * this.ratio;
this.canvas.height = height * this.ratio;
}
}
/**
* Sets a provided theme.
*
* @param {Object} theme A theme from the smiles drawer options.
*/
setTheme(theme) {
this.colors = theme;
}
/**
* Scale the canvas based on vertex positions.
*
* @param {Vertex[]} vertices An array of vertices containing the vertices associated with the current molecule.
*/
scale(vertices) {
// Figure out the final size of the image
let maxX = -Number.MAX_VALUE;
let maxY = -Number.MAX_VALUE;
let minX = Number.MAX_VALUE;
let minY = Number.MAX_VALUE;
for (var i = 0; i < vertices.length; i++) {
if (!vertices[i].value.isDrawn) {
continue;
}
let p = vertices[i].position;
if (maxX < p.x) maxX = p.x;
if (maxY < p.y) maxY = p.y;
if (minX > p.x) minX = p.x;
if (minY > p.y) minY = p.y;
}
// Add padding
var padding = this.opts.padding;
maxX += padding;
maxY += padding;
minX -= padding;
minY -= padding;
this.drawingWidth = maxX - minX;
this.drawingHeight = maxY - minY;
var scaleX = this.canvas.offsetWidth / this.drawingWidth;
var scaleY = this.canvas.offsetHeight / this.drawingHeight;
var scale = (scaleX < scaleY) ? scaleX : scaleY;
this.ctx.scale(scale, scale);
this.offsetX = -minX;
this.offsetY = -minY;
// Center
if (scaleX < scaleY) {
this.offsetY += this.canvas.offsetHeight / (2.0 * scale) - this.drawingHeight / 2.0;
} else {
this.offsetX += this.canvas.offsetWidth / (2.0 * scale) - this.drawingWidth / 2.0;
}
}
/**
* Resets the transform of the canvas.
*/
reset() {
this.ctx.setTransform(1, 0, 0, 1, 0, 0);
}
/**
* Returns the hex code of a color associated with a key from the current theme.
*
* @param {String} key The color key in the theme (e.g. C, N, BACKGROUND, ...).
* @returns {String} A color hex value.
*/
getColor(key) {
key = key.toUpperCase();
if (key in this.colors) {
return this.colors[key];
}
return this.colors['C'];
}
/**
* Draws a circle to a canvas context.
* @param {Number} x The x coordinate of the circles center.
* @param {Number} y The y coordinate of the circles center.
* @param {Number} radius The radius of the circle
* @param {String} color A hex encoded color.
* @param {Boolean} [fill=true] Whether to fill or stroke the circle.
* @param {Boolean} [debug=false] Draw in debug mode.
* @param {String} [debugText=''] A debug message.
*/
drawCircle(x, y, radius, color, fill = true, debug = false, debugText = '') {
let ctx = this.ctx;
let offsetX = this.offsetX;
let offsetY = this.offsetY;
ctx.save();
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(x + offsetX, y + offsetY, radius, 0, MathHelper.twoPI, true);
ctx.closePath();
if (debug) {
if (fill) {
ctx.fillStyle = '#f00';
ctx.fill();
} else {
ctx.strokeStyle = '#f00';
ctx.stroke();
}
this.drawDebugText(x, y, debugText);
} else {
if (fill) {
ctx.fillStyle = color;
ctx.fill();
} else {
ctx.strokeStyle = color;
ctx.stroke();
}
}
ctx.restore();
}
/**
* Draw a line to a canvas.
*
* @param {Line} line A line.
* @param {Boolean} [dashed=false] Whether or not the line is dashed.
* @param {Number} [alpha=1.0] The alpha value of the color.
*/
drawLine(line, dashed = false, alpha = 1.0) {
let ctx = this.ctx;
let offsetX = this.offsetX;
let offsetY = this.offsetY;
// Add a shadow behind the line
let shortLine = line.clone().shorten(4.0);
let l = shortLine.getLeftVector().clone();
let r = shortLine.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
// Draw the "shadow"
if (!dashed) {
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.moveTo(l.x, l.y);
ctx.lineTo(r.x, r.y);
ctx.lineCap = 'round';
ctx.lineWidth = this.opts.bondThickness + 1.2;
ctx.strokeStyle = this.themeManager.getColor('BACKGROUND');
ctx.stroke();
ctx.globalCompositeOperation = 'source-over';
ctx.restore();
}
l = line.getLeftVector().clone();
r = line.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
ctx.save();
ctx.beginPath();
ctx.moveTo(l.x, l.y);
ctx.lineTo(r.x, r.y);
ctx.lineCap = 'round';
ctx.lineWidth = this.opts.bondThickness;
let gradient = this.ctx.createLinearGradient(l.x, l.y, r.x, r.y);
gradient.addColorStop(0.4, this.themeManager.getColor(line.getLeftElement()) ||
this.themeManager.getColor('C'));
gradient.addColorStop(0.6, this.themeManager.getColor(line.getRightElement()) ||
this.themeManager.getColor('C'));
if (dashed) {
ctx.setLineDash([1, 1.5]);
ctx.lineWidth = this.opts.bondThickness / 1.5;
}
if (alpha < 1.0) {
ctx.globalAlpha = alpha;
}
ctx.strokeStyle = gradient;
ctx.stroke();
ctx.restore();
}
/**
* Draw a wedge on the canvas.
*
* @param {Line} line A line.
* @param {Number} width The wedge width.
*/
drawWedge(line, width = 1.0) {
if (isNaN(line.from.x) || isNaN(line.from.y) ||
isNaN(line.to.x) || isNaN(line.to.y)) {
return;
}
let ctx = this.ctx;
let offsetX = this.offsetX;
let offsetY = this.offsetY;
// Add a shadow behind the line
let shortLine = line.clone().shorten(5.0);
let l = shortLine.getLeftVector().clone();
let r = shortLine.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
l = line.getLeftVector().clone();
r = line.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
ctx.save();
let normals = Vector2.normals(l, r);
normals[0].normalize();
normals[1].normalize();
let isRightChiralCenter = line.getRightChiral();
let start = l;
let end = r;
if (isRightChiralCenter) {
start = r;
end = l;
}
let t = Vector2.add(start, Vector2.multiplyScalar(normals[0], this.halfBondThickness));
let u = Vector2.add(end, Vector2.multiplyScalar(normals[0], 1.5 + this.halfBondThickness));
let v = Vector2.add(end, Vector2.multiplyScalar(normals[1], 1.5 + this.halfBondThickness));
let w = Vector2.add(start, Vector2.multiplyScalar(normals[1], this.halfBondThickness));
ctx.beginPath();
ctx.moveTo(t.x, t.y);
ctx.lineTo(u.x, u.y);
ctx.lineTo(v.x, v.y);
ctx.lineTo(w.x, w.y);
let gradient = this.ctx.createRadialGradient(r.x, r.y, this.opts.bondLength, r.x, r.y, 0);
gradient.addColorStop(0.4, this.themeManager.getColor(line.getLeftElement()) ||
this.themeManager.getColor('C'));
gradient.addColorStop(0.6, this.themeManager.getColor(line.getRightElement()) ||
this.themeManager.getColor('C'));
ctx.fillStyle = gradient;
ctx.fill();
ctx.restore();
}
/**
* Draw a dashed wedge on the canvas.
*
* @param {Line} line A line.
*/
drawDashedWedge(line) {
if (isNaN(line.from.x) || isNaN(line.from.y) ||
isNaN(line.to.x) || isNaN(line.to.y)) {
return;
}
let ctx = this.ctx;
let offsetX = this.offsetX;
let offsetY = this.offsetY;
let l = line.getLeftVector().clone();
let r = line.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
ctx.save();
let normals = Vector2.normals(l, r);
normals[0].normalize();
normals[1].normalize();
let isRightChiralCenter = line.getRightChiral();
let start;
let end;
let sStart;
let sEnd;
let shortLine = line.clone();
if (isRightChiralCenter) {
start = r;
end = l;
shortLine.shortenRight(1.0);
sStart = shortLine.getRightVector().clone();
sEnd = shortLine.getLeftVector().clone();
} else {
start = l;
end = r;
shortLine.shortenLeft(1.0);
sStart = shortLine.getLeftVector().clone();
sEnd = shortLine.getRightVector().clone();
}
sStart.x += offsetX;
sStart.y += offsetY;
sEnd.x += offsetX;
sEnd.y += offsetY;
let dir = Vector2.subtract(end, start).normalize();
ctx.strokeStyle = this.themeManager.getColor('C');
ctx.lineCap = 'round';
ctx.lineWidth = this.opts.bondThickness;
ctx.beginPath();
let length = line.getLength();
let step = 1.25 / (length / (this.opts.bondThickness * 3.0));
let changed = false;
for (var t = 0.0; t < 1.0; t += step) {
let to = Vector2.multiplyScalar(dir, t * length);
let startDash = Vector2.add(start, to);
let width = 1.5 * t;
let dashOffset = Vector2.multiplyScalar(normals[0], width);
if (!changed && t > 0.5) {
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = this.themeManager.getColor(line.getRightElement()) || this.themeManager.getColor('C');
changed = true;
}
startDash.subtract(dashOffset);
ctx.moveTo(startDash.x, startDash.y);
startDash.add(Vector2.multiplyScalar(dashOffset, 2.0));
ctx.lineTo(startDash.x, startDash.y);
}
ctx.stroke();
ctx.restore();
}
/**
* Draws a debug text message at a given position
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {String} text The debug text.
*/
drawDebugText(x, y, text) {
let ctx = this.ctx;
ctx.save();
ctx.font = '5px Droid Sans, sans-serif';
ctx.textAlign = 'start';
ctx.textBaseline = 'top';
ctx.fillStyle = '#ff0000';
ctx.fillText(text, x + this.offsetX, y + this.offsetY);
ctx.restore();
}
/**
* Draw a ball to the canvas.
*
* @param {Number} x The x position of the text.
* @param {Number} y The y position of the text.
* @param {String} elementName The name of the element (single-letter).
*/
drawBall(x, y, elementName) {
let ctx = this.ctx;
ctx.save();
ctx.beginPath();
ctx.arc(x + this.offsetX, y + this.offsetY, this.opts.bondLength / 4.5, 0, MathHelper.twoPI, false);
ctx.fillStyle = this.themeManager.getColor(elementName);
ctx.fill();
ctx.restore();
}
/**
* Draw a point to the canvas.
*
* @param {Number} x The x position of the point.
* @param {Number} y The y position of the point.
* @param {String} elementName The name of the element (single-letter).
*/
drawPoint(x, y, elementName) {
let ctx = this.ctx;
let offsetX = this.offsetX;
let offsetY = this.offsetY;
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x + offsetX, y + offsetY, 1.5, 0, MathHelper.twoPI, true);
ctx.closePath();
ctx.fill();
ctx.globalCompositeOperation = 'source-over';
ctx.beginPath();
ctx.arc(x + this.offsetX, y + this.offsetY, 0.75, 0, MathHelper.twoPI, false);
ctx.fillStyle = this.themeManager.getColor(elementName);
ctx.fill();
ctx.restore();
}
/**
* Draw a text to the canvas.
*
* @param {Number} x The x position of the text.
* @param {Number} y The y position of the text.
* @param {String} elementName The name of the element (single-letter).
* @param {Number} hydrogens The number of hydrogen atoms.
* @param {String} direction The direction of the text in relation to the associated vertex.
* @param {Boolean} isTerminal A boolean indicating whether or not the vertex is terminal.
* @param {Number} charge The charge of the atom.
* @param {Number} isotope The isotope number.
* @param {Object} attachedPseudoElement A map with containing information for pseudo elements or concatinated elements. The key is comprised of the element symbol and the hydrogen count.
* @param {String} attachedPseudoElement.element The element symbol.
* @param {Number} attachedPseudoElement.count The number of occurences that match the key.
* @param {Number} attachedPseudoElement.hyrogenCount The number of hydrogens attached to each atom matching the key.
*/
drawText(x, y, elementName, hydrogens, direction, isTerminal, charge, isotope, attachedPseudoElement = {}) {
let ctx = this.ctx;
let offsetX = this.offsetX;
let offsetY = this.offsetY;
ctx.save();
ctx.textAlign = 'start';
ctx.textBaseline = 'alphabetic';
let pseudoElementHandled = false;
// Charge
let chargeText = ''
let chargeWidth = 0;
if (charge) {
chargeText = getChargeText(charge);
ctx.font = this.fontSmall;
chargeWidth = ctx.measureText(chargeText).width;
}
let isotopeText = '0';
let isotopeWidth = 0;
if (isotope > 0) {
isotopeText = isotope.toString();
ctx.font = this.fontSmall;
isotopeWidth = ctx.measureText(isotopeText).width;
}
// TODO: Better handle exceptions
// Exception for nitro (draw nitro as NO2 instead of N+O-O)
if (charge === 1 && elementName === 'N' && attachedPseudoElement.hasOwnProperty('0O') &&
attachedPseudoElement.hasOwnProperty('0O-1')) {
attachedPseudoElement = { '0O': { element: 'O', count: 2, hydrogenCount: 0, previousElement: 'C', charge: '' } }
charge = 0;
}
ctx.font = this.fontLarge;
ctx.fillStyle = this.themeManager.getColor('BACKGROUND');
let dim = ctx.measureText(elementName);
dim.totalWidth = dim.width + chargeWidth;
dim.height = parseInt(this.fontLarge, 10);
let r = (dim.width > this.opts.fontSizeLarge) ? dim.width : this.opts.fontSizeLarge;
r /= 1.5;
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x + offsetX, y + offsetY, r, 0, MathHelper.twoPI, true);
ctx.closePath();
ctx.fill();
ctx.globalCompositeOperation = 'source-over';
let cursorPos = -dim.width / 2.0;
let cursorPosLeft = -dim.width / 2.0;
ctx.fillStyle = this.themeManager.getColor(elementName);
ctx.fillText(elementName, x + offsetX + cursorPos, y + this.opts.halfFontSizeLarge + offsetY);
cursorPos += dim.width;
if (charge) {
ctx.font = this.fontSmall;
ctx.fillText(chargeText, x + offsetX + cursorPos, y - this.opts.fifthFontSizeSmall + offsetY);
cursorPos += chargeWidth;
}
if (isotope > 0) {
ctx.font = this.fontSmall;
ctx.fillText(isotopeText, x + offsetX + cursorPosLeft - isotopeWidth, y - this.opts.fifthFontSizeSmall + offsetY);
cursorPosLeft -= isotopeWidth;
}
ctx.font = this.fontLarge;
let hydrogenWidth = 0;
let hydrogenCountWidth = 0;
if (hydrogens === 1) {
let hx = x + offsetX;
let hy = y + offsetY + this.opts.halfFontSizeLarge;
hydrogenWidth = this.hydrogenWidth;
cursorPosLeft -= hydrogenWidth;
if (direction === 'left') {
hx += cursorPosLeft;
} else if (direction === 'right') {
hx += cursorPos;
} else if (direction === 'up' && isTerminal) {
hx += cursorPos;
} else if (direction === 'down' && isTerminal) {
hx += cursorPos;
} else if (direction === 'up' && !isTerminal) {
hy -= this.opts.fontSizeLarge + this.opts.quarterFontSizeLarge;
hx -= this.halfHydrogenWidth;
} else if (direction === 'down' && !isTerminal) {
hy += this.opts.fontSizeLarge + this.opts.quarterFontSizeLarge;
hx -= this.halfHydrogenWidth;
}
ctx.fillText('H', hx, hy);
cursorPos += hydrogenWidth;
} else if (hydrogens > 1) {
let hx = x + offsetX;
let hy = y + offsetY + this.opts.halfFontSizeLarge;
hydrogenWidth = this.hydrogenWidth;
ctx.font = this.fontSmall;
hydrogenCountWidth = ctx.measureText(hydrogens).width;
cursorPosLeft -= hydrogenWidth + hydrogenCountWidth;
if (direction === 'left') {
hx += cursorPosLeft;
} else if (direction === 'right') {
hx += cursorPos;
} else if (direction === 'up' && isTerminal) {
hx += cursorPos;
} else if (direction === 'down' && isTerminal) {
hx += cursorPos;
} else if (direction === 'up' && !isTerminal) {
hy -= this.opts.fontSizeLarge + this.opts.quarterFontSizeLarge;
hx -= this.halfHydrogenWidth;
} else if (direction === 'down' && !isTerminal) {
hy += this.opts.fontSizeLarge + this.opts.quarterFontSizeLarge;
hx -= this.halfHydrogenWidth;
}
ctx.font = this.fontLarge;
ctx.fillText('H', hx, hy)
ctx.font = this.fontSmall;
ctx.fillText(hydrogens, hx + this.halfHydrogenWidth + hydrogenCountWidth, hy + this.opts.fifthFontSizeSmall);
cursorPos += hydrogenWidth + this.halfHydrogenWidth + hydrogenCountWidth;
}
if (pseudoElementHandled) {
ctx.restore();
return;
}
for (let key in attachedPseudoElement) {
if (!attachedPseudoElement.hasOwnProperty(key)) {
continue;
}
let openParenthesisWidth = 0;
let closeParenthesisWidth = 0;
let element = attachedPseudoElement[key].element;
let elementCount = attachedPseudoElement[key].count;
let hydrogenCount = attachedPseudoElement[key].hydrogenCount;
let elementCharge = attachedPseudoElement[key].charge;
ctx.font = this.fontLarge;
if (elementCount > 1 && hydrogenCount > 0) {
openParenthesisWidth = ctx.measureText('(').width;
closeParenthesisWidth = ctx.measureText(')').width;
}
let elementWidth = ctx.measureText(element).width;
let elementCountWidth = 0;
let elementChargeText = '';
let elementChargeWidth = 0;
hydrogenWidth = 0;
if (hydrogenCount > 0) {
hydrogenWidth = this.hydrogenWidth;
}
ctx.font = this.fontSmall;
if (elementCount > 1) {
elementCountWidth = ctx.measureText(elementCount).width;
}
if (elementCharge !== 0) {
elementChargeText = getChargeText(elementCharge);
elementChargeWidth = ctx.measureText(elementChargeText).width;
}
hydrogenCountWidth = 0;
if (hydrogenCount > 1) {
hydrogenCountWidth = ctx.measureText(hydrogenCount).width;
}
ctx.font = this.fontLarge;
let hx = x + offsetX;
let hy = y + offsetY + this.opts.halfFontSizeLarge;
ctx.fillStyle = this.themeManager.getColor(element);
if (elementCount > 0) {
cursorPosLeft -= elementCountWidth;
}
if (elementCount > 1 && hydrogenCount > 0) {
if (direction === 'left') {
cursorPosLeft -= closeParenthesisWidth;
ctx.fillText(')', hx + cursorPosLeft, hy);
} else {
ctx.fillText('(', hx + cursorPos, hy);
cursorPos += openParenthesisWidth;
}
}
if (direction === 'left') {
cursorPosLeft -= elementWidth;
ctx.fillText(element, hx + cursorPosLeft, hy)
} else {
ctx.fillText(element, hx + cursorPos, hy)
cursorPos += elementWidth;
}
if (hydrogenCount > 0) {
if (direction === 'left') {
cursorPosLeft -= hydrogenWidth + hydrogenCountWidth;
ctx.fillText('H', hx + cursorPosLeft, hy)
if (hydrogenCount > 1) {
ctx.font = this.fontSmall;
ctx.fillText(hydrogenCount, hx + cursorPosLeft + hydrogenWidth, hy + this.opts.fifthFontSizeSmall);
}
} else {
ctx.fillText('H', hx + cursorPos, hy)
cursorPos += hydrogenWidth;
if (hydrogenCount > 1) {
ctx.font = this.fontSmall;
ctx.fillText(hydrogenCount, hx + cursorPos, hy + this.opts.fifthFontSizeSmall);
cursorPos += hydrogenCountWidth;
}
}
}
ctx.font = this.fontLarge;
if (elementCount > 1 && hydrogenCount > 0) {
if (direction === 'left') {
cursorPosLeft -= openParenthesisWidth;
ctx.fillText('(', hx + cursorPosLeft, hy);
} else {
ctx.fillText(')', hx + cursorPos, hy);
cursorPos += closeParenthesisWidth;
}
}
ctx.font = this.fontSmall;
if (elementCount > 1) {
if (direction === 'left') {
ctx.fillText(elementCount, hx + cursorPosLeft +
openParenthesisWidth + closeParenthesisWidth + hydrogenWidth +
hydrogenCountWidth + elementWidth, hy + this.opts.fifthFontSizeSmall);
} else {
ctx.fillText(elementCount, hx + cursorPos, hy + this.opts.fifthFontSizeSmall);
cursorPos += elementCountWidth;
}
}
if (elementCharge !== 0) {
if (direction === 'left') {
ctx.fillText(elementChargeText, hx + cursorPosLeft +
openParenthesisWidth + closeParenthesisWidth + hydrogenWidth +
hydrogenCountWidth + elementWidth, y - this.opts.fifthFontSizeSmall + offsetY);
} else {
ctx.fillText(elementChargeText, hx + cursorPos, y - this.opts.fifthFontSizeSmall + offsetY);
cursorPos += elementChargeWidth;
}
}
}
ctx.restore();
}
/**
* Translate the integer indicating the charge to the appropriate text.
* @param {Number} charge The integer indicating the charge.
* @returns {String} A string representing a charge.
*/
getChargeText(charge) {
if (charge === 1) {
return '+'
} else if (charge === 2) {
return '2+';
} else if (charge === -1) {
return '-';
} else if (charge === -2) {
return '2-';
} else {
return '';
}
}
/**
* Draws a dubug dot at a given coordinate and adds text.
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordindate.
* @param {String} [debugText=''] A string.
* @param {String} [color='#f00'] A color in hex form.
*/
drawDebugPoint(x, y, debugText = '', color = '#f00') {
this.drawCircle(x, y, 2, color, true, true, debugText);
}
/**
* Draws a ring inside a provided ring, indicating aromaticity.
*
* @param {Ring} ring A ring.
*/
drawAromaticityRing(ring) {
let ctx = this.ctx;
let radius = MathHelper.apothemFromSideLength(this.opts.bondLength, ring.getSize());
ctx.save();
ctx.strokeStyle = this.themeManager.getColor('C');
ctx.lineWidth = this.opts.bondThickness;
ctx.beginPath();
ctx.arc(ring.center.x + this.offsetX, ring.center.y + this.offsetY,
radius - this.opts.bondSpacing, 0, Math.PI * 2, true);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
/**
* Clear the canvas.
*
*/
clear() {
this.ctx.clearRect(0, 0, this.canvas.offsetWidth, this.canvas.offsetHeight);
}
}
export default CanvasWrapper; | the_stack |
import assert from "assert";
import Path from "path";
import _ from "lodash";
import redbird from "@jchip/redbird";
import ck from "chalker";
import { makeOptionalRequire } from "optional-require";
import { devProxy } from "../../config/dev-proxy";
import { cdnMock } from "./cdn-mock";
import { isValidPort, formUrl } from "../utils";
import QS from "querystring";
const { settings, searchSSLCerts, controlPaths } = devProxy;
const optionalRequire = makeOptionalRequire(require);
let APP_RULES = [];
const getNotFoundPage = (data) => {
const { protocol, actualHost, expectedHost, port } = data;
const adminUrl = formUrl({ protocol, host: expectedHost, port, path: controlPaths.status });
/* eslint-disable max-len */
const invalidHostMessage = `<p>
<span style="color: red;">ERROR:</span> You used a hostname that the development proxy doesn't recognize.<br />
The proxy is using the hostname <span style="color: green;">${expectedHost}</span>.<br />
The hostname in your URL is <span style="color: red;">${actualHost}</span>.<br />
To change the hostname that the proxy uses, set the HOST env variable.<br />
For example:<br /><br />
In unix bash: <code style="color: white;background-color: black;padding: 5px;">
HOST=${actualHost} clap dev
</code><br /><br />
In Windows PowerShell: <code style="color: white;background-color: #012456;padding: 5px;">
$Env:HOST="${actualHost}"; clap dev
</code>
</p>`;
return `<html>
<body>
<div style="text-align:center;">
<div>
<svg version="1.0" viewBox="100 0 202.3 65.1" width="250px" height="250px">
<g transform="scale(5,5) translate(-94, -10)">
<path id="Fill-1" class="st0" d="M134.6,8.9c-0.2,0-0.3-0.1-0.4-0.2l-1.1-1.9l-0.9,1.8c-0.1,0.2-0.4,0.3-0.6,0.2 c-0.1-0.1-0.2-0.2-0.2-0.3l-0.8-4.6l-0.9,2.7c-0.1,0.2-0.2,0.3-0.4,0.3h-2.2c-0.2,0-0.4-0.2-0.4-0.4c0-0.2,0.2-0.4,0.4-0.4 h1.9l1.3-4.1c0.1-0.2,0.3-0.3,0.5-0.3c0.1,0,0.3,0.2,0.3,0.3l0.9,5.1l0.7-1.3c0.1-0.2,0.4-0.3,0.6-0.2c0.1,0,0.1,0.1,0.2,0.2 l1,1.6l1.6-7c0.1-0.2,0.3-0.4,0.5-0.3c0.2,0,0.3,0.2,0.3,0.3l1,5.7l3.4,0.2c0.2,0,0.4,0.2,0.4,0.4c0,0.2-0.2,0.4-0.4,0.4l0,0 l-3.7-0.2c-0.2,0-0.4-0.2-0.4-0.3l-0.8-4L135,8.6C135,8.7,134.8,8.9,134.6,8.9L134.6,8.9"></path>
<path d="M134.3,31.9 c-4.9,0 -8.8,-3.9 -8.8,-8.8 s3.9,-8.8 8.8,-8.8 s8.8,3.9 8.8,8.8 S139.2,31.9 134.3,31.9 L134.3,31.9 M145.1,18.5 h-0.3 l-0.1,-0.3 c-0.6,-1.3 -1.5,-2.4 -2.5,-3.4 l-0.4,-0.3 l3.4,-5.8 h0.3 c1,-0.2 1.6,-1.1 1.5,-2 s-1.1,-1.6 -2,-1.5 s-1.6,1.1 -1.5,2 c0,0.2 0.1,0.4 0.2,0.6 l0.2,0.3 l-3.3,5.4 l-0.5,-0.3 c-1.7,-0.9 -3.6,-1.5 -5.6,-1.5 l0,0 c-1.9,0 -3.9,0.5 -5.6,1.5 l-0.5,0.3 L124.9,8 l0.1,-0.3 c0.1,-0.2 0.2,-0.5 0.2,-0.8 c0,-1 -0.8,-1.8 -1.8,-1.8 s-1.8,0.8 -1.8,1.8 c0,0.9 0.7,1.6 1.5,1.7 h0.3 l3.4,5.8 l-0.4,0.3 c-1,0.9 -1.9,2.1 -2.5,3.3 l-0.2,0.3 h-0.3 c-2.4,0.2 -4.2,2.4 -4,4.8 c0.2,2 1.7,3.7 3.8,4 h0.3 l0.1,0.3 c1.8,4.2 5.9,7 10.5,7 l0,0 c4.6,0 8.7,-2.8 10.5,-7 l0.1,-0.3 h0.3 c2.4,-0.4 4.1,-2.6 3.7,-5 C148.7,20.2 147.1,18.6 145.1,18.5 " id="Fill-4" class="st0"></path>
<path id="Fill-7" class="st0" d="M138.9,21.1c0,0.7-0.6,1.3-1.3,1.3c-0.7,0-1.3-0.6-1.3-1.3c0-0.7,0.6-1.3,1.3-1.3 S138.9,20.4,138.9,21.1C138.9,21.1,138.9,21.1,138.9,21.1"></path>
<path id="Fill-9" class="st0" d="M132.2,21.1c0,0.7-0.6,1.3-1.3,1.3c-0.7,0-1.3-0.6-1.3-1.3s0.6-1.3,1.3-1.3c0,0,0,0,0,0 C131.7,19.8,132.3,20.4,132.2,21.1C132.3,21.1,132.3,21.1,132.2,21.1"></path>
</g>
</svg>
<p>
Electrode development reverse proxy is unable to forward your URL.<br />
Check <a href="${adminUrl}">${adminUrl}</a> to see a list of forward rules.
</p>
${actualHost !== expectedHost ? invalidHostMessage : ""}
</div>
</div>
</body>
</html>`;
/* eslint-enable max-len */
};
// eslint-disable-next-line max-params
const getLineForTree = (_rotocol, host) => (tree, [envVarName, port], idx, arr) => {
const boxChar = idx === arr.length - 1 ? "└" : "├";
const portText = envVarName.replace(/port/gi, "");
return ck`${tree} ${boxChar}─<green>${formUrl({
protocol: "http",
host,
port,
})}</> (${portText})\n`;
};
const buildProxyTree = (options, ports) => {
const { host, port, protocol } = options;
const lineGen = getLineForTree(protocol, host);
const portTree = Object.entries(_.pick(options, ports)).reduce(lineGen, "");
return ck`<orange>${formUrl({ protocol, host, port })}</> (proxy) \n${portTree}`;
};
const onExitRequest = (_req, res) => {
res.statusCode = 200;
res.write(`<!DOCTYPE html>
<html><head></head><body>
<h1>Bye</h1>
</body>
</html>`);
res.end();
process.nextTick(() => process.exit(0));
return false;
};
const onStatusRequest = (_req, res) => {
res.statusCode = 200;
res.write(`<!DOCTYPE html>
<html><head></head><body>
<h1>Electrode Development Reverse Proxy</h1>
<h2>Rules</h2>
<ul>
${APP_RULES.map(
(x) => `<li><pre><a href="${x[0]}">${x[0]}</a> ===> <a href="${x[1]}">${x[1]}</a></pre></li>`
).join("")}
</ul>
</body>
</html>`);
res.end();
return false;
};
let regAppPort = 0;
let regWebpackDevPort = 0;
const registerElectrodeDevRules = ({
proxy,
ssl,
protocol,
host,
port,
appPort,
webpackDevPort,
restart,
enableCdnMock,
noDev,
}) => {
const { dev: devPath, admin: adminPath, hmr: hmrPath, appLog, reporter } = controlPaths;
const logEventsPath = `${devPath}/log-events`;
const logStreamsPath = `${devPath}/stream-logs`;
const appForwards: any[] = [[{}, { port: appPort }]];
regAppPort = appPort;
regWebpackDevPort = webpackDevPort;
if (!noDev) {
appForwards.push(
[{ path: `/js` }, { path: `/js`, port: webpackDevPort }],
[{ path: hmrPath }, { path: hmrPath, port: webpackDevPort }],
[{ path: appLog }, { path: appLog, port: settings.devAdminPort }],
[{ path: logEventsPath }, { path: logEventsPath, port: settings.devAdminPort }],
[{ path: logStreamsPath }, { path: logStreamsPath, port: settings.devAdminPort }],
[{ path: devPath }, { path: devPath, port: webpackDevPort }],
[{ path: reporter }, { path: reporter, port: webpackDevPort }],
[{ path: `${adminPath}/test-google` }, { protocol: "https", host: "www.google.com" }]
);
}
const appRules = appForwards
.map(([src, target, opts]) => {
return [
formUrl({ host, protocol, port, ...src }),
formUrl({ host, protocol: "http", ...target }),
opts,
];
})
.concat(
// repeat all rules for 127.0.0.1
appForwards.map(([src, target, opts]) => {
return [
formUrl({ protocol, port, ...src, host: src.host || "127.0.0.1" }),
formUrl({
...target,
protocol: target.protocol || "http",
host: target.host || "127.0.0.1",
}),
opts,
];
})
)
.filter((x) => x);
appRules.forEach((x) => proxy.register(...x));
APP_RULES = APP_RULES.concat(appRules);
proxy.register({
ssl,
src: formUrl({ protocol, host, path: controlPaths.exit }),
target: `http://localhost:29999/skip`,
onRequest: onExitRequest,
});
proxy.register({
ssl,
src: formUrl({ protocol, host, path: controlPaths.status }),
target: `http://localhost:29999/skip`,
onRequest: onStatusRequest,
});
proxy.register({
ssl,
src: formUrl({ protocol, host, path: controlPaths.restart }),
target: `http://localhost:29999/skip`,
onRequest: (req, res) => {
const restartOpts = { ...QS.parse(req._url.split("?")[1]) };
const newPorts: any = {};
if (restartOpts.updatePorts) {
if (restartOpts.hasOwnProperty("appPort")) {
const tmpPort = restartOpts.appPort as string;
if (tmpPort !== `${regAppPort}`) {
newPorts.appPort = tmpPort;
}
}
if (restartOpts.hasOwnProperty("webpackDevPort")) {
const tmpPort = restartOpts.webpackDevPort as string;
if (tmpPort !== `${regWebpackDevPort}`) {
newPorts.webpackDevPort = tmpPort;
}
}
res.statusCode = 200;
if (_.isEmpty(newPorts)) {
res.write(`update-ports - proxy ports same: app ${regAppPort}, wds ${regWebpackDevPort}`);
} else {
res.write(`update-ports - proxy proxy ports updated`);
process.nextTick(() => restart({ ...restartOpts, newPorts }));
}
res.end();
} else {
res.statusCode = 200;
res.write(`proxy restarted`);
res.end();
process.nextTick(() => restart({ ...restartOpts, newPorts }));
}
return false;
},
});
// mock-cdn
if (enableCdnMock) {
const mockCdnSrc = formUrl({ protocol, host, port, path: `/__mock-cdn` });
cdnMock.generateMockAssets(mockCdnSrc);
proxy.register({
ssl,
src: mockCdnSrc,
target: `http://localhost:29999/__mock-cdn`,
onRequest(req, res) {
cdnMock.respondAsset(req, res);
return false;
},
});
}
};
const startProxy = (inOptions = {}) => {
APP_RULES = [];
const options = Object.assign(
{
xfwd: false,
pino: {
level: "warn",
},
resolvers: [],
},
settings,
inOptions
);
const proxyOptions = _.pick(options, ["port", "xfwd", "pino", "resolvers"]);
const { host, port, protocol } = options;
const ssl = Boolean(options.httpsPort);
const enableCdnMock = process.argv.includes("--mock-cdn");
let listenReportTimer;
const proxyUrls = {} as any;
proxyOptions.reportListening = (proto, _port, actualPort) => {
clearTimeout(listenReportTimer);
if (!regAppPort) {
return;
}
proxyUrls[proto] = formUrl({ protocol: proto, host, port: actualPort });
console.log(`Electrode dev proxy listening on ${proto} port`, actualPort);
listenReportTimer = setTimeout(() => {
const mockCdnMsg = enableCdnMock
? `\nMock CDN is enabled (mapping saved to config/assets.json)\n`
: "\n";
console.log(
ck`${mockCdnMsg}${buildProxyTree(options, ["appPort", "webpackDevPort"])}
View status at <green>${proxyUrls.https || proxyUrls.http}${controlPaths.status}</>`
);
const urlsShow = Object.keys(proxyUrls)
.map((x) => {
return ck`<green>${proxyUrls[x]}</>`;
})
.join(" or ");
console.log(ck`You can access your app at ${urlsShow}`);
}, 100).unref();
};
const enableSsl = ssl && isValidPort(options.httpsPort);
if (enableSsl) {
const proxyCerts: any = searchSSLCerts();
assert(proxyCerts.key && proxyCerts.cert, "Dev Proxy can't find SSL key and certs");
const httpPort = isValidPort(options.httpPort) ? options.httpPort : -1;
Object.assign(proxyOptions, {
// We still setup a regular http rules even if HTTPS is enabled
port: httpPort,
host,
secure: true,
ssl: {
port: options.httpsPort,
...proxyCerts,
},
});
}
let proxy = redbird(proxyOptions);
const userFiles = ["archetype/config", "src", "test", "config"].map(
(x) => `${x}/dev-proxy-rules`
);
const userDevProxyFile = userFiles.find((f) => optionalRequire.resolve(Path.resolve(f)));
const userDevProxy = userDevProxyFile && require(Path.resolve(userDevProxyFile));
const restart = async (restartOpts = {}) => {
// ensure user's proxy rules are refreshed
if (userDevProxyFile) {
delete require.cache[userDevProxyFile];
}
if (proxy) {
const old = proxy;
proxy = undefined;
await old.close(true);
process.nextTick(() => startProxy({ ...inOptions, ...restartOpts }));
}
};
proxy.notFound((req, res) => {
res.statusCode = 404;
res.setHeader("Content-Type", "text/html");
res.write(
getNotFoundPage({
protocol,
actualHost: req.headers.host.split(":")[0],
expectedHost: host,
port,
})
);
res.end();
});
const noDev = process.argv.includes("--no-dev");
// register with primary protocol/host/port
registerElectrodeDevRules({ ...options, ssl: enableSsl, proxy, restart, enableCdnMock, noDev });
// if primary protocol is https, then register regular http rules at httpPort
if (enableSsl && isValidPort(options.httpPort)) {
registerElectrodeDevRules({
proxy,
protocol: "http",
host,
port: options.httpPort,
appPort: options.appPort,
webpackDevPort: options.webpackDevPort,
restart,
} as any);
}
if (process.send) {
process.send({ name: "proxy-started", appPort: regAppPort });
}
if (userDevProxy && userDevProxy.setupRules) {
console.log("Calling proxy setupRules from your archetype/config/dev-proxy");
userDevProxy.setupRules(proxy, options);
}
};
export = startProxy;
startProxy(); | the_stack |
import {
Injectable,
BadRequestException,
HttpException
} from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { AxiosError, AxiosResponse } from 'axios';
import { CommandBus } from '@nestjs/cqrs';
import { DeepPartial } from 'typeorm';
import { map, catchError, switchMap } from 'rxjs/operators';
import * as moment from 'moment';
import { environment as env } from '@gauzy/config';
import { isEmpty, isNotEmpty, isObject } from '@gauzy/common';
import {
ICreateIntegrationDto,
IIntegrationTenant,
IntegrationEnum,
IntegrationEntity,
IIntegrationMap,
IIntegrationSetting,
RolesEnum,
TimeLogType,
ContactType,
CurrenciesEnum,
ProjectBillingEnum,
TimeLogSourceEnum,
IHubstaffOrganization,
IHubstaffProject,
IIntegrationEntitySetting,
IDateRangeActivityFilter,
ComponentLayoutStyleEnum,
ActivityType,
IDateRange,
OrganizationProjectBudgetTypeEnum,
OrganizationContactBudgetTypeEnum,
IHubstaffProjectsResponse,
IHubstaffOrganizationsResponse,
IHubstaffProjectResponse,
IHubstaffTimeSlotActivity,
IActivity,
IHubstaffLogFromTimeSlots
} from '@gauzy/contracts';
import {
DEFAULT_ENTITY_SETTINGS,
HUBSTAFF_AUTHORIZATION_URL,
PROJECT_TIED_ENTITIES
} from '@gauzy/integration-hubstaff';
import { firstValueFrom, lastValueFrom } from 'rxjs';
import { IntegrationTenantService } from '../integration-tenant/integration-tenant.service';
import { IntegrationSettingService } from '../integration-setting/integration-setting.service';
import { IntegrationMapService } from '../integration-map/integration-map.service';
import { OrganizationContactCreateCommand } from '../organization-contact/commands';
import { EmployeeCreateCommand, EmployeeGetCommand } from '../employee/commands';
import { RoleService } from '../role/role.service';
import { OrganizationService } from '../organization/organization.service';
import { UserService } from '../user/user.service';
import {
IntegrationMapSyncActivityCommand,
IntegrationMapSyncEntityCommand,
IntegrationMapSyncOrganizationCommand,
IntegrationMapSyncProjectCommand,
IntegrationMapSyncScreenshotCommand,
IntegrationMapSyncTaskCommand,
IntegrationMapSyncTimeLogCommand,
IntegrationMapSyncTimeSlotCommand
} from './../integration-map/commands';
import { RequestContext } from './../core/context';
import { mergeOverlappingDateRanges } from './../core/utils';
@Injectable()
export class HubstaffService {
constructor(
private readonly _httpService: HttpService,
private readonly _integrationTenantService: IntegrationTenantService,
private readonly _integrationSettingService: IntegrationSettingService,
private readonly _integrationMapService: IntegrationMapService,
private readonly _roleService: RoleService,
private readonly _organizationService: OrganizationService,
private readonly _userService: UserService,
private readonly _commandBus: CommandBus
) {}
async fetchIntegration<T = any>(url: string, token: string): Promise<any> {
const headers = {
Authorization: `Bearer ${token}`
};
return firstValueFrom(
this._httpService.get(url, { headers }).pipe(
catchError((error: AxiosError<any>) => {
const response: AxiosResponse<any> = error.response;
const status = response.status;
const statusText = response.statusText;
const data = response.data;
/**
* Handle hubstaff http exception
*/
throw new HttpException({
statusCode: status,
error: statusText,
message: data.error
}, response.status);
}),
map(
(response: AxiosResponse<T>) => response.data
)
)
);
}
async refreshToken(integrationId) {
const {
items: settings
} = await this._integrationSettingService.findAll({
where: {
integration: { id: integrationId }
}
});
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
const urlParams = new URLSearchParams();
const { client_id, client_secret, refresh_token } = settings.reduce(
(prev, current) => {
return {
...prev,
client_id:
current.settingsName === 'client_id'
? current.settingsValue
: prev.client_id,
client_secret:
current.settingsName === 'client_secret'
? current.settingsValue
: prev.client_secret,
refresh_token:
current.settingsName === 'refresh_token'
? current.settingsValue
: prev.refresh_token
};
},
{
client_id: '',
client_secret: '',
refresh_token: ''
}
);
urlParams.append('grant_type', 'refresh_token');
urlParams.append('refresh_token', refresh_token);
urlParams.append('client_id', client_id);
urlParams.append('client_secret', client_secret);
try {
const tokens$ = this._httpService.post(`${HUBSTAFF_AUTHORIZATION_URL}/access_tokens`, urlParams, {
headers
})
.pipe(
map(
(response: AxiosResponse<any>) => response.data
)
);
const tokens = await lastValueFrom(tokens$);
const settingsDto = settings.map((setting) => {
if (setting.settingsName === 'access_token') {
setting.settingsValue = tokens.access_token;
}
if (setting.settingsName === 'refresh_token') {
setting.settingsValue = tokens.refresh_token;
}
return setting;
}) as DeepPartial<IIntegrationSetting>;
await this._integrationSettingService.create(settingsDto);
return tokens;
} catch (error) {
throw new BadRequestException(error);
}
}
async getHubstaffToken(integrationId): Promise<IIntegrationSetting> {
const {
record: integrationSetting
} = await this._integrationSettingService.findOneOrFailByOptions({
where: {
integration: { id: integrationId },
settingsName: 'access_token'
}
});
return integrationSetting;
}
async addIntegration(
body: ICreateIntegrationDto
): Promise<IIntegrationTenant> {
const tenantId = RequestContext.currentTenantId();
const { client_id, client_secret, code, redirect_uri, organizationId } = body;
const urlParams = new URLSearchParams();
urlParams.append('client_id', client_id);
urlParams.append('code', code);
urlParams.append('grant_type', 'authorization_code');
urlParams.append('redirect_uri', redirect_uri);
urlParams.append('client_secret', client_secret);
const tiedEntities = [];
for await (const entity of PROJECT_TIED_ENTITIES) {
tiedEntities.push(
Object.assign(entity, { organizationId, tenantId })
);
}
const entitySettings = DEFAULT_ENTITY_SETTINGS.map(
(settingEntity) => {
return Object.assign(settingEntity, {
organizationId,
tenantId
});
}
).map((settingEntity) =>
settingEntity.entity === IntegrationEntity.PROJECT
? {
...settingEntity,
tiedEntities: tiedEntities
}
: settingEntity
) as IIntegrationEntitySetting[];
const tokens$ = this._httpService
.post(`${HUBSTAFF_AUTHORIZATION_URL}/access_tokens`, urlParams, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.pipe(
switchMap(({ data }) =>
this._integrationTenantService.addIntegration({
organizationId,
tenantId,
name: IntegrationEnum.HUBSTAFF,
entitySettings: entitySettings,
settings: [
{
settingsName: 'client_id',
settingsValue: client_id
},
{
settingsName: 'client_secret',
settingsValue: client_secret
},
{
settingsName: 'access_token',
settingsValue: data.access_token
},
{
settingsName: 'refresh_token',
settingsValue: data.refresh_token
}
].map((setting) => {
return { organizationId, ...setting };
})
})
),
catchError((err) => {
throw new BadRequestException(err);
})
);
return await lastValueFrom(tokens$);
}
/*
* Fetch all organizations
*/
async fetchOrganizations({
token
}): Promise<IHubstaffOrganization[]> {
const { organizations } = await this.fetchIntegration<IHubstaffOrganizationsResponse[]>(
'organizations',
token
);
return organizations;
}
/*
* Fetch all organization projects
*/
async fetchOrganizationProjects({
organizationId,
token
}): Promise<IHubstaffProject[]> {
const { projects } = await this.fetchIntegration<IHubstaffProjectsResponse[]>(
`organizations/${organizationId}/projects?status=all`,
token
);
return projects;
}
async syncProjects({
integrationId,
organizationId,
projects,
token
}): Promise<IIntegrationMap[]> {
try {
const tenantId = RequestContext.currentTenantId();
return await Promise.all(
await projects.map(
async ({ name, sourceId, billable, description }) => {
const { project } = await this.fetchIntegration<IHubstaffProjectResponse>(
`projects/${sourceId}`,
token
);
/**
* Set Project Budget Here
*/
let budget = {};
if (project.budget) {
budget['budgetType'] = project.budget.type || OrganizationProjectBudgetTypeEnum.COST;
budget['startDate'] = project.budget.start_date || null;
budget['budget'] = project.budget[budget['budgetType']];
}
const payload = {
name,
organizationId,
public: true,
billing: ProjectBillingEnum.RATE,
currency: env.defaultCurrency as CurrenciesEnum,
billable,
description,
tenantId,
...budget
};
return await this._commandBus.execute(
new IntegrationMapSyncProjectCommand(
Object.assign({
organizationProjectInput: payload,
sourceId,
integrationId,
organizationId
})
)
);
}
)
)
} catch (error) {
throw new BadRequestException(error, `Can\'t sync ${IntegrationEntity.PROJECT}`);
}
}
async syncOrganizations({
integrationId,
organizationId,
organizations
}): Promise<IIntegrationMap[]> {
try {
return await Promise.all(
await organizations.map(
async (organization) => {
const { sourceId } = organization;
return await this._commandBus.execute(
new IntegrationMapSyncOrganizationCommand(
Object.assign({
organizationInput: organization,
sourceId,
integrationId,
organizationId
})
)
);
}
)
);
} catch (error) {
throw new BadRequestException(error, `Can\'t sync ${IntegrationEntity.ORGANIZATION}`);
}
}
async syncClients({
integrationId,
organizationId,
clients
}): Promise<IIntegrationMap[]> {
try {
return await Promise.all(
await clients.map(
async ({ id, name, emails, phone, budget = {} as any }) => {
const { record } = await this._integrationMapService.findOneOrFailByOptions({
where: {
sourceId: id,
entity: IntegrationEntity.CLIENT,
organizationId
}
});
if (record) {
return record;
}
/**
* Set Client Budget Here
*/
let clientBudget = {};
if (isNotEmpty(budget)) {
clientBudget['budgetType'] = budget.type || OrganizationContactBudgetTypeEnum.COST;
clientBudget['budget'] = budget[clientBudget['budgetType']];
}
const gauzyClient = await this._commandBus.execute(
new OrganizationContactCreateCommand({
name,
organizationId,
primaryEmail: emails[0],
primaryPhone: phone,
contactType: ContactType.CLIENT,
...clientBudget
})
);
return await this._commandBus.execute(
new IntegrationMapSyncEntityCommand({
gauzyId: gauzyClient.id,
integrationId,
sourceId: id,
entity: IntegrationEntity.CLIENT,
organizationId
})
);
}
)
);
} catch (error) {
throw new BadRequestException(error, `Can\'t sync ${IntegrationEntity.CLIENT}`);
}
}
/*
* Sync screenshot using timeslot
*/
async syncScreenshots({
integrationId,
screenshots,
token,
organizationId
}): Promise<IIntegrationMap[]> {
try {
let integratedScreenshots: IIntegrationMap[] = [];
for await (const screenshot of screenshots) {
const { id, user_id } = screenshot;
const employee = await this._getEmployeeByHubstaffUserId(
user_id,
token,
integrationId,
organizationId
);
integratedScreenshots.push(
await this._commandBus.execute(
new IntegrationMapSyncScreenshotCommand(
Object.assign({
screenshot: {
employeeId: employee ? employee.gauzyId : null,
...screenshot
},
sourceId: id,
integrationId,
organizationId
})
)
)
);
}
return integratedScreenshots;
} catch (error) {
throw new BadRequestException(error, `Can\'t sync ${IntegrationEntity.SCREENSHOT}`);
}
}
async syncTasks({
integrationId,
projectId,
tasks,
organizationId
}): Promise<IIntegrationMap[]> {
try {
const tenantId = RequestContext.currentTenantId();
const creatorId = RequestContext.currentUserId();
return await Promise.all(
await tasks.map(
async ({ summary: title, id, status, due_at }) => {
if (!due_at) {
due_at = new Date(moment().add(2, 'week').format('YYYY-MM-DD HH:mm:ss'));
}
const task = {
title,
projectId,
description: 'Hubstaff Task',
status: status.charAt(0).toUpperCase() + status.slice(1),
creatorId,
dueDate: due_at,
organizationId,
tenantId
};
return await this._commandBus.execute(
new IntegrationMapSyncTaskCommand(
Object.assign({
taskInput: task,
sourceId: id,
integrationId,
organizationId
})
)
);
}
)
);
} catch (error) {
throw new BadRequestException(error, `Can\'t sync ${IntegrationEntity.TASK}`);
}
}
private async _getEmployeeByHubstaffUserId(
user_id: number,
token: string,
integrationId: string,
organizationId: string
) {
try {
const tenantId = RequestContext.currentTenantId();
return await this._integrationMapService.findOneByOptions({
where: {
sourceId: user_id,
entity: IntegrationEntity.EMPLOYEE,
organizationId,
tenantId
}
});
} catch (error) {
return await this._handleEmployee({
user_id,
token,
integrationId,
organizationId
});
}
}
/**
* Map worked timeslot activity
*
* @param timeSlots
* @returns
*/
async syncTimeSlots(
integrationId: string,
organizationId: string,
employee: IIntegrationMap,
timeSlots: IHubstaffTimeSlotActivity[],
): Promise<any> {
try {
return timeSlots
.filter(async (timeslot: IHubstaffTimeSlotActivity) => {
return !!await this._commandBus.execute(
new IntegrationMapSyncTimeSlotCommand(
Object.assign({
timeSlot: {
...timeslot,
employeeId: employee.gauzyId
},
sourceId: timeslot.id,
integrationId,
organizationId
})
)
);
})
.map(
({ keyboard, mouse, overall, tracked, time_slot }) => ({
keyboard,
mouse,
overall,
duration: tracked,
startedAt: time_slot
})
);
} catch (error) {
throw new BadRequestException(error, `Can\'t sync ${IntegrationEntity.TIME_SLOT}`);
}
}
async syncTimeLogs(
timeLogs: any,
token: string,
integrationId: string,
organizationId: string,
projectId: string
): Promise<IIntegrationMap[]> {
try {
let integratedTimeLogs: IIntegrationMap[] = [];
const tenantId = RequestContext.currentTenantId();
for await (const timeLog of timeLogs) {
const { id, user_id, task_id, logType, startedAt, stoppedAt, timeSlots } = timeLog;
const employee = await this._getEmployeeByHubstaffUserId(
user_id,
token,
integrationId,
organizationId
);
const { record } = await this._integrationMapService.findOneOrFailByOptions({
where: {
sourceId: task_id,
entity: IntegrationEntity.TASK,
organizationId,
tenantId
}
});
const syncTimeSlots = await this.syncTimeSlots(
integrationId,
organizationId,
employee,
timeSlots
);
integratedTimeLogs.push(
await this._commandBus.execute(
new IntegrationMapSyncTimeLogCommand(
Object.assign({}, {
timeLog: {
projectId,
employeeId: employee.gauzyId,
taskId: record ? record.gauzyId : null,
logType,
startedAt,
stoppedAt,
source: TimeLogSourceEnum.HUBSTAFF,
organizationId,
tenantId,
timeSlots: syncTimeSlots
},
sourceId: id,
integrationId,
organizationId
})
)
)
);
}
return integratedTimeLogs;
} catch (error) {
throw new BadRequestException(error, `Can\'t sync ${IntegrationEntity.TIME_LOG}`);
}
}
async syncEmployee({ integrationId, user, organizationId }) {
try {
const tenantId = RequestContext.currentTenantId();
const { record } = await this._userService.findOneOrFailByOptions({
where: {
email: user.email,
tenantId
}
});
let employee;
if (record) {
employee = await this._commandBus.execute(
new EmployeeGetCommand({ where: { userId: record.id } })
);
} else {
const [role, organization] = await Promise.all([
await this._roleService.findOneByOptions({
where: {
name: RolesEnum.EMPLOYEE,
tenantId
}
}),
await this._organizationService.findOneByOptions({
where: {
id: organizationId,
tenantId
}
})
]);
const [firstName, lastName] = user.name.split(' ');
const isActive = user.status === 'active' ? true : false;
employee = await this._commandBus.execute(
new EmployeeCreateCommand({
user: {
email: user.email,
firstName,
lastName,
role,
tags: null,
tenantId,
preferredComponentLayout: ComponentLayoutStyleEnum.TABLE,
thirdPartyId: user.id
},
password: env.defaultIntegratedUserPass,
organization,
startedWorkOn: new Date(
moment().format('YYYY-MM-DD HH:mm:ss')
),
isActive,
tenantId
})
);
}
return await this._commandBus.execute(
new IntegrationMapSyncEntityCommand({
gauzyId: employee.id,
integrationId,
sourceId: user.id,
entity: IntegrationEntity.EMPLOYEE,
organizationId
})
);
} catch (error) {
throw new BadRequestException(error, `Can\'t sync ${IntegrationEntity.EMPLOYEE}`);
}
}
private async _handleEmployee({
user_id,
integrationId,
token,
organizationId
}) {
try {
const { user } = await this.fetchIntegration(
`users/${user_id}`,
token
);
return await this.syncEmployee({
integrationId,
user,
organizationId
});
} catch (error) {
throw new BadRequestException(error, `Can\'t handle ${IntegrationEntity.EMPLOYEE}`);
}
}
private async _handleProjects(
sourceId: string,
integrationId: string,
gauzyId: string,
token: string
) {
try {
const { projects } = await this.fetchIntegration(
`organizations/${sourceId}/projects?status=all`,
token
);
const projectMap = projects.map(({ name, id, billable, description }) => ({
name,
sourceId: id,
billable,
description
})
);
return await this.syncProjects({
integrationId,
organizationId: gauzyId,
projects: projectMap,
token
});
} catch (error) {
throw new BadRequestException(`Can\'t handle ${IntegrationEntity.PROJECT}`);
}
}
private async _handleClients(
sourceId: string,
integrationId: string,
gauzyId: string,
token: string
) {
try {
const { clients } = await this.fetchIntegration(
`organizations/${sourceId}/clients?status=active`,
token
);
return await this.syncClients({
integrationId,
organizationId: gauzyId,
clients
});
} catch (error) {
throw new BadRequestException(error, `Can\'t handle ${IntegrationEntity.CLIENT}`);
}
}
private async _handleTasks(projectsMap, integrationId, token, gauzyId) {
try {
const tasksMap = await Promise.all(
projectsMap.map(async (project) => {
const { tasks } = await this.fetchIntegration(
`projects/${project.sourceId}/tasks`,
token
);
return await this.syncTasks({
integrationId,
tasks,
projectId: project.gauzyId,
organizationId: gauzyId
});
})
);
return tasksMap;
} catch (error) {
throw new BadRequestException(error, `Can\'t handle ${IntegrationEntity.TASK}`);
}
}
/*
* Sync with database urls activities
*/
async syncUrlActivities({
integrationId,
projectId,
activities,
token,
organizationId
}): Promise<IIntegrationMap[]> {
try {
const tenantId = RequestContext.currentTenantId();
return await Promise.all(
await activities.map(
async ({ id, site, tracked, user_id, time_slot, task_id }) => {
const time = moment(time_slot).format('HH:mm:ss');
const date = moment(time_slot).format('YYYY-MM-DD');
const employee = await this._getEmployeeByHubstaffUserId(
user_id,
token,
integrationId,
organizationId
);
const { record: task } = await this._integrationMapService.findOneOrFailByOptions({
where: {
sourceId: task_id,
entity: IntegrationEntity.TASK,
organizationId,
tenantId
}
});
const activity: IActivity = {
title: site,
duration: tracked,
type: ActivityType.URL,
time,
date,
projectId,
employeeId: employee ? employee.gauzyId : null,
taskId: task ? task.gauzyId : null,
organizationId,
activityTimestamp: time_slot
};
return await this._commandBus.execute(
new IntegrationMapSyncActivityCommand(
Object.assign({}, {
activity,
sourceId: id,
integrationId,
organizationId
})
)
);
}
)
);
} catch (error) {
throw new BadRequestException(error, `Can\'t sync URL ${IntegrationEntity.ACTIVITY}`);
}
}
/*
* auto sync for urls activities for seperate project
*/
private async _handleUrlActivities(
projectsMap: IIntegrationMap[],
integrationId: string,
token: string,
organizationId: string,
dateRange: IDateRangeActivityFilter
) {
try {
const start = moment(dateRange.start).format('YYYY-MM-DD');
const end = moment(dateRange.end).format('YYYY-MM-DD');
const pageLimit = 500;
const urlActivitiesMapped = await Promise.all(
projectsMap.map(async (project) => {
const { gauzyId, sourceId } = project;
const syncedActivities = {
urlActivities: []
};
let stillRecordsAvailable = true;
let nextPageStartId = null;
while (stillRecordsAvailable) {
let url = `projects/${sourceId}/url_activities?page_limit=${pageLimit}&time_slot[start]=${start}&time_slot[stop]=${end}`;
if (nextPageStartId) {
url += `&page_start_id=${nextPageStartId}`;
}
const {
urls,
pagination = {}
} = await this.fetchIntegration(url, token);
if (
pagination &&
pagination.hasOwnProperty('next_page_start_id')
) {
const { next_page_start_id } = pagination;
nextPageStartId = next_page_start_id;
stillRecordsAvailable = true;
} else {
nextPageStartId = null;
stillRecordsAvailable = false;
}
syncedActivities.urlActivities.push(urls);
}
const activities = [].concat.apply(
[],
syncedActivities.urlActivities
);
return await this.syncUrlActivities({
integrationId,
projectId: gauzyId,
activities,
token,
organizationId
});
})
);
return urlActivitiesMapped;
} catch (error) {
throw new BadRequestException(error, `Can\'t handle URL ${IntegrationEntity.ACTIVITY}`);
}
}
/*
* Sync with database application activities
*/
async syncAppActivities({
integrationId,
projectId,
activities,
token,
organizationId
}): Promise<IIntegrationMap[]> {
try {
const tenantId = RequestContext.currentTenantId();
return await Promise.all(
await activities.map(
async ({ id, name, tracked, user_id, time_slot, task_id }) => {
const time = moment(time_slot).format('HH:mm:ss');
const date = moment(time_slot).format('YYYY-MM-DD');
const employee = await this._getEmployeeByHubstaffUserId(
user_id,
token,
integrationId,
organizationId
);
const { record: task } = await this._integrationMapService.findOneOrFailByOptions({
where: {
sourceId: task_id,
entity: IntegrationEntity.TASK,
organizationId,
tenantId
}
});
const activity: IActivity = {
title: name,
duration: tracked,
type: ActivityType.APP,
time,
date,
projectId,
employeeId: employee ? employee.gauzyId : null,
taskId: task ? task.gauzyId : null,
organizationId,
activityTimestamp: time_slot
};
return await this._commandBus.execute(
new IntegrationMapSyncActivityCommand(
Object.assign({}, {
activity,
sourceId: id,
integrationId,
organizationId
})
)
);
}
)
);
} catch (error) {
throw new BadRequestException(error, `Can\'t sync APP ${IntegrationEntity.ACTIVITY}`);
}
}
/*
* auto sync for application activities for seperate project
*/
private async _handleAppActivities(
projectsMap: IIntegrationMap[],
integrationId: string,
token: string,
organizationId: string,
dateRange: IDateRangeActivityFilter
) {
try {
const start = moment(dateRange.start).format('YYYY-MM-DD');
const end = moment(dateRange.end).format('YYYY-MM-DD');
const pageLimit = 500;
const appActivitiesMapped = await Promise.all(
projectsMap.map(async (project) => {
const { gauzyId, sourceId } = project;
const syncedActivities = {
applicationActivities: []
};
let stillRecordsAvailable = true;
let nextPageStartId = null;
while (stillRecordsAvailable) {
let url = `projects/${sourceId}/application_activities?page_limit=${pageLimit}&time_slot[start]=${start}&time_slot[stop]=${end}`;
if (nextPageStartId) {
url += `&page_start_id=${nextPageStartId}`;
}
const {
applications,
pagination = {}
} = await this.fetchIntegration(url, token);
if (
pagination &&
pagination.hasOwnProperty('next_page_start_id')
) {
const { next_page_start_id } = pagination;
nextPageStartId = next_page_start_id;
stillRecordsAvailable = true;
} else {
nextPageStartId = null;
stillRecordsAvailable = false;
}
syncedActivities.applicationActivities.push(
applications
);
}
const activities = [].concat.apply(
[],
syncedActivities.applicationActivities
);
return await this.syncAppActivities({
integrationId,
projectId: gauzyId,
activities,
token,
organizationId
});
})
);
return appActivitiesMapped;
} catch (error) {
throw new BadRequestException(error, `Can\'t handle APP ${IntegrationEntity.ACTIVITY}`);
}
}
private async _handleActivities(
projectsMap: IIntegrationMap[],
integrationId: string,
token: string,
organizationId: string,
dateRange: IDateRangeActivityFilter
) {
try {
const start = moment(dateRange.start).format('YYYY-MM-DD');
const end = moment(dateRange.end).format('YYYY-MM-DD');
const integratedTimeLogs: IIntegrationMap[] = [];
for await (const project of projectsMap) {
const { activities } = await this.fetchIntegration<IHubstaffTimeSlotActivity[]>(
`projects/${project.sourceId}/activities?time_slot[start]=${start}&time_slot[stop]=${end}`,
token
);
if (isEmpty(activities)) {
continue;
}
const timeLogs = this.formatLogsFromSlots(activities);
const integratedTimeLogs = await this.syncTimeLogs(
timeLogs,
token,
integrationId,
organizationId,
project.gauzyId
);
integratedTimeLogs.push(...integratedTimeLogs);
}
return integratedTimeLogs;
} catch (error) {
if (error instanceof HttpException) {
throw new HttpException(error.getResponse(), error.getStatus());
}
throw new BadRequestException(error, `Can\'t handle ${IntegrationEntity.ACTIVITY}`);
}
}
/**
* Sync activities screenshots
*/
private async _handleScreenshots(
projectsMap: IIntegrationMap[],
integrationId: string,
token: string,
organizationId: string,
dateRange: IDateRangeActivityFilter
): Promise<IIntegrationMap[][]> {
try {
const start = moment(dateRange.start).format('YYYY-MM-DD');
const end = moment(dateRange.end).format('YYYY-MM-DD');
const pageLimit = 500;
return await Promise.all(
projectsMap.map(async (project) => {
const { sourceId } = project;
const syncedActivities = {
screenshots: []
};
let stillRecordsAvailable = true;
let nextPageStartId = null;
while (stillRecordsAvailable) {
let url = `projects/${sourceId}/screenshots?page_limit=${pageLimit}&time_slot[start]=${start}&time_slot[stop]=${end}`;
if (nextPageStartId) {
url += `&page_start_id=${nextPageStartId}`;
}
const {
screenshots: fetchScreenshots,
pagination = {}
} = await this.fetchIntegration(url, token);
if (
pagination &&
pagination.hasOwnProperty('next_page_start_id')
) {
const { next_page_start_id } = pagination;
nextPageStartId = next_page_start_id;
stillRecordsAvailable = true;
} else {
nextPageStartId = null;
stillRecordsAvailable = false;
}
syncedActivities.screenshots.push(fetchScreenshots);
}
const screenshots = [].concat.apply(
[],
syncedActivities.screenshots
);
return await this.syncScreenshots({
integrationId,
screenshots,
token,
organizationId
});
})
);
} catch (error) {
throw new BadRequestException(error, `Can\'t handle activities ${IntegrationEntity.SCREENSHOT}`);
}
}
async autoSync({
integrationId,
gauzyId,
sourceId,
token,
dateRange
}) {
console.log(`${IntegrationEnum.HUBSTAFF} integration start for ${integrationId}`);
/**
* GET organization tenant integration entities settings
*/
const tenantId = RequestContext.currentTenantId();
const { entitySettings } = await this._integrationTenantService.findOneByConditions(integrationId, {
where: {
tenantId
},
relations: ['entitySettings', 'entitySettings.tiedEntities']
});
//entities have depended entity. eg to fetch Task we need Project id or Org id, because our Task entity is related to Project, the relation here is same, we need project id to fetch Tasks
const integratedMaps = await Promise.all(
entitySettings.map(async (setting) => {
switch (setting.entity) {
case IntegrationEntity.PROJECT:
let tasks, activities, screenshots;
const projectsMap: IIntegrationMap[] = await this._handleProjects(
sourceId,
integrationId,
gauzyId,
token
);
/**
* Tasks Sync
*/
const taskSetting: IIntegrationEntitySetting = setting.tiedEntities.find(
(res) => res.entity === IntegrationEntity.TASK
);
if (isObject(taskSetting) && taskSetting.sync) {
tasks = await this._handleTasks(
projectsMap,
integrationId,
token,
gauzyId
);
}
/**
* Activity Sync
*/
const activitySetting: IIntegrationEntitySetting = setting.tiedEntities.find(
(res) => res.entity === IntegrationEntity.ACTIVITY
);
if (isObject(activitySetting) && activitySetting.sync) {
activities = await this._handleActivities(
projectsMap,
integrationId,
token,
gauzyId,
dateRange
);
activities.application = await this._handleAppActivities(
projectsMap,
integrationId,
token,
gauzyId,
dateRange
);
activities.urls = await this._handleUrlActivities(
projectsMap,
integrationId,
token,
gauzyId,
dateRange
);
}
/**
* Activity Screenshot Sync
*/
const screenshotSetting: IIntegrationEntitySetting = setting.tiedEntities.find(
(res) => res.entity === IntegrationEntity.SCREENSHOT
);
if (isObject(screenshotSetting) && screenshotSetting.sync) {
screenshots = await this._handleScreenshots(
projectsMap,
integrationId,
token,
gauzyId,
dateRange
);
}
return { tasks, projectsMap, activities, screenshots };
case IntegrationEntity.CLIENT:
const clients = await this._handleClients(
sourceId,
integrationId,
gauzyId,
token
);
return { clients };
}
})
);
console.log(`${IntegrationEnum.HUBSTAFF} integration end for ${integrationId}`);
return integratedMaps;
}
formatLogsFromSlots(slots: IHubstaffTimeSlotActivity[]) {
if (isEmpty(slots)) {
return;
}
const range = [];
let i = 0;
while (slots[i]) {
const start = moment(slots[i].starts_at);
const end = moment(slots[i].starts_at).add(slots[i].tracked, 'seconds');
range.push({
start: start.toDate(),
end: end.toDate()
});
i++;
}
const timeLogs: Array<any> = [];
const dates: IDateRange[] = mergeOverlappingDateRanges(range);
if (isNotEmpty(dates)) {
dates.forEach(({ start, end}) => {
let i = 0;
const timeSlots = new Array();
while (slots[i]) {
const slotTime = moment(slots[i].starts_at);
if (slotTime.isBetween(moment(start), moment(end), null, '[]')) {
timeSlots.push(slots[i]);
}
i++;
}
const [ activity ] = this.getLogsActivityFromSlots(timeSlots);
timeLogs.push({
startedAt: start,
stoppedAt: end,
timeSlots,
...activity
});
});
}
return timeLogs;
}
/**
* GET TimeLogs from Activity TimeSlots
*
* @param timeSlots
* @returns
*/
getLogsActivityFromSlots(timeSlots: IHubstaffTimeSlotActivity[]): IHubstaffLogFromTimeSlots[] {
const timeLogs = timeSlots.reduce((prev, current) => {
const prevLog = prev[current.date];
return {
...prev,
[current.date]: prevLog
? {
id: current.id,
date: current.date,
user_id: prevLog.user_id,
project_id: prevLog.project_id || null,
task_id: prevLog.task_id || null,
// this will take the last chunk(slot), maybe we should allow percentage for this, as one time log can have both manual and tracked
logType:
current.client === 'windows'
? TimeLogType.TRACKED
: TimeLogType.MANUAL
}
: {
id: current.id,
date: current.date,
user_id: current.user_id,
project_id: current.project_id || null,
task_id: current.task_id || null,
logType:
current.client === 'windows'
? TimeLogType.TRACKED
: TimeLogType.MANUAL
}
};
}, {});
return Object.values(timeLogs);
}
} | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import { exec } from 'child_process';
/* eslint-disable import/no-unassigned-import mocha-no-side-effect-code */
import "mocha";
import * as chai from "chai";
import { TestHost } from "../common/testHost";
import * as util from "../common/testUtils";
import { resolve } from 'url';
import { promisify } from 'util';
// TODO: Split this file up. I (dazuniga) spent ~1hr trying to split this file into two pieces but I cannot figure out
// how to make that work with the way we're using jake & namespaces / modules
// setup
function initGlobals() {
let g = global as any
g.pxt = pxt;
g.ts = ts;
g.pxtc = pxtc;
g.btoa = (str: string) => Buffer.from(str, "binary").toString("base64");
g.atob = (str: string) => Buffer.from(str, "base64").toString("binary");
}
initGlobals();
// Just needs to exist
pxt.setAppTarget(util.testAppTarget);
// tests files
const casesDir = path.join(process.cwd(), "tests", "runtime-trace-tests", "cases");
describe("convert between ts<->py ", () => {
// TODO: can this be moved to a mocha before() block?
let tsAndPyFiles: string[]
pxsim.initCurrentRuntime = pxsim.initBareRuntime
cleanup()
let tsFiles = util.getFilesByExt(casesDir, ".ts")
let pyFiles = util.getFilesByExt(casesDir, ".py")
// optionally diable files using a "TODO_" prefix
const isDisabled = (file: string): boolean =>
path.basename(file).indexOf("TODO") >= 0
tsAndPyFiles = tsFiles.concat(pyFiles)
.filter(f => !isDisabled(f))
// optionally whitelist files using a "ONLY_" prefix
const isWhitelisted = (file: string): boolean =>
path.basename(file).indexOf("ONLY") >= 0
let whitelisted = tsAndPyFiles.filter(isWhitelisted)
if (whitelisted.length)
tsAndPyFiles = whitelisted
tsAndPyFiles.forEach(file => {
it("should preserve the runtime semantics of " + path.basename(file), async function () {
this.timeout(10000)
await testTsOrPy(file)
return
});
});
});
// we use this simple wrapper to enfore content type of "string". writeFileSync
// accepts "any" and we've had bugs where objects get inadvertently written
function writeFileStringSync(filePath: string, content: string) {
fs.writeFileSync(filePath, content)
}
async function testTsOrPy(tsOrPyFile: string): Promise<void> {
let ext = path.extname(tsOrPyFile)
let isPy = ext === ".py"
let isTs = ext === ".ts"
if (!isPy && !isTs)
return Promise.reject(new Error("Invald non-.py, non-.ts file: " + tsOrPyFile))
let baselineFile: string;
let baseline: string;
let recordBaseline = (bl: string) => {
baseline = bl
baselineFile = tsOrPyFile + ".baseline"
writeFileStringSync(baselineFile, baseline)
}
if (isPy) {
let pyFile = tsOrPyFile
recordBaseline(await PY(pyFile))
let tsFile = await testPy2Ts(pyFile)
await testSts(tsFile)
let pyFile2 = await testTs2Py(tsFile)
} else {
let tsFile = tsOrPyFile
recordBaseline(await TS(tsFile))
await testSts(tsFile)
let pyFile = await testTs2Py(tsFile)
// TODO: py2ts needs to implement more features before we can run the full test suite. Specifically at least:
// - types: str, List[]
// let tsfile2 = await testPy2Ts(pyFile)
// await testSts(tsfile2)
}
return;
// DSL for the tests
type Trace = string
type File = string
function STS(tsFile: string): Promise<Trace> { return compileAndRunStsAsync(tsFile) }
function TS(tsFile: string): Promise<Trace> { return compileAndRunTs(tsFile) }
function PY(pyFile: string): Promise<Trace> { return runPyAsync(pyFile) }
function TS2PY(tsFile: string): Promise<File> { return convertTs2Py(tsFile) }
function PY2TS(pyFile: string): Promise<File> { return convertPy2Ts(pyFile) }
// Test functions & helpers
async function testPy2Ts(pyFile: string): Promise<string> {
return testConversion(pyFile, true)
}
async function testTs2Py(tsFile: string): Promise<string> {
return testConversion(tsFile, false)
}
async function testConversion(inFile: string, isPy: boolean): Promise<string> {
let convert = isPy ? PY2TS : TS2PY
let runConverted = isPy ? TS : PY
let fnName = isPy ? "py2ts" : "ts2py"
let errFile = inFile + `.${fnName}_error`;
return convert(inFile)
.catch(e => {
writeFileStringSync(errFile, JSON.stringify(e))
return `${fnName} failed to convert '${inFile}'. Error saved at:\n${errFile}\nError is:\n${e}\n`
})
.then(async outFile => {
let outTrace = await runConverted(outFile)
if (!util.compareBaselines(outTrace, baseline)) {
writeFileStringSync(errFile, outTrace)
return Promise.reject(new Error(
`${fnName} incorrectly converted:\n` +
`${inFile}\n${fs.readFileSync(inFile, "utf8")}\nto:\n${outFile}\n${fs.readFileSync(outFile, "utf8")}\n` +
`Trace mismatch with baseline. Baseline:\n${baseline}\nIncorrect trace:\n${outTrace}\n` +
`Diff conversion with:\ncode --diff ${inFile} ${outFile}\n` +
`Diff traces with:\ncode --diff ${baselineFile} ${errFile}\n`))
}
return outFile
})
}
async function testSts(tsFile: string): Promise<void> {
let errFile = tsFile + ".sts_error"
return STS(tsFile)
.catch(error => {
let errStr = `${error}`
writeFileStringSync(errFile, errStr)
return Promise.reject(new Error(`Static Typescript failed to run on:\n${tsFile}\nError saved at:\n${errFile}\nError is:\n${errStr}\n`))
})
.then(outTrace => {
if (!util.compareBaselines(outTrace, baseline)) {
writeFileStringSync(errFile, outTrace)
return Promise.reject(new Error(
`Static Typescript produced a different trace than node.js when run on:\n${tsFile}\n` +
`Baseline:\n${baseline}\nIncorrect trace:\n${outTrace}\n` +
`Diff traces with:\ncode --diff ${baselineFile} ${errFile}\n`))
}
return Promise.resolve();
})
}
}
function removeBySubstring(dir: string, sub: string) {
return fs.readdirSync(dir)
.filter(f => f.indexOf(sub) >= 0)
.map(f => path.join(dir, f))
.forEach(f => fs.unlinkSync(f))
}
function cleanup() {
removeBySubstring(casesDir, ".js")
removeBySubstring(casesDir, ".py.ts")
removeBySubstring(casesDir, ".ts.py")
removeBySubstring(casesDir, ".py2ts_error")
removeBySubstring(casesDir, ".ts2py_error")
removeBySubstring(casesDir, ".sts_error")
removeBySubstring(casesDir, ".baseline")
}
function runProcAsync(cmd: string, stdin?: string): Promise<string> {
return new Promise((resolve, reject) => {
let e = exec(cmd, (err, stdout, stderr) => {
let trace = ""
if (stdout)
trace += stdout
if (stderr)
trace += stderr
resolve(trace)
})
if (stdin) {
e.stdin.write(stdin);
e.stdin.end();
}
});
}
function runPyAsync(pyFile: string): Promise<string> {
let pyBody = fs.readFileSync(pyFile, "utf8")
// swap "(args) -> ret" syntax for "Callable[[args] -> ret]"
pyBody = pyBody.replace(/: \((.*?)\) -> ([\w]+)/gi, function (f, m1, m2) {
return ": Callable[[" + m1 + "], " + m2 + "]";
})
const prelude = `
from typing import *
number = Any
class Enum:
pass
# end prelude
`;
let pyStr = `${prelude}\n${pyBody}`
let escapedStr = `<<"EOF"\n${pyStr}\nEOF`
let cmd = `python3 ${escapedStr}`
return runProcAsync("python3", pyStr)
}
function runNodeJsAsync(nodeArgs: string): Promise<string> {
// Note: another option would be to use eval() but
// at least this way we get process isolation. E.g.:
/*
let stout: string[] = []
let console: any = {}
console.log = function (str: string) {
stout.push(str)
return str
}
eval(js)
return stout.join("\n")
*/
return runProcAsync(`node ${nodeArgs}`)
}
async function convertTs2Py(tsFile: string): Promise<string> {
const tsCode = fs.readFileSync(tsFile, "utf8").replace(/\r\n/g, "\n");
let pyCode = await util.ts2pyAsync(tsCode, null, false, tsFile)
const pyFile = path.join(util.replaceFileExtension(tsFile, ".ts.py"));
writeFileStringSync(pyFile, pyCode)
return pyFile
}
async function convertPy2Ts(pyFile: string): Promise<string> {
const pyCode = fs.readFileSync(pyFile, "utf8").replace(/\r\n/g, "\n");
let tsCode = await util.py2tsAsync(pyCode, null, false, true, pyFile)
const tsFile = path.join(util.replaceFileExtension(pyFile, ".py.ts"));
writeFileStringSync(tsFile, tsCode.ts)
return tsFile
}
function emitJsFiles(prog: ts.Program, file?: ts.SourceFile): string[] {
let jsFiles: string[] = []
prog.emit(file, (f, data) => {
writeFileStringSync(f, data)
jsFiles.push(f)
});
return jsFiles
}
function compileTsToJs(files: string[]): ts.Program {
let cOpts: ts.CompilerOptions = {
noEmitOnError: true,
noImplicitAny: true,
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.ES2015,
noLib: true,
skipLibCheck: true,
types: [],
}
// TODO: it'd be great to include the python helper fns so we can cover
// more scenarios however this doesn't work easily since we use custom methods
// like Array.removeAt which don't exist in vanilla JS. We'd need to provide
// an implementation for these tests
// const pyHelpers = ["pxt-python-helpers.ts"]
// .map(f => path.resolve("libs", "pxt-python", f), 'utf8')
let allFiles = [...files, path.resolve("pxtcompiler/ext-typescript/lib/lib.d.ts")/*, ...pyHelpers*/]
return ts.pxtc.plainTscCompileFiles(allFiles, cOpts)
}
async function compileAndRunTs(filename: string): Promise<string> {
let prog = compileTsToJs([filename])
let diagnostics = ts.pxtc.getProgramDiagnostics(prog)
let diagMsgs = diagnostics.map(ts.pxtc.getDiagnosticString)
if (diagMsgs.length)
return diagMsgs.join("\n")
else {
let fileSrc = prog.getSourceFile(path.basename(filename))
let jsFiles = emitJsFiles(prog, fileSrc)
let nodejsCmdLine = jsFiles
.join(", ")
let trace = await runNodeJsAsync(nodejsCmdLine)
return trace
}
}
function compileAndRunStsAsync(filename: string): Promise<string> {
const prelude = `
// end prelude
`
// TODO(dz): why is this necessary? This doesn't seem right..
// without this pause(), a lot of the console output doesn't appear
const postlude = `
// start postlude
pause(300);
`
let body = fs.readFileSync(filename, "utf8")
let tsMain = [prelude, body, postlude].join("\n")
return util.stsAsync(tsMain)
.then((compiled) => {
return runStsAsync(compiled)
})
}
function runStsAsync(res: pxtc.CompileResult): Promise<string> {
return new Promise<string>((resolve, reject) => {
let f = res.outfiles[pxtc.BINARY_JS]
if (f) {
let timeout = setTimeout(() => {
reject(new Error("Simulating code timed out"))
}, 5000);
let r = new pxsim.Runtime({ type: "run", code: f })
r.errorHandler = (e) => {
clearTimeout(timeout);
reject(e);
}
let trace = ""
pxsim.Runtime.messagePosted = (msg) => {
if (msg.type === "bulkserial") {
let smsg = msg as pxsim.SimulatorBulkSerialMessage
for (let m of smsg.data)
trace += `${m.data}\n`
} else if (msg.type === "status") {
} else {
trace += `\nUNKNOWN: ${msg.type}\n`
}
}
r.run(() => {
clearTimeout(timeout);
pxsim.dumpLivePointers();
resolve(trace)
})
}
else {
reject(new Error("No compiled js"));
}
})
} | the_stack |
import { RecorderEnvironmentSetup, windowLens } from "../../src/utils";
import { record, TestContextInterface, TestContext, TestContextTest } from "../../src";
import { consoleLog, setConsoleLogForTesting } from "../../src/customConsoleLog";
import { expect } from "chai";
import MD5 from "md5";
import xhrMock from "xhr-mock";
const expectedHttpResponse = "Hello World!";
async function helloWorldRequest(): Promise<string> {
return new Promise((resolve) => {
function reqListener(this: any) {
resolve(this.responseText);
}
const req = new XMLHttpRequest();
req.addEventListener("load", reqListener);
req.open("GET", windowLens.get(["__env__", "PATH"]));
req.send();
});
}
const recorderEnvSetup: RecorderEnvironmentSetup = {
replaceableVariables: {
PATH: "/replaced"
},
customizationsOnRecordings: [],
queryParametersToSkip: []
};
/**
* A function that generates another function with a predictable shape, even after compiling it to the browser.
*/
const getNoOpFunction = () => {
/* istanbul ignore next */
return () => {};
};
/**
* Another function that generates another function with a predictable shape, even after compiling it to the browser.
*/
const getAnotherNoOpFunction = () => {
/* istanbul ignore next */
return () => 1;
};
describe("The recorder's public API, on a browser", () => {
afterEach(() => {
windowLens.set(["__env__", "TEST_MODE"], undefined);
windowLens.set(["__env__", "PATH"], undefined);
windowLens.set(["__json__"], undefined);
});
it("should record a simple test", async function() {
// Setting up the record mode, and the PATH environment variable.
windowLens.set(["__env__", "TEST_MODE"], "record");
windowLens.set(["__env__", "PATH"], "/to/replace");
// We can't use Nise's FakeServer since the recorder ends up sending the request through the original XHR anyway.
xhrMock.setup();
xhrMock.get("/to/replace", {
status: 200,
body: expectedHttpResponse
});
// Before starting the recorder, we need to make a copy of the original XHR object, so that we can
// restore it before doing the recorder do its magic, in order for the HTTP request to hit the xhr-mock instance.
const originalXHR = XMLHttpRequest;
// The recorder outputs files into the console,
// so we need to mock the console.log function to capture and test the recorder output.
const originalConsoleLog = consoleLog;
const savedConsoleLogParams: any[] = [];
setConsoleLogForTesting((...params: any[]) => {
if (params && params.length > 0) {
try {
if (JSON.parse(params[0]).writeFile) {
savedConsoleLogParams.push(params);
}
} catch (err) {}
}
});
// The recorder should start in the beforeEach call.
// We have to do this to emulate that.
const fakeThis: TestContextInterface = new TestContext(this.test! as TestContextTest, {
...this.currentTest,
file: "test/recorder.browser.spec.ts",
// For this test, we don't care what's the content of the recorded function.
fn: getNoOpFunction()
});
const recorder = record(fakeThis, recorderEnvSetup);
// Restoring the XHR, otherwise we can't test this.
windowLens.set(["XMLHttpRequest"], originalXHR);
const response = await helloWorldRequest();
// This test's request reached the server and received the expected response.
expect(response).to.equal(expectedHttpResponse);
// Cleaning everything before we continue verifying the results.
xhrMock.teardown();
await recorder.stop();
setConsoleLogForTesting(originalConsoleLog);
// Here we confirm that the recorder generated an expected output on the console.logs.
// This output is used to generate the recording files in the filesystem, though here we're only
// checking what was that the recorded emitted to the standard output.
expect(savedConsoleLogParams[0][0]).to.equal(
// The recordings here are empty because we hijacked the XHR.
// See the playback test for an example of a properly constructed recording object.
// TODO: Find a way to capture the complete output.
JSON.stringify({
writeFile: true,
path:
"./recordings/browsers/the_recorders_public_api_on_a_browser/recording_should_record_a_simple_test.json",
content: {
recordings: [],
uniqueTestInfo: {
uniqueName: {},
newDate: {}
},
hash: MD5(getNoOpFunction().toString())
}
})
);
});
it("should playback a simple test", async function() {
// Setting up the playback mode.
// The PATH environment variable is not needed on playback.
// The recorder will assume that it is in playback mode by default.
// windowLens.set(["__env__", "TEST_MODE"], "playback");
// This is to emulate what 'karma-json-preprocessor' does for us during the real scenarios.
windowLens.set(
[
"__json__",
"recordings/browsers/the_recorders_public_api_on_a_browser/recording_should_playback_a_simple_test.json"
],
{
recordings: [
{
method: "GET",
url: "/replaced",
response: expectedHttpResponse
}
],
uniqueTestInfo: { uniqueName: {}, newDate: {} }
}
);
// The recorder should start in the beforeEach call.
// To emulate that behavior while keeping the test code as contained as possible,
// we're compensating with this.
const fakeThis: TestContextInterface = new TestContext(this.test! as TestContextTest, {
...this.currentTest,
file: "test/recorder.browser.spec.ts",
// For this test, we don't care what's the content of the recorded function.
fn: getNoOpFunction()
});
const recorder = record(fakeThis, recorderEnvSetup);
const response = await helloWorldRequest();
// The playback code served the appropriate response based on the recordings.
expect(response).to.equal(expectedHttpResponse);
await recorder.stop();
});
it("soft-record should re-record a simple outdated test", async function() {
// Setting up the playback mode.
// The PATH environment variable is not needed on playback.
windowLens.set(["__env__", "TEST_MODE"], "soft-record");
windowLens.set(["__env__", "PATH"], "/to/replace");
// This is to emulate what 'karma-json-preprocessor' does for us during the real scenarios.
windowLens.set(
[
"__json__",
"recordings/browsers/the_recorders_public_api_on_a_browser/recording_softrecord_should_rerecord_a_simple_outdated_test.json"
],
{
recordings: [
{
method: "GET",
url: "/replaced",
response: expectedHttpResponse
}
],
uniqueTestInfo: { uniqueName: {}, newDate: {} },
hash: "fake old hash"
}
);
// We can't use Nise's FakeServer since the recorder ends up sending the request through the original XHR anyway.
xhrMock.setup();
xhrMock.get("/to/replace", {
status: 200,
body: expectedHttpResponse
});
// Before starting the recorder, we need to make a copy of the original XHR object, so that we can
// restore it before doing the recorder do its magic, in order for the HTTP request to hit the xhr-mock instance.
const originalXHR = XMLHttpRequest;
// The recorder outputs files into the console,
// so we need to override the consoleLog function to capture and test the recorder output.
const originalConsoleLog = consoleLog;
const savedConsoleLogParams: any[] = [];
setConsoleLogForTesting((...params: any[]) => {
if (params && params.length > 0) {
try {
if (JSON.parse(params[0]).writeFile) {
savedConsoleLogParams.push(params);
}
} catch (err) {}
}
});
// The recorder should start in the beforeEach call.
// To emulate that behavior while keeping the test code as contained as possible,
// we're compensating with this.
const fakeThis: TestContextInterface = new TestContext(this.test! as TestContextTest, {
...this.currentTest,
file: "test/recorder.browser.spec.ts",
// The hash in our expected recording is made out of an empty function.
// This function has something inside, which means it has changed.
fn: getAnotherNoOpFunction()
});
const recorder = record(fakeThis, recorderEnvSetup);
// Restoring the XHR, otherwise we can't test this.
windowLens.set(["XMLHttpRequest"], originalXHR);
const response = await helloWorldRequest();
// This test's request reached the server and received the expected response.
expect(response).to.equal(expectedHttpResponse);
// Cleaning everything before we continue verifying the results.
xhrMock.teardown();
await recorder.stop();
setConsoleLogForTesting(originalConsoleLog);
// Now we check the hash has changed in the recorded console.log output.
// Here we confirm that the recorder generated an expected output on the console.logs.
// This output is used to generate the recording files in the filesystem, though here we're only
// checking what was that the recorded emitted to the standard output.
expect(savedConsoleLogParams[0][0]).to.equal(
// The recordings here are empty because we hijacked the XHR.
// See the playback test for an example of a properly constructed recording object.
// TODO: Find a way to capture the complete output.
JSON.stringify({
writeFile: true,
path:
"./recordings/browsers/the_recorders_public_api_on_a_browser/recording_softrecord_should_rerecord_a_simple_outdated_test.json",
content: {
recordings: [],
uniqueTestInfo: {
uniqueName: {},
newDate: {}
},
hash: MD5(getAnotherNoOpFunction().toString())
}
})
);
});
it("soft-record should skip a simple unchanged test", async function() {
// Setting up the playback mode.
// The PATH environment variable is not needed on playback.
windowLens.set(["__env__", "TEST_MODE"], "soft-record");
// This is to emulate what 'karma-json-preprocessor' does for us during the real scenarios.
windowLens.set(
[
"__json__",
"recordings/browsers/the_recorders_public_api_on_a_browser/recording_softrecord_should_skip_a_simple_unchanged_test.json"
],
{
recordings: [
{
method: "GET",
url: "/replaced",
response: expectedHttpResponse
}
],
uniqueTestInfo: { uniqueName: {}, newDate: {} },
// This is the expected hash
hash: MD5(getNoOpFunction().toString())
}
);
// The recorder should start in the beforeEach call.
// To emulate that behavior while keeping the test code as contained as possible,
// we're compensating with this.
let skipped = false;
const fakeThis: TestContextInterface = new TestContext(this.test! as TestContextTest, {
...this.currentTest,
file: "test/recorder.browser.spec.ts",
// The hash in our expected recording is made out of an empty function.
// This function is empty, which means it remains the same.
fn: getNoOpFunction()
});
// We have to mock this.skip in order to confirm that the recorder has called it.
// We'll make a fake this.
fakeThis.skip = () => {
skipped = true;
throw new Error("Emulating mocha's skip");
};
try {
record(fakeThis, recorderEnvSetup);
} catch (e) {
if (e.message !== "Emulating mocha's skip") {
throw e;
}
}
expect(skipped).to.true;
});
}); | the_stack |
namespace fgui {
export class GLoader extends GObject implements IAnimationGear, IColorGear {
protected $url: string;
protected $align: AlignType;
protected $verticalAlign: VertAlignType;
protected $autoSize: boolean;
protected $fill: LoaderFillType;
protected $showErrorSign: boolean;
protected $playing: boolean;
protected $frame: number = 0;
protected $color: number = 0;
private $contentItem: PackageItem;
private $contentSourceWidth: number = 0;
private $contentSourceHeight: number = 0;
private $contentWidth: number = 0;
private $contentHeight: number = 0;
protected $container: UIContainer;
protected $content: UIImage | MovieClip;
protected $errorSign: GObject;
private $updatingLayout: boolean;
private static $errorSignPool: utils.GObjectRecycler = new utils.GObjectRecycler();
public constructor() {
super();
this.$playing = true;
this.$url = "";
this.$fill = LoaderFillType.None;
this.$align = AlignType.Left;
this.$verticalAlign = VertAlignType.Top;
this.$showErrorSign = true;
this.$color = 0xFFFFFF;
}
protected createDisplayObject(): void {
this.$container = new UIContainer(this);
this.$container.hitArea = new PIXI.Rectangle();
this.setDisplayObject(this.$container);
this.$container.interactiveChildren = false;
}
public dispose(): void {
this.clearContent();
super.dispose();
}
public get url(): string {
return this.$url;
}
public set url(value: string) {
if (this.$url == value)
return;
this.$url = value;
this.loadContent();
this.updateGear(GearType.Icon);
}
public get icon(): string {
return this.$url;
}
public set icon(value: string) {
this.url = value;
}
public get align(): AlignType {
return this.$align;
}
public set align(value: AlignType) {
if (this.$align != value) {
this.$align = value;
this.updateLayout();
}
}
public get verticalAlign(): VertAlignType {
return this.$verticalAlign;
}
public set verticalAlign(value: VertAlignType) {
if (this.$verticalAlign != value) {
this.$verticalAlign = value;
this.updateLayout();
}
}
public get fill(): LoaderFillType {
return this.$fill;
}
public set fill(value: LoaderFillType) {
if (this.$fill != value) {
this.$fill = value;
this.updateLayout();
}
}
public get autoSize(): boolean {
return this.$autoSize;
}
public set autoSize(value: boolean) {
if (this.$autoSize != value) {
this.$autoSize = value;
this.updateLayout();
}
}
public get playing(): boolean {
return this.$playing;
}
public set playing(value: boolean) {
if (this.$playing != value) {
this.$playing = value;
if (this.$content instanceof MovieClip)
this.$content.playing = value;
this.updateGear(GearType.Animation);
}
}
public get frame(): number {
return this.$frame;
}
public set frame(value: number) {
if (this.$frame != value) {
this.$frame = value;
if (this.$content instanceof MovieClip)
this.$content.currentFrame = value;
this.updateGear(GearType.Animation);
}
}
public get color(): number {
return this.$color;
}
public set color(value: number) {
if (this.$color != value) {
this.$color = value;
this.updateGear(GearType.Color);
this.applyColor();
}
}
private applyColor(): void {
if (this.$content)
this.$content.tint = this.$color;
}
public get showErrorSign(): boolean {
return this.$showErrorSign;
}
public set showErrorSign(value: boolean) {
this.$showErrorSign = value;
}
public get content(): UIImage | MovieClip {
return this.$content;
}
public get texture(): PIXI.Texture {
if (this.$content instanceof UIImage)
return this.$content.texture;
else
return null;
}
public set texture(value: PIXI.Texture) {
this.url = null;
this.switchToMovieMode(false);
if(this.$content instanceof UIImage)
this.$content.texture = value;
if (value) {
this.$contentSourceWidth = value.orig.width;
this.$contentSourceHeight = value.orig.height;
}
else
this.$contentSourceWidth = this.$contentHeight = 0;
this.updateLayout();
}
protected loadContent(): void {
this.clearContent();
if (!this.$url)
return;
if (utils.StringUtil.startsWith(this.$url, "ui://"))
this.loadFromPackage(this.$url);
else
this.loadExternal();
}
protected loadFromPackage(itemURL: string): void {
this.$contentItem = UIPackage.getItemByURL(itemURL);
if (this.$contentItem) {
this.$contentItem.load();
if (this.$contentItem.type == PackageItemType.Image) {
if (this.$contentItem.texture == null) {
this.setErrorState();
}
else {
this.switchToMovieMode(false);
(this.$content as UIImage).$initDisp(this.$contentItem);
this.$contentSourceWidth = this.$contentItem.width;
this.$contentSourceHeight = this.$contentItem.height;
this.updateLayout();
}
}
else if (this.$contentItem.type == PackageItemType.MovieClip) {
this.switchToMovieMode(true);
this.$contentSourceWidth = this.$contentItem.width;
this.$contentSourceHeight = this.$contentItem.height;
let mc: MovieClip = this.$content as MovieClip;
mc.interval = this.$contentItem.interval;
mc.swing = this.$contentItem.swing;
mc.repeatDelay = this.$contentItem.repeatDelay;
mc.frames = this.$contentItem.frames;
mc.boundsRect = new PIXI.Rectangle(0, 0, this.$contentSourceWidth, this.$contentSourceHeight);
this.updateLayout();
}
else
this.setErrorState();
}
else
this.setErrorState();
}
private switchToMovieMode(value: boolean): void {
this.$container.removeChildren();
if (value) {
if (!(this.$content instanceof MovieClip))
this.$content = new MovieClip(this);
}
else {
if (!(this.$content instanceof UIImage))
this.$content = new UIImage(null);
}
this.$container.addChild(this.$content);
}
private $loadingTexture:PIXI.Texture = null;
/**overwrite this method if you need to load resources by your own way*/
protected loadExternal(): void {
let texture = PIXI.Texture.fromImage(this.$url, true);
this.$loadingTexture = texture;
//TODO: Texture does not have error event... monitor error event on baseTexture will casue cross-error-event problem.
texture.once("update", () => {
if (!texture.width || !texture.height)
this.$loadResCompleted(null);
else
this.$loadResCompleted(texture);
});
}
/**free the resource you loaded */
protected freeExternal(texture: PIXI.Texture): void {
PIXI.Texture.removeFromCache(texture);
texture.destroy(texture.baseTexture != null);
}
private $loadResCompleted(res: PIXI.Texture): void {
if (res)
this.onExternalLoadSuccess(res);
else {
this.onExternalLoadFailed();
this.$loadingTexture.removeAllListeners();
this.freeExternal(this.$loadingTexture);
this.$loadingTexture = null;
}
this.$loadingTexture = null;
}
/**content loaded */
protected onExternalLoadSuccess(texture: PIXI.Texture): void {
this.$container.removeChildren();
if (!this.$content || !(this.$content instanceof UIImage)) {
this.$content = new UIImage(null);
this.$content.$initDisp();
this.$container.addChild(this.$content);
}
else
this.$container.addChild(this.$content);
//baseTexture loaded, so update frame info
texture.frame = new PIXI.Rectangle(0, 0, texture.baseTexture.width, texture.baseTexture.height);
this.$content.texture = texture;
this.$contentSourceWidth = texture.width;
this.$contentSourceHeight = texture.height;
this.updateLayout();
}
protected onExternalLoadFailed(): void {
this.setErrorState();
}
private setErrorState(): void {
if (!this.$showErrorSign)
return;
if (this.$errorSign == null) {
if (UIConfig.loaderErrorSign) {
this.$errorSign = GLoader.$errorSignPool.get(UIConfig.loaderErrorSign);
}
}
if (this.$errorSign) {
this.$errorSign.width = this.width;
this.$errorSign.height = this.height;
this.$container.addChild(this.$errorSign.displayObject);
}
}
private clearErrorState(): void {
if (this.$errorSign) {
this.$container.removeChild(this.$errorSign.displayObject);
GLoader.$errorSignPool.recycle(this.$errorSign.resourceURL, this.$errorSign);
this.$errorSign = null;
}
}
private updateLayout(): void {
if (this.$content == null) {
if (this.$autoSize) {
this.$updatingLayout = true;
this.setSize(50, 30);
this.$updatingLayout = false;
}
return;
}
this.$content.position.set(0, 0);
this.$content.scale.set(1, 1);
this.$contentWidth = this.$contentSourceWidth;
this.$contentHeight = this.$contentSourceHeight;
if (this.$autoSize) {
this.$updatingLayout = true;
if (this.$contentWidth == 0)
this.$contentWidth = 50;
if (this.$contentHeight == 0)
this.$contentHeight = 30;
this.setSize(this.$contentWidth, this.$contentHeight);
this.$updatingLayout = false;
}
else {
let sx: number = 1, sy: number = 1;
if (this.$fill != LoaderFillType.None) {
sx = this.width / this.$contentSourceWidth;
sy = this.height / this.$contentSourceHeight;
if (sx != 1 || sy != 1) {
if (this.$fill == LoaderFillType.ScaleMatchHeight)
sx = sy;
else if (this.$fill == LoaderFillType.ScaleMatchWidth)
sy = sx;
else if (this.$fill == LoaderFillType.Scale) {
if (sx > sy)
sx = sy;
else
sy = sx;
}
else if (this.$fill == LoaderFillType.ScaleNoBorder) {
if (sx > sy)
sy = sx;
else
sx = sy;
}
this.$contentWidth = this.$contentSourceWidth * sx;
this.$contentHeight = this.$contentSourceHeight * sy;
}
}
if (this.$content instanceof UIImage) {
this.$content.width = this.$contentWidth;
this.$content.height = this.$contentHeight;
}
else
this.$content.scale.set(sx, sy);
if (this.$align == AlignType.Center)
this.$content.x = Math.floor((this.width - this.$contentWidth) / 2);
else if (this.$align == AlignType.Right)
this.$content.x = this.width - this.$contentWidth;
if (this.$verticalAlign == VertAlignType.Middle)
this.$content.y = Math.floor((this.height - this.$contentHeight) / 2);
else if (this.$verticalAlign == VertAlignType.Bottom)
this.$content.y = this.height - this.$contentHeight;
}
}
private clearContent(): void {
this.clearErrorState();
if (this.$content && this.$content.parent)
this.$container.removeChild(this.$content);
if(this.$loadingTexture) {
this.$loadingTexture.removeAllListeners();
this.freeExternal(this.$loadingTexture);
this.$loadingTexture = null;
}
if (this.$contentItem == null && this.$content instanceof UIImage)
this.freeExternal(this.$content.texture);
this.$content && this.$content.destroy();
this.$content = null;
this.$contentItem = null;
}
protected handleSizeChanged(): void {
if (!this.$updatingLayout)
this.updateLayout();
let rect: PIXI.Rectangle = this.$container.hitArea as PIXI.Rectangle; //TODO: hitArea can be Rectangle | Circle | Ellipse | Polygon | RoundedRectangle
rect.x = rect.y = 0;
rect.width = this.width;
rect.height = this.height;
}
public setupBeforeAdd(xml: utils.XmlNode): void {
super.setupBeforeAdd(xml);
let str: string;
str = xml.attributes.url;
if (str)
this.$url = str;
str = xml.attributes.align;
if (str)
this.$align = ParseAlignType(str);
str = xml.attributes.vAlign;
if (str)
this.$verticalAlign = ParseVertAlignType(str);
str = xml.attributes.fill;
if (str)
this.$fill = ParseLoaderFillType(str);
this.$autoSize = xml.attributes.autoSize == "true";
str = xml.attributes.errorSign;
if (str)
this.$showErrorSign = str == "true";
this.$playing = xml.attributes.playing != "false";
str = xml.attributes.color;
if (str)
this.color = utils.StringUtil.convertFromHtmlColor(str);
if (this.$url)
this.loadContent();
}
}
} | the_stack |
import {buildQueryString,join} from 'aurelia-path';
import {HttpClient,HttpClientConfiguration} from 'aurelia-fetch-client';
import {Container,resolver} from 'aurelia-dependency-injection';
/**
* Represents the options to use when constructing a `Rest` instance.
*/
export declare interface RestOptions {
/**
* `true` to use the traditional URI template standard (RFC6570) when building
* query strings from criteria objects, `false` otherwise. Default is `false`.
* NOTE: maps to `useTraditionalUriTemplates` parameter on `Rest` constructor.
*
* @type {boolean}
*/
useTraditionalUriTemplates?: boolean;
}
/**
* Rest class. A simple rest client to fetch resources
*/
export declare class Rest {
/**
* The defaults to apply to any request
*
* @param {{}} defaults The default fetch request options
*/
defaults: {};
/**
* The client for the rest adapter
*
* @param {HttpClient} client The fetch client
*
*/
client: HttpClient;
/**
* The name of the endpoint it was registered under
*
* @param {string} endpoint The endpoint name
*/
endpoint: string;
/**
* true to use the traditional URI template standard (RFC6570) when building
* query strings from criteria objects, false otherwise. Default is false.
*
* @param {boolean} useTraditionalUriTemplates The flag that enables RFC6570 URI templates.
*/
useTraditionalUriTemplates: boolean;
/**
* Inject the httpClient to use for requests.
*
* @param {HttpClient} httpClient The httpClient to use
* @param {string} endpoint The endpoint name
* @param {boolean} [useTraditionalUriTemplates] true to use the traditional URI
* template standard (RFC6570) when building
* query strings from criteria objects, false
* otherwise. Default is false.
*/
constructor(httpClient: HttpClient, endpoint: string, useTraditionalUriTemplates?: boolean);
/**
* Make a request to the server.
*
* @param {string} method The fetch method
* @param {string} path Path to the resource
* @param {{}} [body] The body to send if applicable
* @param {{}} [options] Fetch request options overwrites
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
request(method: string, path: string, body?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Find a resource.
*
* @param {string} resource Resource to find in
* @param {string|number|{}} idOrCriteria Object for where clause, string / number for id.
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
find(resource: string, idOrCriteria?: string | number | {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Find a resource.
*
* @param {string} resource Resource to find in
* @param {string|number} id String / number for id to be added to the path.
* @param {{}} [criteria] Object for where clause
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
findOne(resource: string, id: string | number, criteria?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Create a new instance for resource.
*
* @param {string} resource Resource to create
* @param {{}} [body] The data to post (as Object)
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
post(resource: string, body?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Update a resource.
*
* @param {string} resource Resource to update
* @param {string|number|{}} idOrCriteria Object for where clause, string / number for id.
* @param {{}} [body] New data for provided idOrCriteria.
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
update(resource: string, idOrCriteria?: string | number | {}, body?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Update a resource.
*
* @param {string} resource Resource to update
* @param {string|number} id String / number for id to be added to the path.
* @param {{}} [criteria] Object for where clause
* @param {{}} [body] New data for provided criteria.
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
updateOne(resource: string, id: string | number, criteria?: {}, body?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Patch a resource.
*
* @param {string} resource Resource to patch
* @param {string|number|{}} [idOrCriteria] Object for where clause, string / number for id.
* @param {{}} [body] Data to patch for provided idOrCriteria.
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
patch(resource: string, idOrCriteria?: string | number | {}, body?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Patch a resource.
*
* @param {string} resource Resource to patch
* @param {string|number} id String / number for id to be added to the path.
* @param {{}} [criteria] Object for where clause
* @param {{}} [body] Data to patch for provided criteria.
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
patchOne(resource: string, id: string | number, criteria?: {}, body?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Delete a resource.
*
* @param {string} resource The resource to delete
* @param {string|number|{}} [idOrCriteria] Object for where clause, string / number for id.
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
destroy(resource: string, idOrCriteria?: string | number | {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Delete a resource.
*
* @param {string} resource The resource to delete
* @param {string|number} id String / number for id to be added to the path.
* @param {{}} [criteria] Object for where clause
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>|Promise<Error>} Server response as Object
*/
destroyOne(resource: string, id: string | number, criteria?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
/**
* Create a new instance for resource.
*
* @param {string} resource The resource to create
* @param {{}} [body] The data to post (as Object)
* @param {{}} [options] Extra request options.
* @param {{ response: Response}} [responseOutput] reference output for Response object
*
* @return {Promise<*>} Server response as Object
*/
create(resource: string, body?: {}, options?: {}, responseOutput?: { response: Response }): Promise<any | Error>;
}
/**
* Config class. Configures and stores endpoints
*/
/**
* Config class. Configures and stores endpoints
*/
export declare class Config {
/**
* Collection of configures endpoints
*
* @param {{}} Key: endpoint name; value: Rest client
*/
endpoints: { [key: string]: Rest };
/**
* Current default endpoint if set
*
* @param {Rest} defaultEndpoint The Rest client
*/
defaultEndpoint: Rest;
/**
* Current default baseUrl if set
*
* @param {string} defaultBaseUrl The Rest client
*/
defaultBaseUrl: string;
/**
* Register a new endpoint.
*
* @param {string} name The name of the new endpoint.
* @param {Function|string} [configureMethod] Endpoint url or configure method for client.configure().
* @param {{}} [defaults] New defaults for the HttpClient
* @param {RestOptions} [restOptions] Options to pass when constructing the Rest instance.
*
* @see http://aurelia.io/docs.html#/aurelia/fetch-client/latest/doc/api/class/HttpClientConfiguration
* @return {Config} this Fluent interface
* @chainable
*/
registerEndpoint(name: string, configureMethod?: string | Function, defaults?: {}, restOptions?: RestOptions): Config;
/**
* Get a previously registered endpoint. Returns null when not found.
*
* @param {string} [name] The endpoint name. Returns default endpoint when not set.
*
* @return {Rest|null}
*/
getEndpoint(name?: string): Rest;
/**
* Check if an endpoint has been registered.
*
* @param {string} name The endpoint name
*
* @return {boolean}
*/
endpointExists(name: string): boolean;
/**
* Set a previously registered endpoint as the default.
*
* @param {string} name The endpoint name
*
* @return {Config} this Fluent interface
* @chainable
*/
setDefaultEndpoint(name: string): Config;
/**
* Set a base url for all endpoints
*
* @param {string} baseUrl The url for endpoints to append
*
* @return {Config} this Fluent interface
* @chainable
*/
setDefaultBaseUrl(baseUrl: string): Config;
/**
* Configure with an object
*
* @param {{}} config The configuration object
*
* @return {Config} this Fluent interface
* @chainable
*/
configure(config: { defaultEndpoint: string, defaultBaseUrl: string, endpoints: Array<{ name: string, endpoint: string, config: {}, default: boolean }> }): Config;
}
/**
* Plugin configure
*
* @export
* @param {{ container: Container}} frameworkConfig
* @param {({defaultEndpoint: string, defaultBaseUrl: string, endpoints: Array<{name: string, endpoint: string, config: RequestInit, default: boolean}>} | function(config: Config): void)} configOrConfigure
*/
export declare function configure(frameworkConfig: { container: Container }, configOrConfigure: { defaultEndpoint: string, defaultBaseUrl: string, endpoints: Array<{ name: string, endpoint: string, config: RequestInit, default: boolean }> } | ((config: Config) => void)): any;
/**
* Endpoint class. A resolver for endpoints which allows injection of the corresponding Rest client into a class
*/
export declare class Endpoint {
/**
* Construct the resolver with the specified key.
*
* @param {string} key
*/
constructor(key: string);
/**
* Resolve for key.
*
* @param {Container} container
*
* @return {Rest}
*/
get(container: Container): Rest;
/**
* Get a new resolver for `key`.
*
* @param {string} [key] The endpoint name
*
* @return {Endpoint} Resolves to the Rest client for this endpoint
*/
static of(key?: string): Rest;
} | the_stack |
import type {
ComponentType,
ForwardRefExoticComponent,
RefAttributes,
ElementRef,
ComponentPropsWithoutRef,
Ref
} from 'react';
import Feature, { FeatureClass } from './Feature';
// LOOKUP TYPES
/**
* A lookup type to extract the instance from a {@link FeatureClass}.
*
* @typeparam F - The type of the feature class to infer from.
*
* @example
*
* ```ts
* type ForceElementInstanceType = ExtractFeatureFromClass<typeof ForceElementSizeFeature>;
* ```
*
* @public
*/
export type ExtractFeatureFromClass<F> = F extends FeatureClass<
infer O,
infer S,
infer W
>
? Feature<O, S, W>
: never;
/**
* A lookup type to get the shell component from `WebView` and feature classes.
*
* @example
*
* ```ts
* type MyShellComponent = ExtractWebshellFromFeatClass<
* typeof WebView,
* [typeof HandleElementCSSBoxFeature]
* >;
* ```
*
* @typeparam C - The type of the `WebView` component.
* @typeparam F - The type for a collection of features classes.
*
* @public
*/
export type ExtractWebshellFromFeatClass<
C extends ComponentType<any>,
F extends FeatureClass<any, any, any>[]
> = WebshellComponent<C, ExtractFeatureFromClass<F[number]>[]>;
/**
* A lookup type to extract Web Handler specs from {@link WebHandlerDefinition}.
*
* @typeparam W - The type for the webhandler definition to which specs should be built.
*
* @public
*/
export type ExtractWebHandlerSpecFromDef<W> = W extends WebHandlerDefinition<
infer I,
infer P
>
? {
[k in I]: WebHandlerDefinition<I, P>;
}
: never;
/**
* A lookup type to extract props from {@link PropsSpecs}.
*
* @typeparam S - The type for the specs to which props should be extracted.
*
* @public
*/
export type ExtractPropsFromSpecs<S> = S extends PropsSpecs<infer N, any>
? S[N] extends never
? {}
: Required<S[N]>['signature']
: never;
/**
* A lookup type to extract Web handler specs from {@link Feature}.
*
* @typeparam F - The type of the feature from which handler specs should be extracted.
*
* @public
*/
export type ExtractWebHandlerSpecsFromFeature<F> = F extends Feature<
any,
any,
infer P
>
? P
: never;
/**
* A lookup type to infer the additional props from a feature.
*
* @typeparam F - The type of the feature from which prop specs should be extracted.
*
* @public
*/
export type ExtractPropsFromFeature<F> = F extends Feature<any, infer P, any>
? ExtractPropsFromSpecs<P>
: {};
// CONCRETE TYPES
/**
* A shell component type derived from its features.
*
* @typeparam C - A type of the `WebView` component.
* @typeparam F - A type for a collection of features to inject.
*
* @public
*/
export type WebshellComponent<
C extends ComponentType<any>,
F extends Feature<any, any, any>[]
> = ForwardRefExoticComponent<
WebshellProps<ComponentPropsWithoutRef<C>, F> & RefAttributes<ElementRef<C>>
>;
/**
* A minimal set of attributes to define a feature.
*
* @typeparam O - A type describing the shape of the JSON-serializable object that will be passed to the Web script.
*
* @public
*/
export type FeatureDefinition<O extends {}> = {
/**
* The string containing valid ECMAScript 5 to be run in the WebView.
*
* @remarks
* The script must define a single function which only argument is of the
* type {@link WebjsContext}.
*
* It is recommended that you use eslint to validate this script syntax, and
* event better, unit-test the script. See our repository home page for more
* information.
*/
readonly script: string;
/**
* A unique identifier of the feature. The convention is to use a reverse
* namespace domain ending with the feature name.
*
* @example
* org.formidable-webview/webshell.link-press
*/
readonly identifier: string;
/**
* These options will be shallow-merged with the options provided to the {@link FeatureClass}.
*/
readonly defaultOptions: Required<O>;
};
/**
* An object to define an API to send messages from shell to Web.
*
* @typeparam I - A type for the event identifier.
* @typeparam P - A type describing the shape of payloads sent to Web handlers.
*
* @public
*/
export interface WebHandlerDefinition<I extends string, P> {
eventId: I;
payload?: P;
async: false;
}
/**
* An object describing the structure of messages a feature Web script can handle.
*
* @typeparam I - A type for the event identifier.
* @typeparam P - A type describing the shape of payloads sent to Web handlers.
*
* @public
*/
export type WebHandlersSpecs<I extends string = string, P = {}> = {
[k in I]: WebHandlerDefinition<I, P>;
};
/**
* An object to define an API to send messages from Web to shell.
*
* @typeparam N - A type to define the name of the prop.
* @typeparam P - A type describing the shape of the prop.
*
* @public
*/
export type PropDefinition<N extends string, P> = {
eventId: string;
type: 'handler' | 'inert';
featureIdentifier: string;
name: N;
signature?: Partial<Record<N, P>>;
};
/**
*
* @typeparam N - A type to define the names of the props.
* @typeparam P - A type describing the shapes of the props.
*
* @public
*/
export type PropsSpecs<N extends string, P> = {
[k in N]: PropDefinition<k, P>;
};
/**
* An object to send messages from the shell to the Web.
* See {@link WebjsContext.onShellMessage}, {@link WebshellInvariantProps.webHandleRef} and {@link FeatureBuilder.withWebHandler}.
*
* @public
*/
export interface WebHandle {
/**
* Send a message to a Web handler, e.g. a callback registered in the Web script associated with a feature.
*
* @remarks
*
* Web handlers must have been declared with {@link FeatureBuilder.withWebHandler}.
*
*
* @param feat - The feature to which a message should be sent.
* @param eventId - A unique identifier for the event sent to the Web script.
* @param payload - The type of the message to sent.
*/
postMessageToWeb<
F extends Feature<any, any, any>,
H extends keyof ExtractWebHandlerSpecsFromFeature<F>
>(
feat: F,
eventId: H,
payload: Required<ExtractWebHandlerSpecsFromFeature<F>[H]>['payload']
): void;
}
/**
* Props all shell components will support.
*
* @public
*/
export interface WebshellInvariantProps {
/**
* Triggered when a feature script throws.
*/
onWebFeatureError?: (featureIdentifier: string, error: string) => void;
/**
* Report Web error messages from features in the console.
*
* @defaultvalue `__DEV__` (`true` in development, `false` otherwise)
*/
webshellDebug?: boolean;
/**
* If this prop is `true` and `webshellDebug` is `true`, errors will be
* thrown when inconsistencies are identified.
*
* @defaultvalue false
*/
webshellStrictMode?: boolean;
/**
* Pass a reference to send messages to the Web environment.
*/
webHandleRef?: Ref<WebHandle>;
}
/**
* Props of the Webshell produced by {@link makeWebshell}.
*
* @typeparam W - The type for the Props of the `WebView` component.
* @typeparam F - The type for a collection of features classes.
*
* @public
*/
export type WebshellProps<
W extends MinimalWebViewProps,
F extends Feature<any, any, any>[]
> = WebshellInvariantProps &
W &
(F[number] extends never ? {} : ExtractPropsFromFeature<F[number]>);
/**
* A high-compatibility type expressing minimal requirements for the
* WebView Component's props.
*
* @public
*/
export interface MinimalWebViewProps {
readonly onMessage?: unknown;
readonly onError?: unknown;
readonly injectedJavaScript?: unknown;
readonly javaScriptEnabled?: unknown;
readonly source?: Record<string, any>;
readonly style?: unknown;
readonly onNavigationStateChange?: unknown;
readonly scalesPageToFit?: unknown;
readonly showsVerticalScrollIndicator?: unknown;
readonly disableScrollViewPanResponder?: unknown;
readonly contentMode?: unknown;
}
// Web TYPES
/**
* A collection of utilities to manipulate the DOM.
*
* @public
*/
export interface DOMUtils {
/**
* Get one element in the DOM from a request. See {@link DOMElementRequest}.
*
* @returns An {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement | HTMLElement} or `null`.
*/
getDOMSelection(selector: DOMElementRequest): HTMLElement | null;
/**
* Get a collection of live elements in the DOM from a query request.
*
* @param selector - Which elements should be returned?
* @returns A live {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection | HTMLCollection}.
*/
getDOMSelectionAll(selector: DOMElementQueryRequest | string): any;
/**
* Get a collection of static elements in the DOM from a class or tag-name request.
*
* @param selector - Which elements should be returned?
* @returns A static {@link https://developer.mozilla.org/en-US/docs/Web/API/NodeList | NodeList}.
*/
getDOMSelectionAll(
selector: DOMElementClassNameRequest | DOMElementTagNameRequest
): any;
/**
* @param style - The style to parse, e.g. `'18px'`
*
* @returns Numeric value in CSS pixels.
*/
numericFromPxString(style: string): number;
}
/**
* This type specifies the shape of the object passed to Web features scripts.
*
* @typeparam O - A type describing the shape of the JSON-serializable object given by the shell.
*
* @public
*/
export interface WebjsContext<O extends {}> {
/**
* The options to customize the script behavior.
*/
readonly options: O;
/**
* Instruct the shell to send **the default event** associated with
* this feature, if any.
*
* @param payload - The value which will be passed to the handler.
* @typeparam P - A type describing the shape of the payload sent to shell.
*
*/
postMessageToShell<P>(payload: P): void;
/**
* Instruct the shell to call the handler associated with this
* feature and `eventId`, if any.
*
* @param eventId - A unique identifier for the event sent to the shell.
* You can omit this param if you are sending a `"default"` event identifier.
* @param payload - The value which will be passed to the handler.
* @typeparam P - A type describing the shape of the payload sent to shell.
*/
postMessageToShell<P>(eventId: string, payload: P): void;
/**
* Register a handler on messages sent from the shell.
*
* @param eventId - A unique identifier for the event received by the Web script.
* @param payload - The value which will be passed to the handler.
* @typeparam P - A type describing the shape of the payload sent by shell.
*/
onShellMessage<P>(eventId: string, handler: (payload: P) => void): void;
/**
* Create a function which execute a callback in a try-catch block that will
* grab errors en send them to the `Webshell` component.
*
* @param callback - The callback to try-catch.
*/
makeCallbackSafe<T extends Function>(callback: T): T;
/**
* Safely post a warn message to the console. The message will be routed to
* shell and printed in the React Native console during development.
*/
warn(message: string): void;
/**
* Safely post an info message to the console. The message will be routed to
* shell and printed in the React Native console during development.
*/
info(message: string): void;
/**
* A collection of utilities to manipulate the DOM.
*/
utils: DOMUtils;
}
/**
* @public
*/
export interface DOMRectSize {
width: number;
height: number;
}
/**
* See {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMRect | DOMRect}.
*
* @public
*/
export interface DOMRect extends DOMRectSize {
top: number;
left: number;
right: number;
bottom: number;
}
/**
* A request to select one element in the DOM.
*
* @remarks
* A string will be interpreted as a “query” request.
* See {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector | Document.querySelector() } and {@link DOMElementQueryRequest}.
*
* @public
*/
export type DOMElementRequest =
| DOMElementQueryRequest
| DOMElementClassNameRequest
| DOMElementIdRequest
| DOMElementTagNameRequest
| string;
/**
* A request to select a collection of elements in the DOM.
*
* @remarks
* A string will be interpreted as a “query” request.
* See {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll | Document.querySelectorAll() } and {@link DOMElementQueryRequest}.
*
* @public
*/
export type DOMCollectionRequest =
| DOMElementQueryRequest
| DOMElementClassNameRequest
| DOMElementTagNameRequest
| string;
/**
* A request by query string.
* See {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll | Document.querySelectorAll() }
* and {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector | Document.querySelector() }
*
* @public
*/
export type DOMElementQueryRequest = {
query: string;
};
/**
* A request by id (case-insensitive);
* See {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById | Document.getElementById() }
*
* @public
*/
export type DOMElementIdRequest = {
id: string;
};
/**
* A request by one or many case-sensitive class names, separated by spaces.
* See {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName | Document.getElementsByClassName() }
*
* @public
*/
export type DOMElementClassNameRequest = {
className: string;
};
/**
* A query by tag name.
* See {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName | Document.getElementsByTagName() }
*
* @remarks
* `'html'` will select `document.documentElement`.
*
* @public
*/
export type DOMElementTagNameRequest = {
tagName: string;
}; | the_stack |
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
import { NbDialogRef, NbDialogService } from '@nebular/theme';
import * as html2pdf from 'html2pdf.js';
import { ChartDialogComponent } from '../chart-dialog/chart-dialog.component';
import { UserAnalyticsPreferences } from '../preferences/UserAnalyticsPreferences';
import { UserAnalyticsQueryResult } from '../users/users';
import { UserFilter } from '../users/users.component';
import { ChartData, GraphInfo } from './ChartData';
@Component({
selector: 'tock-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnChanges {
@Input()
pdfId: string;
@Input()
type: string = 'line';
@Input()
title: string;
@Input()
filter: UserFilter
@Input()
data: UserAnalyticsQueryResult;
@Input()
isLoading = false;
@Input()
chartPreferences: UserAnalyticsPreferences;
@Input()
isFullScreen = false;
@Input()
isMultiChart = true;
@Input()
seriesSelectionList: number[] = [];
mainChart: ChartData;
altChart: ChartData;
isFlipped = false;
intentsList : string[] = []
chartOptions: any;
pieChartOptions: any;
@Output()
intentChanged: EventEmitter<UserFilter> = new EventEmitter();
constructor(private dialogService: NbDialogService) {
}
expand(){
this.dialogService.open(ChartDialogComponent, {
context: {
data: this.data,
title: this.title,
type: this.type,
userPreferences: this.chartPreferences,
isMultiChart: this.isMultiChart,
seriesSelectionList: this.seriesSelectionList
}
});
}
refresh(){
this.intentChanged.emit(this.filter);
}
ngOnChanges(changes: SimpleChanges) {
this.rebuild();
}
rebuild(): void {
if (this.data) {
if (this.data.dates.length == 1) {
this.mainChart = this.buildPieChart(this.data, this.type);
} else {
if (this.type == 'PieChart') {
this.mainChart = this.buildPieChartFromDates(this.data, this.type);
} else if (this.type == 'Calendar') {
this.mainChart = this.buildCalendarChart(this.data);
} else {
this.initSelectionList();
if (this.type == 'line') {
this.mainChart = this.buildChartByDate(this.data, this.type);
} else if (this.type == 'pie') {
this.mainChart = this.buildPieChartFromDates(this.data);
}
}
}
} else {
this.mainChart = null;
this.altChart = null;
this.intentsList = []
}
}
initSelectionList() {
if (this.seriesSelectionList.length == 0 && this.data.connectorsType.length > 5) {
this.seriesSelectionList = Array.from({length: 5}, (v, k) => k);
}
}
updateGraph() {
this.seriesSelectionList.sort((a, b) => a - b)
this.rebuild();
}
changeChartType(type: string) {
this.type = type;
this.rebuild();
}
displayMultipleSelectComponent(): boolean {
return this.data.connectorsType.length > 5 && this.type !== 'PieChart'
}
getDataFromSelection(data: string[]) {
let result = [];
if (this.seriesSelectionList.length > 0) {
this.seriesSelectionList.forEach((value, index) => {
result.push(data[value]);
})
return result;
} else {
return data;
}
}
getColumnsLength(series: string[]): number {
if (this.seriesSelectionList.length > 0) {
return this.seriesSelectionList.length;
} else {
return series.length;
}
}
buildCalendarChart(result: UserAnalyticsQueryResult) {
let dates = result.dates;
let that = this;
let data = result.usersData;
let rows = [];
const unique = (value, index, self) => {
return self.indexOf(value) === index
}
const years = dates.map(date=>(new Date(date)).getFullYear()).filter(unique);
dates.forEach(function (date, index) {
rows.push([new Date(date)].concat(that.getDataFromSelection(data[index]).reduce((x,y) => x + y)))
});
this.chartOptions = {
tooltip: {
position: 'top'
},
visualMap: {
min: 0,
calculable: true,
orient: 'horizontal',
left: 'center',
top: 'top',
color: ['#143db8', "#3366ff", '#f0f4ff'],
},
calendar:this.getCalendarList(years) ,
series: this.getSeriesList(years, rows)
};
return new ChartData('Calendar', rows, null, null, '500', '100%');
}
getCalendarList(years: any[]){
return years.map((year, index) => {
return {
cellSize: ['auto', 15],
top: index != 0 ? (190*(index-1)) + 260:90,
range: year,
itemStyle: {
borderWidth: 0.5
}
}
})
}
getSeriesList(years: any[], rows: any[]) {
return years.map((_, index) => {
return {
type: 'heatmap',
coordinateSystem: 'calendar',
calendarIndex: index,
data: rows
}
})
}
buildChartByDate(result: UserAnalyticsQueryResult, chartType?: string, width?: string) {
let dates = result.dates;
let series: any[] = result.connectorsType;
let that = this;
let data = result.usersData;
let rows = [];
dates.forEach(function (date, index) {
if(chartType === 'Calendar'){
rows.push([new Date(date)].concat(that.getDataFromSelection(data[index]).reduce((x,y) => x + y)))
} else {
rows.push([date].concat(that.getDataFromSelection(data[index])))
}
});
let seriesCounters = new Array(this.getColumnsLength(series)).fill(0);
let seriesNumber = that.getDataFromSelection(series).length;
const seriesValues = new Array(seriesNumber);
for (let index = 0; index < seriesNumber; index++) {
seriesValues[index] = new Array(data.length).fill(0);
}
that.getDataFromSelection(series).forEach(function (serie, serieIndex) {
let serieDataIndex = series.indexOf(serie);
data.forEach(function (d, index) {
let serieDateValue = d[serieDataIndex];
seriesValues[serieIndex][index] = serieDateValue;
seriesCounters[serieIndex] += serieDateValue;
})
})
let seriesLabels = this.getDataFromSelection(series).map((c, i) => c + "(" + seriesCounters[i] + ")")
let colors = series.map(serie => this.getColor(serie, series))
this.chartOptions = {
tooltip: {
trigger: this.getTooltipType(this.chartPreferences.lineConfig.focusTarget),
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
grid: {
left: '3%',
right: '5%'
},
legend: {
data: seriesLabels,
type: 'scroll',
orient: 'horizontal',
bottom: 0,
textStyle: {
color: '#8f9bb3',
}
},
color: colors,
xAxis: {
type: 'category',
data: dates
},
yAxis: {
type: 'value'
},
series: this.getSeriesData(seriesValues, seriesLabels, this.chartPreferences.lineConfig.curvedLines,
this.chartPreferences.lineConfig.stacked)
};
return new ChartData(chartType ? chartType : this.chartPreferences.lineConfig.stacked ? "AreaChart" : "LineChart",
rows, ['Date'].concat(seriesLabels), null, '500', width ? width : '100%');
}
getTooltipType(isItem){
if(isItem){
return 'item';
}
return 'axis';
}
getSeriesData(result, columns, smooth, area){
return result.slice(0, columns.length).map((element, index) => {
return {
name:columns[index],
data: element,
type: 'line',
smooth: smooth,
areaStyle: this.isAreaChart(area)
}
});
}
isAreaChart(area){
if(area) {
return {}
}
return null
}
buildPieChart(result: UserAnalyticsQueryResult, chartType?: string, width?: string) {
let series = result.connectorsType;
let rows = [];
this.intentsList = result.intents;
series.forEach(function (serie, index) {
let data = result.usersData;
rows.push(new GraphInfo(data[0][index], serie))
});
let colors = series.map(serie => this.getColor(serie, series))
this.chartOptions = {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)'
},
legend: {
type: 'scroll',
orient: 'horizontal',
bottom: 0,
textStyle: {
color: '#8f9bb3',
}
},
color: colors,
grid: {
left: '0%',
right: '0%',
top: '0%',
bottom: '0%'
},
series: [
{
type: 'pie',
center: ['50%', '50%'],
data: rows,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
}
return new ChartData(chartType ? chartType : 'PieChart', rows, series, null, '500', width ? width : '100%');
}
buildPieChartFromDates(result: UserAnalyticsQueryResult, chartType?: string, width?: string) {
let series: any[] = result.connectorsType;
let data = result.usersData;
let rows = [];
let that = this;
let serieCount = new Array(this.getColumnsLength(series)).fill(0);
data.forEach(function (data) {
that.getDataFromSelection(series).forEach(function (value, index,) {
serieCount[index] += that.getDataFromSelection(data)[index];
})
})
that.getDataFromSelection(series).forEach(function (serie, index) {
rows.push(new GraphInfo(serieCount[index], serie))
});
let colors = series.map(serie => this.getColor(serie, series))
this.chartOptions = {
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)'
},
legend: {
type: 'scroll',
orient: 'horizontal',
bottom: 0,
textStyle: {
color: '#8f9bb3',
}
},
color: colors,
series: [
{
type: 'pie',
data: rows,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
return new ChartData(chartType ? chartType : 'PieChart', rows, ['Date'].concat(series), undefined, '500', width ? width : '100%');
}
getColor(serie: string, series: string[]): string {
let colors = ["#0084ff", "#fabc05", "#3dc3ef", "#e01f5c", "#dc2727", "#1ca3f3", "#41c352", "#5d67cf", "#58e951",
"#878f9c", "#f3745d"];
let serieIndex = series.indexOf(serie);
let colorIndex = serieIndex % colors.length;
return colors[colorIndex];
}
chartIcon(): string {
return this.mainChart.type == 'PieChart' ? 'pie-chart-outline' : 'bar-chart-outline';
}
onFlipAction() {
this.isFlipped = !this.isFlipped;
}
onCsvAction() {
let columnsNumber = this.mainChart.data[0].length;
if(this.mainChart.type == 'PieChart'){
columnsNumber = this.mainChart.data.length;
}
let csv = '';
if (this.mainChart.columnNames) {
this.mainChart.columnNames.forEach(function (column, index) {
csv += column;
if (index + 1 < columnsNumber) {
csv += ',';
}
})
csv += '\n';
}
if(this.mainChart.type == 'PieChart'){
this.mainChart.data.forEach(function (data, index) {
csv += (data as unknown as GraphInfo).value;
if (index + 1 < columnsNumber) {
csv += ',';
}
})
csv += '\n';
} else {
this.mainChart.data.forEach(function (row) {
row.forEach(function (value, index) {
csv += value;
if (index + 1 < columnsNumber) {
csv += ',';
}
})
csv += '\n';
})
}
const blob = new Blob([csv], {type: 'text/csv'});
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = this.getFileName('csv');
a.click();
}
getFileName(exportType: string): string {
return `tock-${exportType}export-` + this.title + `.${exportType}`;
}
onPdfAction() {
const options = {
margin: 0,
filename: this.getFileName('pdf'),
image: {type: 'jpeg ', quality: 0.95},
html2canvas: {scale: 1},
jsPDF: {orientation: 'landscape',
format: 'a2',
compress: true},
pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
};
let element = document.getElementById(this.pdfId)
html2pdf()
.from(element)
.set(options)
.save()
}
} | the_stack |
* Created by tijmen on 01-02-16.
*/
namespace ergometer.ble {
export function hasWebBlueTooth() : boolean {
return ( navigator && typeof navigator.bluetooth !== 'undefined' );
}
interface ListenerMap {
[name : string] : (data:ArrayBuffer)=>void;
}
interface ListenerCharacteristicMap {
[name : string] : webbluetooth.BluetoothRemoteGATTCharacteristic;
}
export class DriverWebBlueTooth implements IDriver {
private _device: webbluetooth.BluetoothDevice;
private _server : webbluetooth.BluetoothRemoteGATTServer;
private _disconnectFn : ()=>void;
private _listenerMap : ListenerMap= {};
//needed to prevent early free of the characteristic
private _listerCharacteristicMap : ListenerCharacteristicMap= {};
//should queue the read and writes, this may be the cause of the blocking issues, this is a work arround for the chrome web blue tooth problem
//private _functionQueue : utils.FunctionQueue = new utils.FunctionQueue(1); //1 means one at a time
constructor (private _performanceMonitor : MonitorBase,
private _scanServices : string[],
private _scanOptionalServices : string[]) {
}
//simple wrapper for bleat characteristic functions
private getCharacteristic(serviceUid : string,characteristicUid : string) : Promise<webbluetooth.BluetoothRemoteGATTCharacteristic> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`getCharacteristic ${characteristicUid} `);
return new Promise<webbluetooth.BluetoothRemoteGATTCharacteristic>((resolve, reject) => {
if (!this._server || !this._server.connected)
reject("server not connected")
else
this._server.getPrimaryService(serviceUid)
.then((service: webbluetooth.BluetoothRemoteGATTService ) => {
return service.getCharacteristic(characteristicUid)
})
.then(resolve,reject);
});
}
private onDisconnected(event :Event) {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`onDisconnected `);
if (this._disconnectFn)
this._disconnectFn();
this.clearConnectionVars();
}
private clearConnectionVars() {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`clearConnectionVars `);
if (this._device)
this._device.removeEventListener('ongattserverdisconnected',this.onDisconnected);
this._device=null;
this._server=null;
this._disconnectFn=null;
this._listenerMap={};
this._listerCharacteristicMap={};
}
public connect(device : IDevice,disconnectFn : ()=>void) : Promise<void> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`connect `);
return new Promise<void>((resolve, reject) => {
try {
var newDevice = device._internalDevice;
newDevice.addEventListener('gattserverdisconnected', this.onDisconnected.bind(this));
newDevice.ongattserverdisconnected=this.onDisconnected.bind(this) ;
newDevice.gatt.connect().then((server : webbluetooth.BluetoothRemoteGATTServer)=>{
this._device=newDevice;
this._server=server;
this._disconnectFn=disconnectFn;
resolve();
},reject);
}
catch (e) {
reject(e);
}
})
}
public disconnect() {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`disconnect `);
if (this._server && this._server.connected) this._server.disconnect();
else this.clearConnectionVars();
}
public startScan( foundFn? : IFoundFunc ) : Promise<void> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`startScan `);
return new Promise<void>((resolve, reject) => {
try {
navigator.bluetooth.requestDevice(
{
filters: [
{ services: this._scanServices
}
],
optionalServices: this._scanOptionalServices
}).then(device => {
foundFn({
address: device.id,
name: device.name,
rssi: ( ( typeof device.adData !== 'undefined' ) && device.adData.rssi)?device.adData.rssi:0,
_internalDevice: device
});
}).then(resolve,reject);
}
catch (e) {
reject(e);
}
});
}
public stopScan() : Promise<void> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`stopScan `);
if ( typeof navigator.bluetooth.cancelRequest !== 'undefined' )
return navigator.bluetooth.cancelRequest()
else return new Promise<void>((resolve, reject) => {
resolve();
}
);
}
/*
public writeCharacteristic(serviceUIID : string,characteristicUUID:string, data:ArrayBufferView) : Promise<void> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`writeCharacteristic ${characteristicUUID} : ${data} `);
//run read and write one at a time , wait for the result and then call the next
//this is a workaround for a problem of web blue tooth
//not yet tested!
return this._functionQueue.add(
this.doWriteCharacteristic,
this,serviceUIID,characteristicUUID,data);
}
*/
public writeCharacteristic(serviceUIID : string,characteristicUUID:string, data:ArrayBufferView) : Promise<void> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`writeCharacteristic ${characteristicUUID} : ${data} `);
if (!this._device || !this._device.gatt || !this._device.gatt.connected) {
this.onDisconnected(null);
return Promise.reject("Not connected");
}
return new Promise<void>((resolve, reject) => {
try {
this.getCharacteristic(serviceUIID,characteristicUUID)
.then(( characteristic : webbluetooth.BluetoothRemoteGATTCharacteristic) => {
return characteristic.writeValue(data.buffer)
})
.then(resolve)
.catch(e=>{
reject(e);
//when an write gives an error asume that we are disconnected
if (!this._device.gatt.connected)
this.onDisconnected(null);
});
}
catch (e) {
reject(e);
}
})
}
/*
public readCharacteristic(serviceUIID : string,characteristicUUID:string) : Promise<ArrayBuffer> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`readCharacteristic ${characteristicUUID} `);
//run read and write one at a time , wait for the result and then call the next
//this is a workaround for a problem of web blue tooth
//not yet tested!
return this._functionQueue.add(
this.doReadCharacteristic,
this,serviceUIID,characteristicUUID);
}
*/
public readCharacteristic(serviceUIID : string,characteristicUUID:string) : Promise<ArrayBuffer> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`readCharacteristic ${characteristicUUID} `);
if (!this._device || !this._device.gatt || !this._device.gatt.connected) {
this.onDisconnected(null);
return Promise.reject("Not connected");
}
return new Promise<ArrayBuffer>((resolve, reject) => {
try {
this.getCharacteristic(serviceUIID,characteristicUUID)
.then(( characteristic : webbluetooth.BluetoothRemoteGATTCharacteristic) => {
return characteristic.readValue()
})
.then((data : DataView)=>{
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`doReadCharacteristic ${characteristicUUID} : ${utils.typedArrayToHexString(data.buffer)} `);
resolve(data.buffer);
})
.catch(e=>{
reject(e);
//when an write gives an error asume that we are disconnected
if (!this._device.gatt.connected)
this.onDisconnected(null);
});;
}
catch (e) {
reject(e);
}
})
}
private onCharacteristicValueChanged(event:webbluetooth.CharacteristicsValueChangedEvent) {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`onCharacteristicValueChanged ${event.target.uuid} : ${utils.typedArrayToHexString(event.target.value.buffer)} `);
try {
if (!this._device.gatt.connected) {
this.onDisconnected(null);
throw "Not connected";
}
let func=this._listenerMap[event.target.uuid];
if (func) func(event.target.value.buffer)
}
catch(e) {
if (this._performanceMonitor)
this._performanceMonitor.handleError(e.toString());
else throw e;
}
}
/*private onCharacteristicValueChanged(uuid,buffer) : Promise<void> {
return new Promise<void>((resolve, reject) => {
try {
let func=this._listerMap[uuid];
if (func) {
func(buffer);
resolve();
}
else throw "characteristics uuid "+uuid.toString()+" not found in map";
}
catch(e) {
if (this._performanceMonitor)
this._performanceMonitor.handleError(e.toString());
reject(e);
}
});
}
private onCharacteristicValueChanged(event:webbluetooth.CharacteristicsValueChangedEvent) {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`onCharacteristicValueChanged ${event.target.uuid} : ${utils.typedArrayToHexString(event.target.value.buffer)} `);
//this may prevent hanging, just a test
//process one at a time to prevent dead locks
this._functionQueue.add(
this.doOnCharacteristicValueChanged,this,event.target.uuid,event.target.value.buffer);
return true;
}
*/
public enableNotification(serviceUIID : string,characteristicUUID:string, receive:(data:ArrayBuffer) =>void) : Promise<void> {
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`enableNotification ${characteristicUUID} `);
if (!this._device.gatt.connected) {
this.onDisconnected(null);
return Promise.reject("Not connected");
}
return new Promise<void>((resolve, reject) => {
try {
this.getCharacteristic(serviceUIID,characteristicUUID)
.then(( characteristic : webbluetooth.BluetoothRemoteGATTCharacteristic) => {
return characteristic.startNotifications().then(_ => {
this._listenerMap[characteristicUUID]=receive;
//bug fix: this prevents the chracteristic from being free-ed
this._listerCharacteristicMap[characteristicUUID]=characteristic;
characteristic.addEventListener('characteristicvaluechanged',this.onCharacteristicValueChanged.bind(this));
resolve();
},reject)
}).then(resolve,reject);
}
catch (e) {
reject(e);
}
})
}
public disableNotification(serviceUIID : string,characteristicUUID:string) : Promise<void> {
//only disable when receive is
if (this._performanceMonitor.logLevel==LogLevel.trace)
this._performanceMonitor.traceInfo(`disableNotification ${characteristicUUID} `);
return new Promise<void>((resolve, reject) => {
try {
if (typeof this._listenerMap[characteristicUUID]!== 'undefined' && this._listenerMap[characteristicUUID]) {
this.getCharacteristic(serviceUIID, characteristicUUID)
.then((characteristic: webbluetooth.BluetoothRemoteGATTCharacteristic) => {
characteristic.stopNotifications().then(() => {
this._listenerMap[characteristic.uuid] = null;
this._listerCharacteristicMap[characteristic.uuid] = null;
characteristic.removeEventListener('characteristicvaluechanged', this.onCharacteristicValueChanged);
resolve();
}, reject);
});
}
else resolve();//just resolve nothing to do
}
catch (e) {
reject(e);
}
})
}
}
} | the_stack |
namespace ts.tscWatch {
import projectsLocation = TestFSWithWatch.tsbuildProjectsLocation;
describe("unittests:: tsbuildWatch:: watchMode:: program updates", () => {
type TsBuildWatchSystem = TestFSWithWatch.TestServerHostTrackingWrittenFiles;
function createTsBuildWatchSystem(fileOrFolderList: readonly TestFSWithWatch.FileOrFolderOrSymLink[], params?: TestFSWithWatch.TestServerHostCreationParameters) {
return TestFSWithWatch.changeToHostTrackingWrittenFiles(
createWatchedSystem(fileOrFolderList, params)
);
}
type OutputFileStamp = [string, Date | undefined, boolean];
function transformOutputToOutputFileStamp(f: string, host: TsBuildWatchSystem): OutputFileStamp {
return [f, host.getModifiedTime(f), host.writtenFiles.has(host.toFullPath(f))] as OutputFileStamp;
}
const scenario = "programUpdates";
const project = "sample1";
const enum SubProject {
core = "core",
logic = "logic",
tests = "tests",
ui = "ui"
}
type ReadonlyFile = Readonly<File>;
/** [tsconfig, index] | [tsconfig, index, anotherModule, someDecl] */
type SubProjectFiles = [ReadonlyFile, ReadonlyFile] | [ReadonlyFile, ReadonlyFile, ReadonlyFile, ReadonlyFile];
function projectPath(subProject: SubProject) {
return TestFSWithWatch.getTsBuildProjectFilePath(project, subProject);
}
function projectFilePath(subProject: SubProject, baseFileName: string) {
return `${projectPath(subProject)}/${baseFileName.toLowerCase()}`;
}
function projectFile(subProject: SubProject, baseFileName: string): File {
return TestFSWithWatch.getTsBuildProjectFile(project, `${subProject}/${baseFileName}`);
}
function subProjectFiles(subProject: SubProject, anotherModuleAndSomeDecl?: true): SubProjectFiles {
const tsconfig = projectFile(subProject, "tsconfig.json");
const index = projectFile(subProject, "index.ts");
if (!anotherModuleAndSomeDecl) {
return [tsconfig, index];
}
const anotherModule = projectFile(SubProject.core, "anotherModule.ts");
const someDecl = projectFile(SubProject.core, "some_decl.ts");
return [tsconfig, index, anotherModule, someDecl];
}
function getOutputFileNames(subProject: SubProject, baseFileNameWithoutExtension: string) {
const file = projectFilePath(subProject, baseFileNameWithoutExtension);
return [`${file}.js`, `${file}.d.ts`];
}
function getOutputStamps(host: TsBuildWatchSystem, subProject: SubProject, baseFileNameWithoutExtension: string): OutputFileStamp[] {
return getOutputFileNames(subProject, baseFileNameWithoutExtension).map(f => transformOutputToOutputFileStamp(f, host));
}
function getOutputFileStamps(host: TsBuildWatchSystem, additionalFiles?: readonly [SubProject, string][]): OutputFileStamp[] {
const result = [
...getOutputStamps(host, SubProject.core, "anotherModule"),
...getOutputStamps(host, SubProject.core, "index"),
...getOutputStamps(host, SubProject.logic, "index"),
...getOutputStamps(host, SubProject.tests, "index"),
];
if (additionalFiles) {
additionalFiles.forEach(([subProject, baseFileNameWithoutExtension]) => result.push(...getOutputStamps(host, subProject, baseFileNameWithoutExtension)));
}
host.writtenFiles.clear();
return result;
}
function changeFile(fileName: string | (() => string), content: string | (() => string), caption: string): TscWatchCompileChange {
return {
caption,
change: sys => sys.writeFile(isString(fileName) ? fileName : fileName(), isString(content) ? content : content()),
timeouts: checkSingleTimeoutQueueLengthAndRun, // Builds core
};
}
function changeCore(content: () => string, caption: string) {
return changeFile(() => core[1].path, content, caption);
}
let core: SubProjectFiles;
let logic: SubProjectFiles;
let tests: SubProjectFiles;
let ui: SubProjectFiles;
let allFiles: readonly File[];
let testProjectExpectedWatchedFiles: string[];
let testProjectExpectedWatchedDirectoriesRecursive: string[];
before(() => {
core = subProjectFiles(SubProject.core, /*anotherModuleAndSomeDecl*/ true);
logic = subProjectFiles(SubProject.logic);
tests = subProjectFiles(SubProject.tests);
ui = subProjectFiles(SubProject.ui);
allFiles = [libFile, ...core, ...logic, ...tests, ...ui];
testProjectExpectedWatchedFiles = [core[0], core[1], core[2]!, ...logic, ...tests].map(f => f.path.toLowerCase());
testProjectExpectedWatchedDirectoriesRecursive = [projectPath(SubProject.core), projectPath(SubProject.logic)];
});
after(() => {
core = undefined!;
logic = undefined!;
tests = undefined!;
ui = undefined!;
allFiles = undefined!;
testProjectExpectedWatchedFiles = undefined!;
testProjectExpectedWatchedDirectoriesRecursive = undefined!;
});
verifyTscWatch({
scenario,
subScenario: "creates solution in watch mode",
commandLineArgs: ["-b", "-w", `${project}/${SubProject.tests}`],
sys: () => createWatchedSystem(allFiles, { currentDirectory: projectsLocation }),
changes: emptyArray
});
it("verify building references watches only those projects", () => {
const system = createTsBuildWatchSystem(allFiles, { currentDirectory: projectsLocation });
const host = createSolutionBuilderWithWatchHost(system);
const solutionBuilder = createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`], { watch: true });
solutionBuilder.buildReferences(`${project}/${SubProject.tests}`);
checkWatchedFiles(system, testProjectExpectedWatchedFiles.slice(0, testProjectExpectedWatchedFiles.length - tests.length));
checkWatchedDirectories(system, emptyArray, /*recursive*/ false);
checkWatchedDirectories(system, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true);
checkOutputErrorsInitial(system, emptyArray);
const testOutput = getOutputStamps(system, SubProject.tests, "index");
const outputFileStamps = getOutputFileStamps(system);
for (const stamp of outputFileStamps.slice(0, outputFileStamps.length - testOutput.length)) {
assert.isDefined(stamp[1], `${stamp[0]} expected to be present`);
}
for (const stamp of testOutput) {
assert.isUndefined(stamp[1], `${stamp[0]} expected to be missing`);
}
return system;
});
const buildTests: TscWatchCompileChange = {
caption: "Build Tests",
change: noop,
// Build tests
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout,
};
describe("validates the changes and watched files", () => {
const newFileWithoutExtension = "newFile";
const newFile: File = {
path: projectFilePath(SubProject.core, `${newFileWithoutExtension}.ts`),
content: `export const newFileConst = 30;`
};
function verifyProjectChanges(subScenario: string, allFilesGetter: () => readonly File[]) {
const buildLogicOrUpdateTimeStamps: TscWatchCompileChange = {
caption: "Build logic or update time stamps",
change: noop,
timeouts: checkSingleTimeoutQueueLengthAndRun, // Builds logic or updates timestamps
};
verifyTscWatch({
scenario,
subScenario: `${subScenario}/change builds changes and reports found errors message`,
commandLineArgs: ["-b", "-w", `${project}/${SubProject.tests}`],
sys: () => createWatchedSystem(
allFilesGetter(),
{ currentDirectory: projectsLocation }
),
changes: [
changeCore(() => `${core[1].content}
export class someClass { }`, "Make change to core"),
buildLogicOrUpdateTimeStamps,
buildTests,
// Another change requeues and builds it
changeCore(() => core[1].content, "Revert core file"),
buildLogicOrUpdateTimeStamps,
buildTests,
{
caption: "Make two changes",
change: sys => {
const change1 = `${core[1].content}
export class someClass { }`;
sys.writeFile(core[1].path, change1);
assert.equal(sys.writtenFiles.size, 1);
sys.writtenFiles.clear();
sys.writeFile(core[1].path, `${change1}
export class someClass2 { }`);
},
timeouts: checkSingleTimeoutQueueLengthAndRun, // Builds core
},
buildLogicOrUpdateTimeStamps,
buildTests,
]
});
verifyTscWatch({
scenario,
subScenario: `${subScenario}/non local change does not start build of referencing projects`,
commandLineArgs: ["-b", "-w", `${project}/${SubProject.tests}`],
sys: () => createWatchedSystem(
allFilesGetter(),
{ currentDirectory: projectsLocation }
),
changes: [
changeCore(() => `${core[1].content}
function foo() { }`, "Make local change to core"),
buildLogicOrUpdateTimeStamps,
buildTests
]
});
function changeNewFile(newFileContent: string) {
return changeFile(newFile.path, newFileContent, "Change to new File and build core");
}
verifyTscWatch({
scenario,
subScenario: `${subScenario}/builds when new file is added, and its subsequent updates`,
commandLineArgs: ["-b", "-w", `${project}/${SubProject.tests}`],
sys: () => createWatchedSystem(
allFilesGetter(),
{ currentDirectory: projectsLocation }
),
changes: [
changeNewFile(newFile.content),
buildLogicOrUpdateTimeStamps,
buildTests,
changeNewFile(`${newFile.content}
export class someClass2 { }`),
buildLogicOrUpdateTimeStamps,
buildTests
]
});
}
describe("with simple project reference graph", () => {
verifyProjectChanges(
"with simple project reference graph",
() => allFiles
);
});
describe("with circular project reference", () => {
verifyProjectChanges(
"with circular project reference",
() => {
const [coreTsconfig, ...otherCoreFiles] = core;
const circularCoreConfig: File = {
path: coreTsconfig.path,
content: JSON.stringify({
compilerOptions: { composite: true, declaration: true },
references: [{ path: "../tests", circular: true }]
})
};
return [libFile, circularCoreConfig, ...otherCoreFiles, ...logic, ...tests];
}
);
});
});
verifyTscWatch({
scenario,
subScenario: "watches config files that are not present",
commandLineArgs: ["-b", "-w", `${project}/${SubProject.tests}`],
sys: () => createWatchedSystem(
[libFile, ...core, logic[1], ...tests],
{ currentDirectory: projectsLocation }
),
changes: [
{
caption: "Write logic tsconfig and build logic",
change: sys => sys.writeFile(logic[0].path, logic[0].content),
timeouts: checkSingleTimeoutQueueLengthAndRun, // Builds logic
},
buildTests
]
});
describe("when referenced using prepend, builds referencing project even for non local change", () => {
let coreIndex: File;
before(() => {
coreIndex = {
path: core[1].path,
content: `function foo() { return 10; }`
};
});
after(() => {
coreIndex = undefined!;
});
const buildLogic: TscWatchCompileChange = {
caption: "Build logic",
change: noop,
// Builds logic
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout,
};
verifyTscWatch({
scenario,
subScenario: "when referenced using prepend builds referencing project even for non local change",
commandLineArgs: ["-b", "-w", `${project}/${SubProject.logic}`],
sys: () => {
const coreTsConfig: File = {
path: core[0].path,
content: JSON.stringify({
compilerOptions: { composite: true, declaration: true, outFile: "index.js" }
})
};
const logicTsConfig: File = {
path: logic[0].path,
content: JSON.stringify({
compilerOptions: { composite: true, declaration: true, outFile: "index.js" },
references: [{ path: "../core", prepend: true }]
})
};
const logicIndex: File = {
path: logic[1].path,
content: `function bar() { return foo() + 1 };`
};
return createWatchedSystem([libFile, coreTsConfig, coreIndex, logicTsConfig, logicIndex], { currentDirectory: projectsLocation });
},
changes: [
changeCore(() => `${coreIndex.content}
function myFunc() { return 10; }`, "Make non local change and build core"),
buildLogic,
changeCore(() => `${coreIndex.content}
function myFunc() { return 100; }`, "Make local change and build core"),
buildLogic,
]
});
});
describe("when referenced project change introduces error in the down stream project and then fixes it", () => {
const subProjectLibrary = `${projectsLocation}/${project}/Library`;
const libraryTs: File = {
path: `${subProjectLibrary}/library.ts`,
content: `
interface SomeObject
{
message: string;
}
export function createSomeObject(): SomeObject
{
return {
message: "new Object"
};
}`
};
verifyTscWatch({
scenario,
subScenario: "when referenced project change introduces error in the down stream project and then fixes it",
commandLineArgs: ["-b", "-w", "App"],
sys: () => {
const libraryTsconfig: File = {
path: `${subProjectLibrary}/tsconfig.json`,
content: JSON.stringify({ compilerOptions: { composite: true } })
};
const subProjectApp = `${projectsLocation}/${project}/App`;
const appTs: File = {
path: `${subProjectApp}/app.ts`,
content: `import { createSomeObject } from "../Library/library";
createSomeObject().message;`
};
const appTsconfig: File = {
path: `${subProjectApp}/tsconfig.json`,
content: JSON.stringify({ references: [{ path: "../Library" }] })
};
const files = [libFile, libraryTs, libraryTsconfig, appTs, appTsconfig];
return createWatchedSystem(files, { currentDirectory: `${projectsLocation}/${project}` });
},
changes: [
{
caption: "Introduce error",
// Change message in library to message2
change: sys => sys.writeFile(libraryTs.path, libraryTs.content.replace(/message/g, "message2")),
timeouts: sys => {
sys.checkTimeoutQueueLengthAndRun(1); // Build library
sys.checkTimeoutQueueLengthAndRun(1); // Build App
},
},
{
caption: "Fix error",
// Revert library changes
change: sys => sys.writeFile(libraryTs.path, libraryTs.content),
timeouts: sys => {
sys.checkTimeoutQueueLengthAndRun(1); // Build library
sys.checkTimeoutQueueLengthAndRun(1); // Build App
},
},
]
});
});
describe("reports errors in all projects on incremental compile", () => {
function verifyIncrementalErrors(subScenario: string, buildOptions: readonly string[]) {
verifyTscWatch({
scenario,
subScenario: `reportErrors/${subScenario}`,
commandLineArgs: ["-b", "-w", `${project}/${SubProject.tests}`, ...buildOptions],
sys: () => createWatchedSystem(allFiles, { currentDirectory: projectsLocation }),
changes: [
{
caption: "change logic",
change: sys => sys.writeFile(logic[1].path, `${logic[1].content}
let y: string = 10;`),
// Builds logic
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout,
},
{
caption: "change core",
change: sys => sys.writeFile(core[1].path, `${core[1].content}
let x: string = 10;`),
// Builds core
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout,
}
]
});
}
verifyIncrementalErrors("when preserveWatchOutput is not used", emptyArray);
verifyIncrementalErrors("when preserveWatchOutput is passed on command line", ["--preserveWatchOutput"]);
describe("when declaration emit errors are present", () => {
const solution = "solution";
const subProject = "app";
const subProjectLocation = `${projectsLocation}/${solution}/${subProject}`;
const fileWithError: File = {
path: `${subProjectLocation}/fileWithError.ts`,
content: `export var myClassWithError = class {
tags() { }
private p = 12
};`
};
const fileWithFixedError: File = {
path: fileWithError.path,
content: fileWithError.content.replace("private p = 12", "")
};
const fileWithoutError: File = {
path: `${subProjectLocation}/fileWithoutError.ts`,
content: `export class myClass { }`
};
const tsconfig: File = {
path: `${subProjectLocation}/tsconfig.json`,
content: JSON.stringify({ compilerOptions: { composite: true } })
};
function incrementalBuild(sys: WatchedSystem) {
sys.checkTimeoutQueueLengthAndRun(1); // Build the app
sys.checkTimeoutQueueLength(0);
}
const fixError: TscWatchCompileChange = {
caption: "Fix error in fileWithError",
// Fix error
change: sys => sys.writeFile(fileWithError.path, fileWithFixedError.content),
timeouts: incrementalBuild
};
const changeFileWithoutError: TscWatchCompileChange = {
caption: "Change fileWithoutError",
change: sys => sys.writeFile(fileWithoutError.path, fileWithoutError.content.replace(/myClass/g, "myClass2")),
timeouts: incrementalBuild
};
verifyTscWatch({
scenario,
subScenario: "reportErrors/declarationEmitErrors/when fixing error files all files are emitted",
commandLineArgs: ["-b", "-w", subProject],
sys: () => createWatchedSystem(
[libFile, fileWithError, fileWithoutError, tsconfig],
{ currentDirectory: `${projectsLocation}/${solution}` }
),
changes: [
fixError
]
});
verifyTscWatch({
scenario,
subScenario: "reportErrors/declarationEmitErrors/when file with no error changes",
commandLineArgs: ["-b", "-w", subProject],
sys: () => createWatchedSystem(
[libFile, fileWithError, fileWithoutError, tsconfig],
{ currentDirectory: `${projectsLocation}/${solution}` }
),
changes: [
changeFileWithoutError
]
});
describe("when reporting errors on introducing error", () => {
const introduceError: TscWatchCompileChange = {
caption: "Introduce error",
change: sys => sys.writeFile(fileWithError.path, fileWithError.content),
timeouts: incrementalBuild,
};
verifyTscWatch({
scenario,
subScenario: "reportErrors/declarationEmitErrors/introduceError/when fixing errors only changed file is emitted",
commandLineArgs: ["-b", "-w", subProject],
sys: () => createWatchedSystem(
[libFile, fileWithFixedError, fileWithoutError, tsconfig],
{ currentDirectory: `${projectsLocation}/${solution}` }
),
changes: [
introduceError,
fixError
]
});
verifyTscWatch({
scenario,
subScenario: "reportErrors/declarationEmitErrors/introduceError/when file with no error changes",
commandLineArgs: ["-b", "-w", subProject],
sys: () => createWatchedSystem(
[libFile, fileWithFixedError, fileWithoutError, tsconfig],
{ currentDirectory: `${projectsLocation}/${solution}` }
),
changes: [
introduceError,
changeFileWithoutError
]
});
});
});
});
verifyTscWatch({
scenario,
subScenario: "incremental updates in verbose mode",
commandLineArgs: ["-b", "-w", `${project}/${SubProject.tests}`, "-verbose"],
sys: () => createWatchedSystem(allFiles, { currentDirectory: projectsLocation }),
changes: [
{
caption: "Make non dts change",
change: sys => sys.writeFile(logic[1].path, `${logic[1].content}
function someFn() { }`),
timeouts: sys => {
sys.checkTimeoutQueueLengthAndRun(1); // build logic
sys.checkTimeoutQueueLengthAndRun(1); // build tests
},
},
{
caption: "Make dts change",
change: sys => sys.writeFile(logic[1].path, `${logic[1].content}
export function someFn() { }`),
timeouts: sys => {
sys.checkTimeoutQueueLengthAndRun(1); // build logic
sys.checkTimeoutQueueLengthAndRun(1); // build tests
},
}
],
});
verifyTscWatch({
scenario,
subScenario: "works when noUnusedParameters changes to false",
commandLineArgs: ["-b", "-w"],
sys: () => {
const index: File = {
path: `${projectRoot}/index.ts`,
content: `const fn = (a: string, b: string) => b;`
};
const configFile: File = {
path: `${projectRoot}/tsconfig.json`,
content: JSON.stringify({
compilerOptions: {
noUnusedParameters: true
}
})
};
return createWatchedSystem([index, configFile, libFile], { currentDirectory: projectRoot });
},
changes: [
{
caption: "Change tsconfig to set noUnusedParameters to false",
change: sys => sys.writeFile(`${projectRoot}/tsconfig.json`, JSON.stringify({
compilerOptions: {
noUnusedParameters: false
}
})),
timeouts: runQueuedTimeoutCallbacks,
},
]
});
verifyTscWatch({
scenario,
subScenario: "should not trigger recompilation because of program emit",
commandLineArgs: ["-b", "-w", `${project}/${SubProject.core}`, "-verbose"],
sys: () => createWatchedSystem([libFile, ...core], { currentDirectory: projectsLocation }),
changes: [
noopChange,
{
caption: "Add new file",
change: sys => sys.writeFile(`${project}/${SubProject.core}/file3.ts`, `export const y = 10;`),
timeouts: checkSingleTimeoutQueueLengthAndRun
},
noopChange,
]
});
verifyTscWatch({
scenario,
subScenario: "should not trigger recompilation because of program emit with outDir specified",
commandLineArgs: ["-b", "-w", `${project}/${SubProject.core}`, "-verbose"],
sys: () => {
const [coreConfig, ...rest] = core;
const newCoreConfig: File = { path: coreConfig.path, content: JSON.stringify({ compilerOptions: { composite: true, outDir: "outDir" } }) };
return createWatchedSystem([libFile, newCoreConfig, ...rest], { currentDirectory: projectsLocation });
},
changes: [
noopChange,
{
caption: "Add new file",
change: sys => sys.writeFile(`${project}/${SubProject.core}/file3.ts`, `export const y = 10;`),
timeouts: checkSingleTimeoutQueueLengthAndRun
},
noopChange
]
});
verifyTscWatch({
scenario,
subScenario: "works with extended source files",
commandLineArgs: ["-b", "-w", "-v", "project1.tsconfig.json", "project2.tsconfig.json"],
sys: () => {
const alphaExtendedConfigFile: File = {
path: "/a/b/alpha.tsconfig.json",
content: "{}"
};
const project1Config: File = {
path: "/a/b/project1.tsconfig.json",
content: JSON.stringify({
extends: "./alpha.tsconfig.json",
compilerOptions: {
composite: true,
},
files: [commonFile1.path, commonFile2.path]
})
};
const bravoExtendedConfigFile: File = {
path: "/a/b/bravo.tsconfig.json",
content: JSON.stringify({
extends: "./alpha.tsconfig.json"
})
};
const otherFile: File = {
path: "/a/b/other.ts",
content: "let z = 0;",
};
const project2Config: File = {
path: "/a/b/project2.tsconfig.json",
content: JSON.stringify({
extends: "./bravo.tsconfig.json",
compilerOptions: {
composite: true,
},
files: [otherFile.path]
})
};
return createWatchedSystem([
libFile,
alphaExtendedConfigFile, project1Config, commonFile1, commonFile2,
bravoExtendedConfigFile, project2Config, otherFile
], { currentDirectory: "/a/b" });
},
changes: [
{
caption: "Modify alpha config",
change: sys => sys.writeFile("/a/b/alpha.tsconfig.json", JSON.stringify({
compilerOptions: { strict: true }
})),
timeouts: checkSingleTimeoutQueueLengthAndRun // Build project1
},
{
caption: "Build project 2",
change: noop,
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout // Build project2
},
{
caption: "change bravo config",
change: sys => sys.writeFile("/a/b/bravo.tsconfig.json", JSON.stringify({
extends: "./alpha.tsconfig.json",
compilerOptions: { strict: false }
})),
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout // Build project2
},
{
caption: "project 2 extends alpha",
change: sys => sys.writeFile("/a/b/project2.tsconfig.json", JSON.stringify({
extends: "./alpha.tsconfig.json",
})),
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout // Build project2
},
{
caption: "update aplha config",
change: sys => sys.writeFile("/a/b/alpha.tsconfig.json", "{}"),
timeouts: checkSingleTimeoutQueueLengthAndRun, // build project1
},
{
caption: "Build project 2",
change: noop,
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout // Build project2
},
]
});
verifyTscWatch({
scenario,
subScenario: "works correctly when project with extended config is removed",
commandLineArgs: ["-b", "-w", "-v"],
sys: () => {
const alphaExtendedConfigFile: File = {
path: "/a/b/alpha.tsconfig.json",
content: JSON.stringify({
compilerOptions: {
strict: true
}
})
};
const project1Config: File = {
path: "/a/b/project1.tsconfig.json",
content: JSON.stringify({
extends: "./alpha.tsconfig.json",
compilerOptions: {
composite: true,
},
files: [commonFile1.path, commonFile2.path]
})
};
const bravoExtendedConfigFile: File = {
path: "/a/b/bravo.tsconfig.json",
content: JSON.stringify({
compilerOptions: {
strict: true
}
})
};
const otherFile: File = {
path: "/a/b/other.ts",
content: "let z = 0;",
};
const project2Config: File = {
path: "/a/b/project2.tsconfig.json",
content: JSON.stringify({
extends: "./bravo.tsconfig.json",
compilerOptions: {
composite: true,
},
files: [otherFile.path]
})
};
const configFile: File = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({
references: [
{
path: "./project1.tsconfig.json",
},
{
path: "./project2.tsconfig.json",
},
],
files: [],
})
};
return createWatchedSystem([
libFile, configFile,
alphaExtendedConfigFile, project1Config, commonFile1, commonFile2,
bravoExtendedConfigFile, project2Config, otherFile
], { currentDirectory: "/a/b" });
},
changes: [
{
caption: "Remove project2 from base config",
change: sys => sys.modifyFile("/a/b/tsconfig.json", JSON.stringify({
references: [
{
path: "./project1.tsconfig.json",
},
],
files: [],
})),
timeouts: checkSingleTimeoutQueueLengthAndRunAndVerifyNoTimeout,
}
]
});
});
} | the_stack |
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
PagingGetNoItemNamePagesOptionalParams,
PagingGetNoItemNamePagesResponse,
PagingGetNullNextLinkNamePagesOptionalParams,
PagingGetNullNextLinkNamePagesResponse,
PagingGetSinglePagesOptionalParams,
PagingGetSinglePagesResponse,
PagingFirstResponseEmptyOptionalParams,
PagingFirstResponseEmptyResponse,
PagingGetMultiplePagesOptionalParams,
PagingGetMultiplePagesResponse,
PagingGetWithQueryParamsOptionalParams,
PagingGetWithQueryParamsResponse,
PagingNextOperationWithQueryParamsOptionalParams,
PagingNextOperationWithQueryParamsResponse,
PagingGetOdataMultiplePagesOptionalParams,
PagingGetOdataMultiplePagesResponse,
PagingGetMultiplePagesWithOffsetOptions,
PagingGetMultiplePagesWithOffsetOptionalParams,
PagingGetMultiplePagesWithOffsetResponse,
PagingGetMultiplePagesRetryFirstOptionalParams,
PagingGetMultiplePagesRetryFirstResponse,
PagingGetMultiplePagesRetrySecondOptionalParams,
PagingGetMultiplePagesRetrySecondResponse,
PagingGetSinglePagesFailureOptionalParams,
PagingGetSinglePagesFailureResponse,
PagingGetMultiplePagesFailureOptionalParams,
PagingGetMultiplePagesFailureResponse,
PagingGetMultiplePagesFailureUriOptionalParams,
PagingGetMultiplePagesFailureUriResponse,
PagingGetMultiplePagesFragmentNextLinkOptionalParams,
PagingGetMultiplePagesFragmentNextLinkResponse,
CustomParameterGroup,
PagingGetMultiplePagesFragmentWithGroupingNextLinkOptionalParams,
PagingGetMultiplePagesFragmentWithGroupingNextLinkResponse,
PagingGetMultiplePagesLROOptionalParams,
PagingGetMultiplePagesLROResponse,
PagingNextFragmentOptionalParams,
PagingNextFragmentResponse,
PagingNextFragmentWithGroupingOptionalParams,
PagingNextFragmentWithGroupingResponse,
PagingGetPagingModelWithItemNameWithXMSClientNameOptionalParams,
PagingGetPagingModelWithItemNameWithXMSClientNameResponse,
PagingGetNoItemNamePagesNextOptionalParams,
PagingGetNoItemNamePagesNextResponse,
PagingGetSinglePagesNextOptionalParams,
PagingGetSinglePagesNextResponse,
PagingFirstResponseEmptyNextOptionalParams,
PagingFirstResponseEmptyNextResponse,
PagingGetMultiplePagesNextOptionalParams,
PagingGetMultiplePagesNextResponse,
PagingGetOdataMultiplePagesNextOptionalParams,
PagingGetOdataMultiplePagesNextResponse,
PagingGetMultiplePagesWithOffsetNextOptionalParams,
PagingGetMultiplePagesWithOffsetNextResponse,
PagingGetMultiplePagesRetryFirstNextOptionalParams,
PagingGetMultiplePagesRetryFirstNextResponse,
PagingGetMultiplePagesRetrySecondNextOptionalParams,
PagingGetMultiplePagesRetrySecondNextResponse,
PagingGetSinglePagesFailureNextOptionalParams,
PagingGetSinglePagesFailureNextResponse,
PagingGetMultiplePagesFailureNextOptionalParams,
PagingGetMultiplePagesFailureNextResponse,
PagingGetMultiplePagesFailureUriNextOptionalParams,
PagingGetMultiplePagesFailureUriNextResponse,
PagingGetMultiplePagesLRONextOptionalParams,
PagingGetMultiplePagesLRONextResponse,
PagingGetPagingModelWithItemNameWithXMSClientNameNextOptionalParams,
PagingGetPagingModelWithItemNameWithXMSClientNameNextResponse
} from "../models";
/** Interface representing a Paging. */
export interface Paging {
/**
* A paging operation that must return result of the default 'value' node.
* @param options The options parameters.
*/
getNoItemNamePages(
options?: PagingGetNoItemNamePagesOptionalParams
): Promise<PagingGetNoItemNamePagesResponse>;
/**
* A paging operation that must ignore any kind of nextLink, and stop after page 1.
* @param options The options parameters.
*/
getNullNextLinkNamePages(
options?: PagingGetNullNextLinkNamePagesOptionalParams
): Promise<PagingGetNullNextLinkNamePagesResponse>;
/**
* A paging operation that finishes on the first call without a nextlink
* @param options The options parameters.
*/
getSinglePages(
options?: PagingGetSinglePagesOptionalParams
): Promise<PagingGetSinglePagesResponse>;
/**
* A paging operation whose first response's items list is empty, but still returns a next link. Second
* (and final) call, will give you an items list of 1.
* @param options The options parameters.
*/
firstResponseEmpty(
options?: PagingFirstResponseEmptyOptionalParams
): Promise<PagingFirstResponseEmptyResponse>;
/**
* A paging operation that includes a nextLink that has 10 pages
* @param options The options parameters.
*/
getMultiplePages(
options?: PagingGetMultiplePagesOptionalParams
): Promise<PagingGetMultiplePagesResponse>;
/**
* A paging operation that includes a next operation. It has a different query parameter from it's next
* operation nextOperationWithQueryParams. Returns a ProductResult
* @param requiredQueryParameter A required integer query parameter. Put in value '100' to pass test.
* @param options The options parameters.
*/
getWithQueryParams(
requiredQueryParameter: number,
options?: PagingGetWithQueryParamsOptionalParams
): Promise<PagingGetWithQueryParamsResponse>;
/**
* Next operation for getWithQueryParams. Pass in next=True to pass test. Returns a ProductResult
* @param options The options parameters.
*/
nextOperationWithQueryParams(
options?: PagingNextOperationWithQueryParamsOptionalParams
): Promise<PagingNextOperationWithQueryParamsResponse>;
/**
* A paging operation that includes a nextLink in odata format that has 10 pages
* @param options The options parameters.
*/
getOdataMultiplePages(
options?: PagingGetOdataMultiplePagesOptionalParams
): Promise<PagingGetOdataMultiplePagesResponse>;
/**
* A paging operation that includes a nextLink that has 10 pages
* @param pagingGetMultiplePagesWithOffsetOptions Parameter group
* @param options The options parameters.
*/
getMultiplePagesWithOffset(
pagingGetMultiplePagesWithOffsetOptions: PagingGetMultiplePagesWithOffsetOptions,
options?: PagingGetMultiplePagesWithOffsetOptionalParams
): Promise<PagingGetMultiplePagesWithOffsetResponse>;
/**
* A paging operation that fails on the first call with 500 and then retries and then get a response
* including a nextLink that has 10 pages
* @param options The options parameters.
*/
getMultiplePagesRetryFirst(
options?: PagingGetMultiplePagesRetryFirstOptionalParams
): Promise<PagingGetMultiplePagesRetryFirstResponse>;
/**
* A paging operation that includes a nextLink that has 10 pages, of which the 2nd call fails first
* with 500. The client should retry and finish all 10 pages eventually.
* @param options The options parameters.
*/
getMultiplePagesRetrySecond(
options?: PagingGetMultiplePagesRetrySecondOptionalParams
): Promise<PagingGetMultiplePagesRetrySecondResponse>;
/**
* A paging operation that receives a 400 on the first call
* @param options The options parameters.
*/
getSinglePagesFailure(
options?: PagingGetSinglePagesFailureOptionalParams
): Promise<PagingGetSinglePagesFailureResponse>;
/**
* A paging operation that receives a 400 on the second call
* @param options The options parameters.
*/
getMultiplePagesFailure(
options?: PagingGetMultiplePagesFailureOptionalParams
): Promise<PagingGetMultiplePagesFailureResponse>;
/**
* A paging operation that receives an invalid nextLink
* @param options The options parameters.
*/
getMultiplePagesFailureUri(
options?: PagingGetMultiplePagesFailureUriOptionalParams
): Promise<PagingGetMultiplePagesFailureUriResponse>;
/**
* A paging operation that doesn't return a full URL, just a fragment
* @param apiVersion Sets the api version to use.
* @param tenant Sets the tenant to use.
* @param options The options parameters.
*/
getMultiplePagesFragmentNextLink(
apiVersion: string,
tenant: string,
options?: PagingGetMultiplePagesFragmentNextLinkOptionalParams
): Promise<PagingGetMultiplePagesFragmentNextLinkResponse>;
/**
* A paging operation that doesn't return a full URL, just a fragment with parameters grouped
* @param customParameterGroup Parameter group
* @param options The options parameters.
*/
getMultiplePagesFragmentWithGroupingNextLink(
customParameterGroup: CustomParameterGroup,
options?: PagingGetMultiplePagesFragmentWithGroupingNextLinkOptionalParams
): Promise<PagingGetMultiplePagesFragmentWithGroupingNextLinkResponse>;
/**
* A long-running paging operation that includes a nextLink that has 10 pages
* @param options The options parameters.
*/
getMultiplePagesLRO(
options?: PagingGetMultiplePagesLROOptionalParams
): Promise<
PollerLike<
PollOperationState<PagingGetMultiplePagesLROResponse>,
PagingGetMultiplePagesLROResponse
>
>;
/**
* A paging operation that doesn't return a full URL, just a fragment
* @param apiVersion Sets the api version to use.
* @param tenant Sets the tenant to use.
* @param nextLink Next link for list operation.
* @param options The options parameters.
*/
nextFragment(
apiVersion: string,
tenant: string,
nextLink: string,
options?: PagingNextFragmentOptionalParams
): Promise<PagingNextFragmentResponse>;
/**
* A paging operation that doesn't return a full URL, just a fragment
* @param nextLink Next link for list operation.
* @param customParameterGroup Parameter group
* @param options The options parameters.
*/
nextFragmentWithGrouping(
nextLink: string,
customParameterGroup: CustomParameterGroup,
options?: PagingNextFragmentWithGroupingOptionalParams
): Promise<PagingNextFragmentWithGroupingResponse>;
/**
* A paging operation that returns a paging model whose item name is is overriden by x-ms-client-name
* 'indexes'.
* @param options The options parameters.
*/
getPagingModelWithItemNameWithXMSClientName(
options?: PagingGetPagingModelWithItemNameWithXMSClientNameOptionalParams
): Promise<PagingGetPagingModelWithItemNameWithXMSClientNameResponse>;
/**
* GetNoItemNamePagesNext
* @param nextLink The nextLink from the previous successful call to the GetNoItemNamePages method.
* @param options The options parameters.
*/
getNoItemNamePagesNext(
nextLink: string,
options?: PagingGetNoItemNamePagesNextOptionalParams
): Promise<PagingGetNoItemNamePagesNextResponse>;
/**
* GetSinglePagesNext
* @param nextLink The nextLink from the previous successful call to the GetSinglePages method.
* @param options The options parameters.
*/
getSinglePagesNext(
nextLink: string,
options?: PagingGetSinglePagesNextOptionalParams
): Promise<PagingGetSinglePagesNextResponse>;
/**
* FirstResponseEmptyNext
* @param nextLink The nextLink from the previous successful call to the FirstResponseEmpty method.
* @param options The options parameters.
*/
firstResponseEmptyNext(
nextLink: string,
options?: PagingFirstResponseEmptyNextOptionalParams
): Promise<PagingFirstResponseEmptyNextResponse>;
/**
* GetMultiplePagesNext
* @param nextLink The nextLink from the previous successful call to the GetMultiplePages method.
* @param options The options parameters.
*/
getMultiplePagesNext(
nextLink: string,
options?: PagingGetMultiplePagesNextOptionalParams
): Promise<PagingGetMultiplePagesNextResponse>;
/**
* GetOdataMultiplePagesNext
* @param nextLink The nextLink from the previous successful call to the GetOdataMultiplePages method.
* @param options The options parameters.
*/
getOdataMultiplePagesNext(
nextLink: string,
options?: PagingGetOdataMultiplePagesNextOptionalParams
): Promise<PagingGetOdataMultiplePagesNextResponse>;
/**
* GetMultiplePagesWithOffsetNext
* @param pagingGetMultiplePagesWithOffsetOptions Parameter group
* @param nextLink The nextLink from the previous successful call to the GetMultiplePagesWithOffset
* method.
* @param options The options parameters.
*/
getMultiplePagesWithOffsetNext(
pagingGetMultiplePagesWithOffsetOptions: PagingGetMultiplePagesWithOffsetOptions,
nextLink: string,
options?: PagingGetMultiplePagesWithOffsetNextOptionalParams
): Promise<PagingGetMultiplePagesWithOffsetNextResponse>;
/**
* GetMultiplePagesRetryFirstNext
* @param nextLink The nextLink from the previous successful call to the GetMultiplePagesRetryFirst
* method.
* @param options The options parameters.
*/
getMultiplePagesRetryFirstNext(
nextLink: string,
options?: PagingGetMultiplePagesRetryFirstNextOptionalParams
): Promise<PagingGetMultiplePagesRetryFirstNextResponse>;
/**
* GetMultiplePagesRetrySecondNext
* @param nextLink The nextLink from the previous successful call to the GetMultiplePagesRetrySecond
* method.
* @param options The options parameters.
*/
getMultiplePagesRetrySecondNext(
nextLink: string,
options?: PagingGetMultiplePagesRetrySecondNextOptionalParams
): Promise<PagingGetMultiplePagesRetrySecondNextResponse>;
/**
* GetSinglePagesFailureNext
* @param nextLink The nextLink from the previous successful call to the GetSinglePagesFailure method.
* @param options The options parameters.
*/
getSinglePagesFailureNext(
nextLink: string,
options?: PagingGetSinglePagesFailureNextOptionalParams
): Promise<PagingGetSinglePagesFailureNextResponse>;
/**
* GetMultiplePagesFailureNext
* @param nextLink The nextLink from the previous successful call to the GetMultiplePagesFailure
* method.
* @param options The options parameters.
*/
getMultiplePagesFailureNext(
nextLink: string,
options?: PagingGetMultiplePagesFailureNextOptionalParams
): Promise<PagingGetMultiplePagesFailureNextResponse>;
/**
* GetMultiplePagesFailureUriNext
* @param nextLink The nextLink from the previous successful call to the GetMultiplePagesFailureUri
* method.
* @param options The options parameters.
*/
getMultiplePagesFailureUriNext(
nextLink: string,
options?: PagingGetMultiplePagesFailureUriNextOptionalParams
): Promise<PagingGetMultiplePagesFailureUriNextResponse>;
/**
* GetMultiplePagesLRONext
* @param nextLink The nextLink from the previous successful call to the GetMultiplePagesLRO method.
* @param options The options parameters.
*/
getMultiplePagesLRONext(
nextLink: string,
options?: PagingGetMultiplePagesLRONextOptionalParams
): Promise<PagingGetMultiplePagesLRONextResponse>;
/**
* GetPagingModelWithItemNameWithXMSClientNameNext
* @param nextLink The nextLink from the previous successful call to the
* GetPagingModelWithItemNameWithXMSClientName method.
* @param options The options parameters.
*/
getPagingModelWithItemNameWithXMSClientNameNext(
nextLink: string,
options?: PagingGetPagingModelWithItemNameWithXMSClientNameNextOptionalParams
): Promise<PagingGetPagingModelWithItemNameWithXMSClientNameNextResponse>;
} | the_stack |
import * as _ from 'lodash';
import { promises as fs } from 'fs';
import * as path from 'path';
import Network from './network';
import Volume from './volume';
import Service from './service';
import * as imageManager from './images';
import type { Image } from './images';
import * as applicationManager from './application-manager';
import {
CompositionStep,
generateStep,
CompositionStepAction,
} from './composition-steps';
import * as targetStateCache from '../device-state/target-state-cache';
import * as dockerUtils from '../lib/docker-utils';
import constants = require('../lib/constants');
import { getStepsFromStrategy } from './update-strategies';
import { InternalInconsistencyError, NotFoundError } from '../lib/errors';
import * as config from '../config';
import { checkTruthy, checkString } from '../lib/validation';
import { ServiceComposeConfig, DeviceMetadata } from './types/service';
import { ImageInspectInfo } from 'dockerode';
import { pathExistsOnHost } from '../lib/fs-utils';
export interface AppConstructOpts {
appId: number;
appName?: string;
commit?: string;
source?: string;
services: Service[];
volumes: Dictionary<Volume>;
networks: Dictionary<Network>;
}
export interface UpdateState {
localMode: boolean;
availableImages: Image[];
containerIds: Dictionary<string>;
downloading: string[];
}
interface ChangingPair<T> {
current?: T;
target?: T;
}
export class App {
public appId: number;
// When setting up an application from current state, these values are not available
public appName?: string;
public commit?: string;
public source?: string;
// Services are stored as an array, as at any one time we could have more than one
// service for a single service ID running (for example handover)
public services: Service[];
public networks: Dictionary<Network>;
public volumes: Dictionary<Volume>;
public constructor(opts: AppConstructOpts, public isTargetState: boolean) {
this.appId = opts.appId;
this.appName = opts.appName;
this.commit = opts.commit;
this.source = opts.source;
this.services = opts.services;
this.volumes = opts.volumes;
this.networks = opts.networks;
if (this.networks.default == null && isTargetState) {
// We always want a default network
this.networks.default = Network.fromComposeObject(
'default',
opts.appId,
{},
);
}
}
public nextStepsForAppUpdate(
state: UpdateState,
target: App,
): CompositionStep[] {
// Check to see if we need to polyfill in some "new" data for legacy services
this.migrateLegacy(target);
// Check for changes in the volumes. We don't remove any volumes until we remove an
// entire app
const volumeChanges = this.compareComponents(
this.volumes,
target.volumes,
false,
);
const networkChanges = this.compareComponents(
this.networks,
target.networks,
true,
);
let steps: CompositionStep[] = [];
// Any services which have died get a remove step
for (const service of this.services) {
if (service.status === 'Dead') {
steps.push(generateStep('remove', { current: service }));
}
}
const { removePairs, installPairs, updatePairs } = this.compareServices(
this.services,
target.services,
state.containerIds,
);
for (const { current: svc } of removePairs) {
// All removes get a kill action if they're not already stopping
if (svc!.status !== 'Stopping') {
steps.push(generateStep('kill', { current: svc! }));
} else {
steps.push(generateStep('noop', {}));
}
}
// For every service which needs to be updated, update via update strategy.
const servicePairs = updatePairs.concat(installPairs);
steps = steps.concat(
servicePairs
.map((pair) =>
this.generateStepsForService(pair, {
...state,
servicePairs: installPairs.concat(updatePairs),
targetApp: target,
networkPairs: networkChanges,
volumePairs: volumeChanges,
}),
)
.filter((step) => step != null) as CompositionStep[],
);
// Generate volume steps
steps = steps.concat(
this.generateStepsForComponent(volumeChanges, servicePairs, (v, svc) =>
// TODO: Volumes are stored without the appId prepended, but networks are stored
// with it prepended. Sort out this inequality
svc.config.volumes.includes(v.name),
),
);
// Generate network steps
steps = steps.concat(
this.generateStepsForComponent(
networkChanges,
servicePairs,
(n, svc) => `${this.appId}_${n.name}` in svc.config.networks,
),
);
if (
steps.length === 0 &&
target.commit != null &&
this.commit !== target.commit
) {
// TODO: The next PR should change this to support multiapp commit values
steps.push(
generateStep('updateCommit', {
target: target.commit,
appId: this.appId,
}),
);
}
return steps;
}
public async stepsToRemoveApp(
state: Omit<UpdateState, 'availableImages'>,
): Promise<CompositionStep[]> {
if (Object.keys(this.services).length > 0) {
return Object.values(this.services).map((service) =>
generateStep('kill', { current: service }),
);
}
if (Object.keys(this.networks).length > 0) {
return Object.values(this.networks).map((network) =>
generateStep('removeNetwork', { current: network }),
);
}
// Don't remove volumes in local mode
if (!state.localMode) {
if (Object.keys(this.volumes).length > 0) {
return Object.values(this.volumes).map((volume) =>
generateStep('removeVolume', { current: volume }),
);
}
}
return [];
}
private migrateLegacy(target: App) {
const currentServices = Object.values(this.services);
const targetServices = Object.values(target.services);
if (
currentServices.length === 1 &&
targetServices.length === 1 &&
targetServices[0].serviceName === currentServices[0].serviceName &&
checkTruthy(
currentServices[0].config.labels['io.balena.legacy-container'],
)
) {
// This is a legacy preloaded app or container, so we didn't have things like serviceId.
// We hack a few things to avoid an unnecessary restart of the preloaded app
// (but ensuring it gets updated if it actually changed)
targetServices[0].config.labels['io.balena.legacy-container'] =
currentServices[0].config.labels['io.balena.legacy-container'];
targetServices[0].config.labels['io.balena.service-id'] =
currentServices[0].config.labels['io.balena.service-id'];
targetServices[0].serviceId = currentServices[0].serviceId;
}
}
private compareComponents<T extends { isEqualConfig(target: T): boolean }>(
current: Dictionary<T>,
target: Dictionary<T>,
// Should this function issue remove steps? (we don't want to for volumes)
generateRemoves: boolean,
): Array<ChangingPair<T>> {
const currentNames = _.keys(current);
const targetNames = _.keys(target);
const outputs: Array<{ current?: T; target?: T }> = [];
if (generateRemoves) {
for (const name of _.difference(currentNames, targetNames)) {
outputs.push({ current: current[name] });
}
}
for (const name of _.difference(targetNames, currentNames)) {
outputs.push({ target: target[name] });
}
const toBeUpdated = _.filter(
_.intersection(targetNames, currentNames),
(name) => !current[name].isEqualConfig(target[name]),
);
for (const name of toBeUpdated) {
outputs.push({ current: current[name], target: target[name] });
}
return outputs;
}
private compareServices(
current: Service[],
target: Service[],
containerIds: Dictionary<string>,
): {
installPairs: Array<ChangingPair<Service>>;
removePairs: Array<ChangingPair<Service>>;
updatePairs: Array<ChangingPair<Service>>;
} {
const currentByServiceName = _.keyBy(current, 'serviceName');
const targetByServiceName = _.keyBy(target, 'serviceName');
const currentServiceNames = Object.keys(currentByServiceName);
const targetServiceNames = Object.keys(targetByServiceName);
const toBeRemoved = _(currentServiceNames)
.difference(targetServiceNames)
.map((id) => ({ current: currentByServiceName[id] }))
.value();
const toBeInstalled = _(targetServiceNames)
.difference(currentServiceNames)
.map((id) => ({ target: targetByServiceName[id] }))
.value();
const maybeUpdate = _.intersection(targetServiceNames, currentServiceNames);
// Build up a list of services for a given service name, always using the latest created
// service. Any older services will have kill steps emitted
for (const serviceName of maybeUpdate) {
const currentServiceContainers = _.filter(current, { serviceName });
if (currentServiceContainers.length > 1) {
currentByServiceName[serviceName] = _.maxBy(
currentServiceContainers,
'createdAt',
)!;
// All but the latest container for the service are spurious and should
// be removed
const otherContainers = _.without(
currentServiceContainers,
currentByServiceName[serviceName],
);
for (const service of otherContainers) {
toBeRemoved.push({ current: service });
}
} else {
currentByServiceName[serviceName] = currentServiceContainers[0];
}
}
/**
* Checks that the config for the current and target services matches, ignoring their run state.
* @param serviceCurrent
* @param serviceTarget
*/
const isEqualExceptForRunningState = (
serviceCurrent: Service,
serviceTarget: Service,
) =>
serviceCurrent.isEqualExceptForRunningState(serviceTarget, containerIds);
/**
* Checks if a service is running, if we tracked it as being started, if the config matches the desired config, and if we actually want it to ever be started.
* @param serviceCurrent
* @param serviceTarget
*/
const shouldBeStarted = (
serviceCurrent: Service,
serviceTarget: Service,
) => {
// If the target run state is stopped, or we are actually running, then we don't care about anything else
if (
serviceTarget.config.running === false ||
serviceCurrent.config.running === true
) {
return false;
}
// Check if we previously remember starting it
if (
applicationManager.containerStarted[serviceCurrent.containerId!] != null
) {
return false;
}
// If the config otherwise matches, then we should be running
return isEqualExceptForRunningState(serviceCurrent, serviceTarget);
};
/**
* Checks if a service should be stopped and if we have tracked it as being stopped.
*
* @param serviceCurrent
* @param serviceTarget
*/
const shouldBeStopped = (
serviceCurrent: Service,
serviceTarget: Service,
) => {
// check that we want to stop it, and that it isn't stopped
return (
serviceTarget.config.running === false &&
// When we issue a stop step, we remove the containerId from this structure.
// We check if the container has been removed first, so that we can ensure we're not providing multiple stop steps.
applicationManager.containerStarted[serviceCurrent.containerId!] == null
);
};
/**
* Filter all the services which should be updated due to run state change, or config mismatch.
*/
const toBeUpdated = maybeUpdate
.map((serviceName) => ({
current: currentByServiceName[serviceName],
target: targetByServiceName[serviceName],
}))
.filter(
({ current: c, target: t }) =>
!isEqualExceptForRunningState(c, t) ||
shouldBeStarted(c, t) ||
shouldBeStopped(c, t),
);
return {
installPairs: toBeInstalled,
removePairs: toBeRemoved,
updatePairs: toBeUpdated,
};
}
// We also accept a changingServices list, so we can avoid outputting multiple kill
// steps for a service
// FIXME: It would make the function simpler if we could just output the steps we want,
// and the nextStepsForAppUpdate function makes sure that we're not repeating steps.
// I'll leave it like this for now as this is how it was in application-manager.js, but
// it should be changed.
private generateStepsForComponent<T extends Volume | Network>(
components: Array<ChangingPair<T>>,
changingServices: Array<ChangingPair<Service>>,
dependencyFn: (component: T, service: Service) => boolean,
): CompositionStep[] {
if (components.length === 0) {
return [];
}
let steps: CompositionStep[] = [];
const actions: {
create: CompositionStepAction;
remove: CompositionStepAction;
} =
(components[0].current ?? components[0].target) instanceof Volume
? { create: 'createVolume', remove: 'removeVolume' }
: { create: 'createNetwork', remove: 'removeNetwork' };
for (const { current, target } of components) {
// If a current exists, we're either removing it or updating the configuration. In
// both cases, we must remove the component first, so we output those steps first.
// If we do remove the component, we first need to remove any services which depend
// on the component
if (current != null) {
// Find any services which are currently running which need to be killed when we
// recreate this component
const dependencies = _.filter(this.services, (s) =>
dependencyFn(current, s),
);
if (dependencies.length > 0) {
// We emit kill steps for these services, and wait to destroy the component in
// the next state application loop
// FIXME: We should add to the changingServices array, as we could emit several
// kill steps for a service
steps = steps.concat(
dependencies.reduce(
(acc, svc) =>
acc.concat(this.generateKillStep(svc, changingServices)),
[] as CompositionStep[],
),
);
} else {
steps = steps.concat([generateStep(actions.remove, { current })]);
}
} else if (target != null) {
steps = steps.concat([generateStep(actions.create, { target })]);
}
}
return steps;
}
private generateStepsForService(
{ current, target }: ChangingPair<Service>,
context: {
localMode: boolean;
availableImages: Image[];
downloading: string[];
targetApp: App;
containerIds: Dictionary<string>;
networkPairs: Array<ChangingPair<Network>>;
volumePairs: Array<ChangingPair<Volume>>;
servicePairs: Array<ChangingPair<Service>>;
},
): Nullable<CompositionStep> {
if (current?.status === 'Stopping') {
// Theres a kill step happening already, emit a noop to ensure we stay alive while
// this happens
return generateStep('noop', {});
}
if (current?.status === 'Dead') {
// A remove step will already have been generated, so we let the state
// application loop revisit this service, once the state has settled
return;
}
let needsDownload = false;
// don't attempt to fetch images whilst in local mode, as they should be there already
if (!context.localMode) {
needsDownload = !_.some(
context.availableImages,
(image) =>
image.dockerImageId === target?.config.image ||
imageManager.isSameImage(image, { name: target?.imageName! }),
);
}
if (needsDownload && context.downloading.includes(target?.imageName!)) {
// The image needs to be downloaded, and it's currently downloading. We simply keep
// the application loop alive
return generateStep('noop', {});
}
if (target && current?.isEqualConfig(target, context.containerIds)) {
// we're only starting/stopping a service
return this.generateContainerStep(current, target);
} else if (current == null) {
// Either this is a new service, or the current one has already been killed
return this.generateFetchOrStartStep(
target!,
needsDownload,
context.networkPairs,
context.volumePairs,
context.servicePairs,
);
} else {
if (!target) {
throw new InternalInconsistencyError(
'An empty changing pair passed to generateStepsForService',
);
}
const needsSpecialKill = this.serviceHasNetworkOrVolume(
current,
context.networkPairs,
context.volumePairs,
);
let strategy =
checkString(target.config.labels['io.balena.update.strategy']) || '';
const validStrategies = [
'download-then-kill',
'kill-then-download',
'delete-then-download',
'hand-over',
];
if (!validStrategies.includes(strategy)) {
strategy = 'download-then-kill';
}
const dependenciesMetForStart = this.dependenciesMetForServiceStart(
target,
context.networkPairs,
context.volumePairs,
context.servicePairs,
);
const dependenciesMetForKill = this.dependenciesMetForServiceKill(
target,
context.targetApp,
context.availableImages,
context.localMode,
);
return getStepsFromStrategy(strategy, {
current,
target,
needsDownload,
dependenciesMetForStart,
dependenciesMetForKill,
needsSpecialKill,
});
}
}
// We return an array from this function so the caller can just concatenate the arrays
// without worrying if the step is skipped or not
private generateKillStep(
service: Service,
changingServices: Array<ChangingPair<Service>>,
): CompositionStep[] {
if (
service.status !== 'Stopping' &&
!_.some(
changingServices,
({ current }) => current?.serviceName !== service.serviceName,
)
) {
return [generateStep('kill', { current: service })];
} else {
return [];
}
}
private serviceHasNetworkOrVolume(
svc: Service,
networkPairs: Array<ChangingPair<Network>>,
volumePairs: Array<ChangingPair<Volume>>,
): boolean {
const serviceVolumes = svc.config.volumes;
for (const { current } of volumePairs) {
if (current && serviceVolumes.includes(`${this.appId}_${current.name}`)) {
return true;
}
}
const serviceNetworks = svc.config.networks;
for (const { current } of networkPairs) {
if (current && `${this.appId}_${current.name}` in serviceNetworks) {
return true;
}
}
return false;
}
private generateContainerStep(current: Service, target: Service) {
// if the services release doesn't match, then rename the container...
if (current.commit !== target.commit) {
return generateStep('updateMetadata', { current, target });
} else if (target.config.running !== current.config.running) {
if (target.config.running) {
return generateStep('start', { target });
} else {
return generateStep('stop', { current });
}
}
}
private generateFetchOrStartStep(
target: Service,
needsDownload: boolean,
networkPairs: Array<ChangingPair<Network>>,
volumePairs: Array<ChangingPair<Volume>>,
servicePairs: Array<ChangingPair<Service>>,
): CompositionStep | undefined {
if (needsDownload) {
// We know the service name exists as it always does for targets
return generateStep('fetch', {
image: imageManager.imageFromService(target),
serviceName: target.serviceName!,
});
} else if (
this.dependenciesMetForServiceStart(
target,
networkPairs,
volumePairs,
servicePairs,
)
) {
return generateStep('start', { target });
}
}
// TODO: account for volumes-from, networks-from, links, etc
// TODO: support networks instead of only network mode
private dependenciesMetForServiceStart(
target: Service,
networkPairs: Array<ChangingPair<Network>>,
volumePairs: Array<ChangingPair<Volume>>,
servicePairs: Array<ChangingPair<Service>>,
): boolean {
// Firstly we check if a dependency is not already running (this is
// different to a dependency which is in the servicePairs below, as these
// are services which are changing). We could have a dependency which is
// starting up, but is not yet running.
const depInstallingButNotRunning = _.some(this.services, (svc) => {
if (target.dependsOn?.includes(svc.serviceName!)) {
if (!svc.config.running) {
return true;
}
}
});
if (depInstallingButNotRunning) {
return false;
}
const depedencyUnmet = _.some(target.dependsOn, (dep) =>
_.some(servicePairs, (pair) => pair.target?.serviceName === dep),
);
if (depedencyUnmet) {
return false;
}
if (
_.some(
networkPairs,
(pair) =>
`${this.appId}_${pair.target?.name}` === target.config.networkMode,
)
) {
return false;
}
if (
_.some(target.config.volumes, (volumeDefinition) => {
const [sourceName, destName] = volumeDefinition.split(':');
if (destName == null) {
// If this is not a named volume, ignore it
return false;
}
if (sourceName[0] === '/') {
// Absolute paths should also be ignored
return false;
}
return _.some(
volumePairs,
(pair) => `${target.appId}_${pair.target?.name}` === sourceName,
);
})
) {
return false;
}
// everything is ready for the service to start...
return true;
}
// Unless the update strategy requires an early kill (i.e kill-then-download,
// delete-then-download), we only want to kill a service once the images for the
// services it depends on have been downloaded, so as to minimize downtime (but not
// block the killing too much, potentially causing a daedlock)
private dependenciesMetForServiceKill(
target: Service,
targetApp: App,
availableImages: Image[],
localMode: boolean,
) {
// because we only check for an image being available, in local mode this will always
// be the case, so return true regardless. If this function ever checks anything else,
// we'll need to change the logic here
if (localMode) {
return true;
}
if (target.dependsOn != null) {
for (const dependency of target.dependsOn) {
const dependencyService = _.find(targetApp.services, {
serviceName: dependency,
});
if (
!_.some(
availableImages,
(image) =>
image.dockerImageId === dependencyService?.config.image ||
imageManager.isSameImage(image, {
name: dependencyService?.imageName!,
}),
)
) {
return false;
}
}
}
return true;
}
public static async fromTargetState(
app: targetStateCache.DatabaseApp,
): Promise<App> {
const volumes = _.mapValues(JSON.parse(app.volumes) ?? {}, (conf, name) => {
if (conf == null) {
conf = {};
}
if (conf.labels == null) {
conf.labels = {};
}
return Volume.fromComposeObject(name, app.appId, conf);
});
const networks = _.mapValues(
JSON.parse(app.networks) ?? {},
(conf, name) => {
return Network.fromComposeObject(name, app.appId, conf ?? {});
},
);
const [
opts,
supervisorApiHost,
hostPathExists,
hostnameOnHost,
] = await Promise.all([
config.get('extendedEnvOptions'),
dockerUtils
.getNetworkGateway(constants.supervisorNetworkInterface)
.catch(() => '127.0.0.1'),
(async () => ({
firmware: await pathExistsOnHost('/lib/firmware'),
modules: await pathExistsOnHost('/lib/modules'),
}))(),
(async () =>
_.trim(
await fs.readFile(
path.join(constants.rootMountPoint, '/etc/hostname'),
'utf8',
),
))(),
]);
const svcOpts = {
appName: app.name,
supervisorApiHost,
hostPathExists,
hostnameOnHost,
...opts,
};
// In the db, the services are an array, but here we switch them to an
// object so that they are consistent
const services: Service[] = await Promise.all(
(JSON.parse(app.services) ?? []).map(
async (svc: ServiceComposeConfig) => {
// Try to fill the image id if the image is downloaded
let imageInfo: ImageInspectInfo | undefined;
try {
imageInfo = await imageManager.inspectByName(svc.image);
} catch (e) {
if (!NotFoundError(e)) {
throw e;
}
}
const thisSvcOpts = {
...svcOpts,
imageInfo,
serviceName: svc.serviceName,
};
// FIXME: Typings for DeviceMetadata
return await Service.fromComposeObject(
svc,
(thisSvcOpts as unknown) as DeviceMetadata,
);
},
),
);
return new App(
{
appId: app.appId,
commit: app.commit,
appName: app.name,
source: app.source,
services,
volumes,
networks,
},
true,
);
}
}
export default App; | the_stack |
import * as React from 'react'
import useLatest from '@react-hook/latest'
import {lru} from './lru'
import type {LRUCache} from './lru'
/**
* Creates an asynchronous LRU cache which can be used with the [`useCache()`](#usecache) hook.
* Cache keys _must_ be a `string` type.
* @param resolve
* @param lruSize
*/
export function createCache<
Value = any,
ErrorType = Error,
Args extends any[] = []
>(
resolve: (key: string, ...args: Args) => Promise<Value>,
lruSize = Infinity
): Cache<Value, ErrorType, Args> {
const cache = lru<string, CacheState<Value, ErrorType>>(lruSize)
const listeners: Record<
string,
LRUCache<CacheSubscribeCallback<CacheState<Value, ErrorType>>, undefined>
> = {}
let id = -1
function dispatch(
action: CancelAction
): CacheState<Value, ErrorType> | undefined
function dispatch(
action: LoadingAction | SuccessAction<Value> | ErrorAction<ErrorType>
): CacheState<Value, ErrorType>
function dispatch(action: CacheAction<Value, ErrorType>) {
const current: CacheState<Value, ErrorType> | undefined = cache.read(
action.key
)
let next = current
if (action.status === 'loading') {
next = {
id: action.id,
status: action.status,
value: current?.value,
error: void 0,
}
} else if (action.status === 'cancelled') {
// We can't cancel a request that isn't already loading, so bail
if (!current || current.status !== 'loading') return current
next = {
id: current.id,
status: action.status,
value: current?.value,
error: void 0,
}
} else if (action.status === 'success') {
// Bails out if the action has been cancelled
if (
current &&
(current.status === 'cancelled' || current.id !== action.id)
)
return current
next = {
id: action.id,
status: action.status,
value: action.value,
error: void 0,
}
} else if (action.status === 'error') {
// Bails out if the action has been cancelled
if (
current &&
(current.status === 'cancelled' || current.id !== action.id)
) {
return current
}
next = {
id: action.id,
status: action.status,
value: current?.value,
error: action.error,
}
} else {
/* istanbul ignore next */
throw new Error(`Unrecognized action: ${JSON.stringify(action, null, 2)}`)
}
const value = next // TypeScript can be very dumb
cache.write(action.key, value)
listeners[action.key]?.forEach((callback) => callback(value))
return next
}
return {
load: async (key, ...args) => {
const current = cache.read(key)
const nextId = ++id
// Bails out if we are already loading this key
if (current?.status === 'loading') return current
dispatch({id: nextId, key, status: 'loading'})
try {
const value = await resolve(key, ...args)
return dispatch({id: nextId, key, status: 'success', value})
} catch (error) {
return dispatch({id: nextId, key, status: 'error', error})
}
},
read: (key) => cache.read(key),
cancel: (key) => dispatch({key, status: 'cancelled'}),
readAll: () => {
const output: CacheExport<Value, ErrorType> = {}
cache.forEach((key, value) => (output[key] = value))
return output
},
write: (input) => {
for (const key in input) {
const value = input[key]
cache.write(key, value)
listeners[key]?.forEach((callback) => callback(value))
}
},
subscribe: (key, callback) => {
let listenerCache = listeners[key]
if (!listenerCache) {
listenerCache = lru(Infinity)
listeners[key] = listenerCache
}
listenerCache.write(callback, undefined)
},
unsubscribe: (key, callback) => {
listeners[key]?.delete(callback)
},
}
}
export type Cache<
Value = any,
ErrorType = Error,
Args extends any[] = any[]
> = {
/**
* Preloads a `key` and provides ...args to the resolver
*/
load: (key: string, ...args: Args) => Promise<CacheState<Value, ErrorType>>
/**
* Reads a `key` in the LRU cache and returns its value if there is one, otherwise
* returns undefined
*/
read: (key: string) => CacheState<Value, ErrorType> | undefined
/**
* Cancels any pending promises for `key`
*/
cancel: (key: string) => void
/**
* Returns a {[key: string]: CacheState} object. This can be used
* for persisting the state rendered on a server to the client.
*/
readAll: () => CacheExport<Value, ErrorType>
/**
* Writes a {[key: string]: CacheState} to the LRU cache. This can be used
* for persisting the state rendered on a server to the client.
*/
write: (input: CacheExport<Value, ErrorType>) => void
/**
* Subscribes to changes to `key`. That is, `callback` will be invoked
* any time the state assigned to `key` changed.
*/
subscribe: (
key: string,
callback: CacheSubscribeCallback<CacheState<Value, ErrorType>>
) => void
/**
* Unsubscribes to changes to `key`
*/
unsubscribe: (
key: string,
callback: CacheSubscribeCallback<CacheState<Value, ErrorType>>
) => void
}
export type CacheState<Value = any, ErrorType = Error> =
| {
id: number
/**
* The cache is currently loading a value for this key
*/
status: 'loading'
/**
* This will be the previous value if there is one, otherwise undefined
*/
value: Value | undefined
/**
* Loading states will never have an error message
*/
error: undefined
}
| {
id: number
/**
* The cache has successfully loaded a value for the key
*/
status: 'success'
/**
* This is the value loaded by the cache
*/
value: Value
/**
* Success states will never have an error message
*/
error: undefined
}
| {
id: number
/**
* The cache encountered an error when loading a value for the key
*/
status: 'error'
/**
* This is the previous value if there is one, otherwise undefined
*/
value: Value | undefined
/**
* This is the error object that was caught during execution
*/
error: ErrorType
}
| {
id: number
/**
* The request for this key was cancelled before it was completed
*/
status: 'cancelled'
/**
* This is the previous value if there isone, otherwise undefined
*/
value: Value | undefined
/**
* Cancelled states never have an error message
*/
error: undefined
}
export type CacheExport<Value = any, ErrorType = Error> = Record<
string,
CacheState<Value, ErrorType>
>
type CacheAction<Value = any, ErrorType = Error> =
| LoadingAction
| CancelAction
| SuccessAction<Value>
| ErrorAction<ErrorType>
type LoadingAction = {
id: number
key: string
status: 'loading'
}
type SuccessAction<Value> = {
id: number
key: string
status: 'success'
value: Value
}
type CancelAction = {
key: string
status: 'cancelled'
}
type ErrorAction<ErrorType = Error> = {
id: number
key: string
status: 'error'
error: ErrorType
}
export type CacheStatus = 'loading' | 'success' | 'error' | 'cancelled'
export interface CacheSubscribeCallback<Value = any> {
(value: Value): void
}
/**
* A hook for reading and loading items from a persistent cache created by the
* `createCache()` function.
*
* @param cache A cache created by the `createCache()` function
* @param key The cache key to read or load from the cache
* @param args Arguments passed to the `cache.load(key, ...args)` function
*/
export function useCache<
Value = any,
ErrorType = Error,
Args extends any[] = any[]
>(
cache: Cache<Value, ErrorType, Args>,
key: string,
...args: Args
): readonly [
UseCacheState<Value, ErrorType>,
() => Promise<CacheState<Value, ErrorType>>
] {
const [state, setState] = React.useState<{
key: string
cache: Cache<Value, ErrorType, Args>
current: CacheState<Value, ErrorType> | undefined
}>(
// Uses an init function because we don't want every render to affect
// the LRU algorithm when we read the cache
() => ({
key,
cache,
current: cache.read(key),
})
)
// Allows the most recent arguments to be available in the cached callback below
const storedArgs = useLatest(args)
// If our cache or key changes, we don't have to set the new key/cache in
// an effect. It can just be done here.
if (state.cache !== cache || state.key !== key) {
setState({
key,
cache,
current: cache.read(key),
})
}
React.useEffect(() => {
let didUnsubscribe = false
const checkForUpdates = (
value: CacheState<Value, ErrorType> | undefined
) => {
if (didUnsubscribe) return
setState((prev) => {
// Bails if our cache or key has changed from under us
if (prev.cache !== cache || prev.key !== key) return prev
// Bails if our value hasn't changed
if (prev.current === value) return prev
return {
key: prev.key,
cache,
current: value,
}
})
}
cache.subscribe(key, checkForUpdates)
checkForUpdates(cache.read(key))
return () => {
didUnsubscribe = true
cache.unsubscribe(key, checkForUpdates)
}
}, [key, cache])
// So React DevTools can report the value of the hook
React.useDebugValue(state?.current)
return [
React.useMemo<UseCacheState<Value, ErrorType>>(() => {
const cancel = () => cache.cancel(key)
if (!state.current) {
return {
status: 'idle',
value: undefined,
error: undefined,
cancel,
}
} else {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {id, ...current} = state.current
return Object.assign(current, {cancel})
}
}, [state, key, cache]),
React.useCallback(() => cache.load(key, ...storedArgs.current), [
key,
cache,
storedArgs,
]),
]
}
export type UseCacheStatus = 'idle' | CacheStatus
export type UseCacheState<Value = any, ErrorType = Error> =
| {
/**
* The key does not exist in the cache and the cache has not started
* loading this key
*/
status: 'idle'
/**
* When idle we have no current or previous value available
*/
value: undefined
/**
* No errors will be reported here
*/
error: undefined
/**
* Cancelling will have no effect when idle
*/
cancel: () => void
}
| {
/**
* The next value for the key is currently loading in the cache
*/
status: 'loading'
/**
* The previous value for this key will persist during the loading phase.
*/
value: Value | undefined
/**
* No errors will be reported
*/
error: undefined
/**
* Cancelling will prevent the value returned in this request from being
* added to state
*/
cancel: () => void
}
| {
/**
* The key does not exist in the cache and the cache has not started
* loading this key
*/
status: 'cancelled'
/**
* The previous value for this key will persist during the loading phase.
*/
value: Value | undefined
/**
* No errors will be reported
*/
error: undefined
/**
* Cancelling has no effect here
*/
cancel: () => void
}
| {
/**
* We have successfully received a value for the key
*/
status: 'success'
/**
* The value returned by the successful request
*/
value: Value
/**
* No errors will be reported here
*/
error: undefined
/**
* Cancelling will have no effect here
*/
cancel: () => void
}
| {
/**
* The promise in the cache encountered an error
*/
status: 'error'
/**
* The last successful value received by the cache will persist here
*/
value: Value | undefined
/**
* This is the error object encountered by the request
*/
error: ErrorType
/**
* Cancelling will have no effect here
*/
cancel: () => void
} | the_stack |
import {LitElement, html, css, PropertyValues, nothing} from 'lit';
import {customElement, query, property} from 'lit/decorators.js';
import './playground-project.js';
import './playground-tab-bar.js';
import './playground-file-editor.js';
import './playground-preview.js';
import {PlaygroundProject} from './playground-project.js';
import {ProjectManifest} from './shared/worker-api.js';
import {npmVersion, serviceWorkerHash} from './shared/version.js';
/**
* A multi-file code editor component with live preview that works without a
* server.
*
* <playground-ide> loads a project configuration file and the set of source
* files it describes from the network. The source files can be edited locally.
* To serve the locally edited files to the live preview, <playground-ide>
* registers a service worker to serve files to the preview from the main UI
* thread directly, without a network roundtrip.
*
* The project manifest is a JSON file with a "files" property. "files" is an
* object with properties for each file. The key is the filename, relative to
* the project manifest.
*
* Example project manifest:
* ```json
* {
* "files": {
* "./index.html": {},
* "./my-element.js": {},
* }
* }
* ```
*
* Files can also be given as <script> tag children of <playground-ide>. The
* type attribute must start with "sample/" and then the type of the file, one
* of: "js", "ts", "html", or "css". The <script> must also have a "filename"
* attribute.
*
* Example inline files:
* ```html
* <playground-ide>
* <script type="sample/html" filename="index.html">
* <script type="module" src="index.js"><script>
* <h1>Hello World</h1>
* </script>
* <script type="sample/js" filename="index.js">
* document.body.append('<h2>Hello from JS</h2>');
* </script>
* </playground>
* ```
*/
@customElement('playground-ide')
export class PlaygroundIde extends LitElement {
static styles = css`
:host {
display: flex;
height: 350px;
min-width: 200px;
border: var(--playground-border, solid 1px #ddd);
/* The invisible resize bar has a high z-index so that it's above
CodeMirror. But we don't want it also above other elements on the page.
Force a new stacking context. */
isolation: isolate;
}
#lhs {
display: flex;
flex-direction: column;
height: 100%;
flex: 1;
min-width: 100px;
border-radius: inherit;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-right: var(--playground-border, solid 1px #ddd);
}
playground-tab-bar {
flex-shrink: 0;
}
playground-file-editor {
flex: 1;
height: calc(100% - var(--playground-bar-height, 40px));
}
#rhs {
height: 100%;
width: max(100px, var(--playground-preview-width, 30%));
position: relative;
border-radius: inherit;
}
playground-preview {
height: 100%;
width: 100%;
border-radius: inherit;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
slot {
display: none;
}
#resizeBar {
position: absolute;
top: 0;
left: -5px;
width: 10px;
height: 100%;
z-index: 9;
cursor: col-resize;
}
#resizeOverlay {
display: none;
}
#resizeOverlay.resizing {
display: block;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 99999;
cursor: col-resize;
}
`;
/**
* A document-relative path to a project configuration file.
*
* When both `projectSrc` and `files` are set, the one set most recently wins.
* Slotted children win only if both `projectSrc` and `files` are undefined.
*/
@property({attribute: 'project-src', hasChanged: () => false})
get projectSrc(): string | undefined {
// To minimize synchronization complexity, we delegate the `projectSrc` and
// `files` getters/setters directly to our <playground-project>. The only
// case we need to handle is properties set before upgrade or before we
// first render the <playground-project>.
//
// Note we set `hasChanged: () => false` because we don't need to trigger
// `update` when this property changes. (Why be a lit property at all?
// Because we want [1] to respond to attribute changes, and [2] to inherit
// property values set before upgrade).
//
// TODO(aomarks) Maybe a "delegate" decorator for this pattern?
return this._project?.projectSrc ?? this._projectSrcSetBeforeRender;
}
set projectSrc(src: string | undefined) {
const project = this._project;
if (project) {
project.projectSrc = src;
} else {
this._projectSrcSetBeforeRender = src;
}
}
/**
* Get or set the project config.
*
* When both `projectSrc` and `config` are set, the one set most recently
* wins. Slotted children win only if both `projectSrc` and `config` are
* undefined.
*/
@property({attribute: false, hasChanged: () => false})
get config(): ProjectManifest | undefined {
// Note this is declared a @property only to capture properties set before
// upgrade. Attribute reflection and update lifecycle disabled because they
// are not needed in this case.
return this._project?.config ?? this._configSetBeforeRender;
}
set config(config: ProjectManifest | undefined) {
const project = this._project;
if (project) {
project.config = config;
} else {
this._configSetBeforeRender = config;
}
}
/**
* Base URL for script execution sandbox.
*
* It is highly advised to change this property to a URL on a separate origin
* which has no privileges to perform sensitive actions or access sensitive
* data. This is because this element will execute arbitrary JavaScript, and
* does not have the ability to sanitize or sandbox it.
*
* This URL must host the following files from the playground-elements
* package:
* 1. playground-service-worker.js
* 2. playground-service-worker-proxy.html
*
* Defaults to the directory containing the script that defines this element
* on the same origin (typically something like
* "/node_modules/playground-elements/").
*/
@property({attribute: 'sandbox-base-url'})
sandboxBaseUrl = `https://unpkg.com/playground-elements@${npmVersion}/`;
/**
* The service worker scope to register on
*/
// TODO: generate this?
@property({attribute: 'sandbox-scope'})
sandboxScope = `__playground_swfs_${serviceWorkerHash}/`;
/**
* Allow the user to add, remove, and rename files in the project's virtual
* filesystem. Disabled by default.
*/
@property({type: Boolean, attribute: 'editable-file-system'})
editableFileSystem = false;
/**
* If true, display a left-hand-side gutter with line numbers. Default false
* (hidden).
*/
@property({type: Boolean, attribute: 'line-numbers'})
lineNumbers = false;
/**
* If true, wrap for long lines. Default false
*/
@property({type: Boolean, attribute: 'line-wrapping'})
lineWrapping = false;
/**
* If true, allow the user to change the relative size of the LHS editor and
* RHS preview by clicking and dragging in the space between them.
*/
@property({type: Boolean})
resizable = false;
/**
* How to handle `playground-hide` and `playground-fold` comments.
*
* See https://github.com/google/playground-elements#hiding--folding for
* more details.
*
* Options:
* - on: Hide and fold regions, and hide the special comments.
* - off: Don't hide or fold regions, but still hide the special comments.
* - off-visible: Don't hide or fold regions, and show the special comments as
* literal text.
*/
@property()
pragmas: 'on' | 'off' | 'off-visible' = 'on';
/**
* The HTML file used in the preview.
*/
@property({attribute: 'html-file'})
htmlFile = 'index.html';
/**
* If true, will disable code completions in the code-editor.
*/
@property({type: Boolean, attribute: 'no-completions'})
noCompletions = false;
/**
* Indicates whether the user has modified, added, or removed any project
* files. Resets whenever a new project is loaded.
*/
get modified(): boolean {
return this._project?.modified ?? false;
}
@query('playground-project')
private _project!: PlaygroundProject | null;
@query('#resizeBar')
private _resizeBar!: HTMLDivElement;
@query('#rhs')
private _rhs!: HTMLDivElement;
private _configSetBeforeRender?: ProjectManifest;
private _projectSrcSetBeforeRender?: string;
render() {
const projectId = 'project';
const editorId = 'editor';
return html`
<playground-project
id=${projectId}
.sandboxBaseUrl=${this.sandboxBaseUrl}
.sandboxScope=${this.sandboxScope}
>
<slot></slot>
</playground-project>
<div id="lhs">
<playground-tab-bar
part="tab-bar"
.project=${projectId}
.editor=${editorId}
.editableFileSystem=${this.editableFileSystem}
>
</playground-tab-bar>
<playground-file-editor
id=${editorId}
part="editor"
.lineNumbers=${this.lineNumbers}
.lineWrapping=${this.lineWrapping}
.project=${projectId}
.pragmas=${this.pragmas}
.noCompletions=${this.noCompletions}
>
</playground-file-editor>
</div>
<div id="rhs">
${this.resizable
? html`<div
id="resizeBar"
@pointerdown=${this._onResizeBarPointerdown}
></div>`
: nothing}
<playground-preview
part="preview"
exportparts="preview-toolbar,
preview-location,
preview-reload-button,
preview-loading-indicator,
diagnostic-tooltip,
dialog"
.htmlFile=${this.htmlFile}
.project=${projectId}
></playground-preview>
</div>
`;
}
firstUpdated() {
if (this._configSetBeforeRender) {
this._project!.config = this._configSetBeforeRender;
this._configSetBeforeRender = undefined;
}
if (this._projectSrcSetBeforeRender) {
this._project!.projectSrc = this._projectSrcSetBeforeRender;
this._projectSrcSetBeforeRender = undefined;
}
}
async update(changedProperties: PropertyValues<this>) {
if (changedProperties.has('resizable') && this.resizable === false) {
// Note we set this property on the RHS element instead of the host so
// that when "resizable" is toggled, we don't reset a host value that the
// user might have set.
this._rhs?.style.removeProperty('--playground-preview-width');
}
super.update(changedProperties);
}
private _onResizeBarPointerdown({pointerId}: PointerEvent) {
const bar = this._resizeBar;
bar.setPointerCapture(pointerId);
const rhsStyle = this._rhs.style;
const {left: hostLeft, right: hostRight} = this.getBoundingClientRect();
const hostWidth = hostRight - hostLeft;
const rhsMinWidth = 100;
const rhsMaxWidth = hostWidth - 100;
const onPointermove = (event: PointerEvent) => {
const rhsWidth = Math.min(
rhsMaxWidth,
Math.max(rhsMinWidth, hostRight - event.clientX)
);
const percent = (rhsWidth / hostWidth) * 100;
rhsStyle.setProperty('--playground-preview-width', `${percent}%`);
};
bar.addEventListener('pointermove', onPointermove);
const onPointerup = () => {
bar.releasePointerCapture(pointerId);
bar.removeEventListener('pointermove', onPointermove);
bar.removeEventListener('pointerup', onPointerup);
};
bar.addEventListener('pointerup', onPointerup);
}
}
declare global {
interface HTMLElementTagNameMap {
'playground-ide': PlaygroundIde;
}
} | the_stack |
import {
Body, JsonController, UseBefore, Get, Param, QueryParam, Put, Delete, Authorized, CurrentUser,
BadRequestError, ForbiddenError, InternalServerError, NotFoundError, UploadedFile, Post
} from 'routing-controllers';
import passportJwtMiddleware from '../security/passportJwtMiddleware';
import * as fs from 'fs';
import * as path from 'path';
import {IUser} from '../../../shared/models/IUser';
import {User} from '../models/User';
import {isNullOrUndefined} from 'util';
import {errorCodes} from '../config/errorCodes';
import * as sharp from 'sharp';
import config from '../config/main';
import {Course} from '../models/Course';
import emailService from '../services/EmailService';
const multer = require('multer');
const uploadOptions = {
storage: multer.diskStorage({
destination: (req: any, file: any, cb: any) => {
cb(null, path.join(config.uploadFolder, 'users'));
},
filename: (req: any, file: any, cb: any) => {
const id = req.params.id;
const randomness = '-' + (Math.floor(Math.random() * 8999) + 1000);
const extPos = file.originalname.lastIndexOf('.');
const ext = (extPos !== -1) ? `.${file.originalname.substr(extPos + 1).toLowerCase()}` : '';
cb(null, id + randomness + ext);
}
}),
};
function escapeRegex(text: string) {
return text.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
@JsonController('/users')
@UseBefore(passportJwtMiddleware)
export class UserController {
/**
* @api {get} /api/users/ Request all users
* @apiName GetUsers
* @apiGroup User
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {User[]} users List of users.
*
* @apiSuccessExample {json} Success-Response:
* [
* {
* "_id": "5a037e6a60f72236d8e7c81d",
* "updatedAt": "2018-01-08T19:27:49.483Z",
* "createdAt": "2017-11-08T22:00:10.899Z",
* "uid": "123456",
* "email": "student1@test.local",
* "__v": 0,
* "isActive": true,
* "role": "student",
* "profile": {
* "firstName": "Tick",
* "lastName": "Studi",
* "picture": {
* "alias": "IMG_20141226_211216.jpg",
* "name": "5a037e6a60f72236d8e7c81d-9558.jpg",
* "path": "uploads\\users\\5a037e6a60f72236d8e7c81d-9558.jpg"
* }
* },
* "id": "5a037e6a60f72236d8e7c81d"
* },
* {
* "uid": null,
* "_id": "5a037e6a60f72236d8e7c815",
* "updatedAt": "2017-11-08T22:00:10.898Z",
* "createdAt": "2017-11-08T22:00:10.898Z",
* "email": "teacher2@test.local",
* "__v": 0,
* "isActive": true,
* "role": "teacher",
* "profile": {
* "firstName": "Ober",
* "lastName": "Lehrer"
* },
* "id": "5a037e6a60f72236d8e7c815"
* }
* ]
*/
@Get('/')
@Authorized(['teacher', 'admin'])
async getUsers(@CurrentUser() currentUser: IUser) {
const users = await User.find();
return users.map(user => user.forUser(currentUser));
}
/**
* @api {get} /api/users/members/search Request users with certain role and query
* @apiName SearchUser
* @apiGroup User
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String="student","teacher"} role User role.
* @apiParam {String} query Query string.
* @apiParam {Number} limit Limit.
*
* @apiSuccess {Object} result Search result.
* @apiSuccess {User[]} result.users List of found users.
* @apiSuccess {Object} result.meta Meta data.
* @apiSuccess {Number} meta.count Number of users with given role.
*
* @apiSuccessExample {json} Success-Response:
* {
* "users": [
* {
* "_id": "5a037e6a60f72236d8e7c81d",
* "updatedAt": "2018-01-08T19:27:49.483Z",
* "createdAt": "2017-11-08T22:00:10.899Z",
* "uid": "123456",
* "email": "student1@test.local",
* "__v": 0,
* "score": 1.1,
* "isActive": true,
* "role": "student",
* "profile": {
* "firstName": "Tick",
* "lastName": "Studi",
* "picture": {
* "alias": "IMG_20141226_211216.jpg",
* "name": "5a037e6a60f72236d8e7c81d-9558.jpg",
* "path": "uploads\\users\\5a037e6a60f72236d8e7c81d-9558.jpg"
* }
* },
* "id": "5a037e6a60f72236d8e7c81d"
* },
* {
* "_id": "5a037e6a60f72236d8e7c81f",
* "updatedAt": "2017-11-08T22:00:10.900Z",
* "createdAt": "2017-11-08T22:00:10.900Z",
* "uid": "345678",
* "email": "student3@test.local",
* "__v": 0,
* "score": 1.1,
* "isActive": true,
* "role": "student",
* "profile": {
* "firstName": "Track",
* "lastName": "Studi"
* },
* "id": "5a037e6a60f72236d8e7c81f"
* },
* {
* "_id": "5a037e6a60f72236d8e7c81e",
* "updatedAt": "2017-11-08T22:00:10.900Z",
* "createdAt": "2017-11-08T22:00:10.900Z",
* "uid": "234567",
* "email": "student2@test.local",
* "__v": 0,
* "score": 1.1,
* "isActive": true,
* "role": "student",
* "profile": {
* "firstName": "Trick",
* "lastName": "Studi"
* },
* "id": "5a037e6a60f72236d8e7c81e"
* }
* ],
* "meta": {
* "count": 31
* }
* }
*
* @apiError BadRequestError Method not allowed for this role.
* @apiError BadRequestError Query was empty.
*/
@Get('/members/search') // members/search because of conflict with /:id
@Authorized(['teacher', 'admin'])
async searchUser(
@CurrentUser() currentUser: IUser, @QueryParam('role') role: string,
@QueryParam('query') query: string, @QueryParam('limit') limit?: number) {
if (role !== 'student' && role !== 'teacher') {
throw new BadRequestError('Method not allowed for this role.');
}
query = query.trim();
if (isNullOrUndefined(query)) {
throw new BadRequestError(errorCodes.query.empty.code);
}
const conditions: any = {};
const escaped = escapeRegex(query).split(' ');
conditions.$or = [];
conditions.$or.push({$text: {$search: query}});
escaped.forEach(elem => {
const re = new RegExp(elem, 'ig');
conditions.$or.push({uid: {$regex: re}});
conditions.$or.push({email: {$regex: re}});
conditions.$or.push({'profile.firstName': {$regex: re}});
conditions.$or.push({'profile.lastName': {$regex: re}});
});
const amountUsers = await User.countDocuments({role: role});
const users = await User.find(conditions, {
'score': {$meta: 'textScore'}
})
.where({role: role})
.limit(limit ? limit : Number.MAX_SAFE_INTEGER)
.sort({'score': {$meta: 'textScore'}});
return {
users: users.map(user => user.forUser(currentUser)),
meta: {
count: amountUsers
}
};
}
/**
* @api {get} /api/users/roles/ Request all user roles
* @apiName GetUserRoles
* @apiGroup User
* @apiPermission admin
*
* @apiSuccess {String[]} roles List of user roles.
*
* @apiSuccessExample {json} Success-Response:
* [
* "student",
* "teacher",
* "admin"
* ]
*/
@Authorized(['admin'])
@Get('/roles/')
getRoles() {
// TODO: Fix any cast
return (<any>User.schema.path('role')).enumValues;
}
/**
* @api {get} /api/users/:id Request user with certain ID
* @apiName GetUser
* @apiGroup User
*
* @apiParam {String} id User ID.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {User} user User.
*
* @apiError NotFoundError User was not found.
*
* @apiSuccessExample {json} Success-Response:
* {
* "_id": "5a037e6a60f72236d8e7c81d",
* "updatedAt": "2018-01-08T19:27:49.483Z",
* "createdAt": "2017-11-08T22:00:10.899Z",
* "uid": "123456",
* "email": "student1@test.local",
* "__v": 0,
* "isActive": true,
* "role": "student",
* "profile": {
* "firstName": "Tick",
* "lastName": "Studi",
* "picture": {
* "alias": "IMG_20141226_211216.jpg",
* "name": "5a037e6a60f72236d8e7c81d-9558.jpg",
* "path": "uploads\\users\\5a037e6a60f72236d8e7c81d-9558.jpg"
* }
* },
* "id": "5a037e6a60f72236d8e7c81d"
* }
*/
@Get('/:id([a-fA-F0-9]{24})')
async getUser(@Param('id') id: string, @CurrentUser() currentUser?: IUser) {
const user = await User.findById(id).populate('progress');
if (!user) {
throw new NotFoundError(`User was not found.`);
}
return user.forUser(currentUser);
}
/**
* @api {post} /api/users/picture/:id Add picture to user profile
* @apiName PostUserPicture
* @apiGroup User
*
* @apiParam {Object} file Uploaded file.
* @apiParam {String} id User target ID.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {User} user Affected user.
*
* @apiSuccessExample {json} Success-Response:
* {
* "_id": "5a037e6a60f72236d8e7c81d",
* "updatedAt": "2018-01-08T19:27:49.483Z",
* "createdAt": "2017-11-08T22:00:10.899Z",
* "uid": "123456",
* "email": "student1@test.local",
* "__v": 0,
* "isActive": true,
* "role": "student",
* "profile": {
* "firstName": "Tick",
* "lastName": "Studi",
* "picture": {
* "alias": "IMG_20141226_211216.jpg",
* "name": "5a037e6a60f72236d8e7c81d-9558.jpg",
* "path": "uploads\\users\\5a037e6a60f72236d8e7c81d-9558.jpg"
* }
* },
* "id": "5a037e6a60f72236d8e7c81d"
* }
*
* @apiError ForbiddenError Forbidden format of uploaded picture.
* @apiError ForbiddenError You don't have the authorization to change a user of this role.
* @apiError BadRequestError
*/
@Post('/picture/:id')
async addUserPicture(
@UploadedFile('file', {options: uploadOptions}) file: any,
@Param('id') id: string, @CurrentUser() currentUser: IUser) {
const mimeFamily = file.mimetype.split('/', 1)[0];
if (mimeFamily !== 'image') {
throw new ForbiddenError('Forbidden format of uploaded picture: ' + mimeFamily);
}
let user = await User.findById(id);
if (!user.checkEditableBy(currentUser).editAllowed) {
throw new ForbiddenError(errorCodes.user.cantChangeUserWithHigherRole.text);
}
if (user.profile.picture) {
const oldPicturePath = user.profile.picture.path;
if (oldPicturePath && fs.existsSync(oldPicturePath)) {
fs.unlinkSync(oldPicturePath);
}
}
const resizedImageBuffer =
await sharp(file.path)
.resize(config.maxProfileImageWidth, config.maxProfileImageHeight, {fit: 'inside', withoutEnlargement: true})
.toBuffer({resolveWithObject: true});
fs.writeFileSync(file.path, resizedImageBuffer.data);
user.profile.picture = {
_id: null,
name: file.filename,
alias: file.originalname,
path: path.relative(path.dirname(config.uploadFolder), file.path).replace(/\\\\?/g, '/'),
size: resizedImageBuffer.info.size
};
try {
user = await user.save();
} catch (error) {
throw new BadRequestError(error);
}
return user.forUser(currentUser);
}
/**
* @api {put} /api/users/:id Update user
* @apiName PutUser
* @apiGroup User
* @apiPermission student
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String} id User target ID.
* @apiParam {Object} newUser New user data.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {User} user Updated user.
*
* @apiSuccessExample {json} Success-Response:
* {
* "_id": "5a037e6a60f72236d8e7c81d",
* "updatedAt": "2018-01-08T19:27:49.483Z",
* "createdAt": "2017-11-08T22:00:10.899Z",
* "uid": "123456",
* "email": "student1@test.local",
* "__v": 0,
* "isActive": true,
* "role": "student",
* "profile": {
* "firstName": "Tick",
* "lastName": "Studi",
* "picture": {
* "alias": "IMG_20141226_211216.jpg",
* "name": "5a037e6a60f72236d8e7c81d-9558.jpg",
* "path": "uploads\\users\\5a037e6a60f72236d8e7c81d-9558.jpg"
* }
* },
* "id": "5a037e6a60f72236d8e7c81d"
* }
*
* @apiError BadRequestError Invalid update role.
* @apiError BadRequestError You can't change your own role.
* @apiError BadRequestError This email address is already in use.
* @apiError BadRequestError Invalid current password!
* @apiError ForbiddenError You don't have the authorization to change a user of this role.
* @apiError ForbiddenError Only users with admin privileges can change roles.
* @apiError ForbiddenError Only users with admin privileges can change uids.
*/
@Authorized(['student', 'teacher', 'admin'])
@Put('/:id')
async updateUser(@Param('id') id: string, @Body() newUser: any, @CurrentUser() currentUser: IUser) {
if (id === currentUser._id && currentUser.role !== newUser.role) {
throw new BadRequestError(errorCodes.user.cantChangeOwnRole.text);
}
const oldUser = await User.findById(id);
const {userIsAdmin, editAllowed} = oldUser.checkEditableBy(currentUser);
if (!editAllowed) {
throw new ForbiddenError(errorCodes.user.cantChangeUserWithHigherRole.text);
}
if (oldUser.uid && newUser.uid === null) {
newUser.uid = oldUser.uid;
}
if (oldUser.role && typeof newUser.role === 'undefined') {
newUser.role = oldUser.role;
} else if (typeof User.getEditLevelUnsafe(newUser) === 'undefined') {
throw new BadRequestError(errorCodes.user.invalidNewUserRole.text);
}
if (!userIsAdmin) {
if (newUser.role !== oldUser.role) {
throw new ForbiddenError(errorCodes.user.onlyAdminsCanChangeRoles.text);
}
if (newUser.uid !== oldUser.uid) {
throw new ForbiddenError(errorCodes.user.onlyAdminsCanChangeUids.text);
}
}
if (typeof newUser.password === 'undefined' || newUser.password.length === 0) {
delete newUser.password;
} else if (!userIsAdmin) {
const isValidPassword = await oldUser.isValidPassword(newUser.currentPassword);
if (!isValidPassword) {
throw new BadRequestError(errorCodes.user.invalidPassword.text);
}
}
{
const sameEmail = {$and: [{'email': newUser.email}, {'_id': {$ne: newUser._id}}]};
const users = await User.find(sameEmail).limit(1);
if (users.length > 0) {
throw new BadRequestError(errorCodes.user.emailAlreadyInUse.text);
}
}
const updatedUser = await User.findOneAndUpdate({_id: id}, newUser, {new: true});
return updatedUser.forUser(currentUser);
}
/**
* @api {delete} /api/users/:id Delete user
* @apiName DeleteUser
* @apiGroup User
* @apiPermission student
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String} id User ID.
*
* @apiSuccess {Boolean} result Confirmation of deletion.
*
* @apiSuccessExample {json} Success-Response:
* {
* "result": true
* }
*
* @apiError BadRequestError There are no other users with admin privileges.
*/
@Authorized(['student', 'teacher', 'admin'])
@Delete('/:id')
async deleteUser(@Param('id') id: string, @CurrentUser() currentUser: IUser) {
const otherAdmin = await User.findOne({$and: [{'role': 'admin'}, {'_id': {$ne: id}}]});
if (id === currentUser._id && (currentUser.role === 'teacher' || currentUser.role === 'student')) {
try {
emailService.sendDeleteRequest(currentUser, otherAdmin);
} catch (err) {
throw new InternalServerError(errorCodes.mail.notSend.code);
}
return {result: true};
}
if (id === currentUser._id && currentUser.role === 'admin') {
if (otherAdmin === null) {
throw new BadRequestError(errorCodes.user.noOtherAdmins.text);
}
} else if (id !== currentUser._id && currentUser.role !== 'admin') {
throw new BadRequestError(errorCodes.user.cantDeleteOtherUsers.text);
}
const user = await User.findById(id);
if (id === currentUser._id) {
// if user is current user, move ownership to another admin.
await Course.changeCourseAdminFromUser(user, otherAdmin);
} else {
// move Courseownerships to active user.
await Course.changeCourseAdminFromUser(user, currentUser);
}
await user.remove();
return {result: true};
}
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import {
mockReadFileSync,
mockReadPkcs12Keystore,
mockReadPkcs12Truststore,
} from './opensearch_config.test.mocks';
import { applyDeprecations, configDeprecationFactory } from '@osd/config';
import { OpenSearchConfig, config } from './opensearch_config';
const DEFAULT_CONFIG_PATH = 'opensearch';
const LEGACY_CONFIG_PATH = 'elasticsearch';
const applyOpenSearchDeprecations = (
settings: Record<string, any> = {},
path = DEFAULT_CONFIG_PATH
) => {
const deprecations = config.deprecations!(configDeprecationFactory);
const deprecationMessages: string[] = [];
const _config: any = {};
_config[path] = settings;
const migrated = applyDeprecations(
_config,
deprecations.map((deprecation) => ({
deprecation,
path,
})),
(msg) => deprecationMessages.push(msg)
);
return {
messages: deprecationMessages,
migrated,
};
};
const applyLegacyDeprecations = (settings: Record<string, any> = {}) => {
return applyOpenSearchDeprecations(settings, LEGACY_CONFIG_PATH);
};
test('set correct defaults', () => {
const configValue = new OpenSearchConfig(config.schema.validate({}));
expect(configValue).toMatchInlineSnapshot(`
OpenSearchConfig {
"apiVersion": "7.x",
"customHeaders": Object {},
"healthCheckDelay": "PT2.5S",
"hosts": Array [
"http://localhost:9200",
],
"ignoreVersionMismatch": false,
"logQueries": false,
"optimizedHealthcheckId": undefined,
"password": undefined,
"pingTimeout": "PT30S",
"requestHeadersWhitelist": Array [
"authorization",
],
"requestTimeout": "PT30S",
"shardTimeout": "PT30S",
"sniffInterval": false,
"sniffOnConnectionFault": false,
"sniffOnStart": false,
"ssl": Object {
"alwaysPresentCertificate": false,
"certificate": undefined,
"certificateAuthorities": undefined,
"key": undefined,
"keyPassphrase": undefined,
"verificationMode": "full",
},
"username": undefined,
}
`);
});
test('#hosts accepts both string and array of strings', () => {
let configValue = new OpenSearchConfig(
config.schema.validate({ hosts: 'http://some.host:1234' })
);
expect(configValue.hosts).toEqual(['http://some.host:1234']);
configValue = new OpenSearchConfig(config.schema.validate({ hosts: ['http://some.host:1234'] }));
expect(configValue.hosts).toEqual(['http://some.host:1234']);
configValue = new OpenSearchConfig(
config.schema.validate({
hosts: ['http://some.host:1234', 'https://some.another.host'],
})
);
expect(configValue.hosts).toEqual(['http://some.host:1234', 'https://some.another.host']);
});
test('#requestHeadersWhitelist accepts both string and array of strings', () => {
let configValue = new OpenSearchConfig(
config.schema.validate({ requestHeadersWhitelist: 'token' })
);
expect(configValue.requestHeadersWhitelist).toEqual(['token']);
configValue = new OpenSearchConfig(
config.schema.validate({ requestHeadersWhitelist: ['token'] })
);
expect(configValue.requestHeadersWhitelist).toEqual(['token']);
configValue = new OpenSearchConfig(
config.schema.validate({
requestHeadersWhitelist: ['token', 'X-Forwarded-Proto'],
})
);
expect(configValue.requestHeadersWhitelist).toEqual(['token', 'X-Forwarded-Proto']);
});
describe('reads files', () => {
beforeEach(() => {
mockReadFileSync.mockReset();
mockReadFileSync.mockImplementation((path: string) => `content-of-${path}`);
mockReadPkcs12Keystore.mockReset();
mockReadPkcs12Keystore.mockImplementation((path: string) => ({
key: `content-of-${path}.key`,
cert: `content-of-${path}.cert`,
ca: [`content-of-${path}.ca`],
}));
mockReadPkcs12Truststore.mockReset();
mockReadPkcs12Truststore.mockImplementation((path: string) => [`content-of-${path}`]);
});
it('reads certificate authorities when ssl.keystore.path is specified', () => {
const configValue = new OpenSearchConfig(
config.schema.validate({ ssl: { keystore: { path: 'some-path' } } })
);
expect(mockReadPkcs12Keystore).toHaveBeenCalledTimes(1);
expect(configValue.ssl.certificateAuthorities).toEqual(['content-of-some-path.ca']);
});
it('reads certificate authorities when ssl.truststore.path is specified', () => {
const configValue = new OpenSearchConfig(
config.schema.validate({ ssl: { truststore: { path: 'some-path' } } })
);
expect(mockReadPkcs12Truststore).toHaveBeenCalledTimes(1);
expect(configValue.ssl.certificateAuthorities).toEqual(['content-of-some-path']);
});
it('reads certificate authorities when ssl.certificateAuthorities is specified', () => {
let configValue = new OpenSearchConfig(
config.schema.validate({ ssl: { certificateAuthorities: 'some-path' } })
);
expect(mockReadFileSync).toHaveBeenCalledTimes(1);
expect(configValue.ssl.certificateAuthorities).toEqual(['content-of-some-path']);
mockReadFileSync.mockClear();
configValue = new OpenSearchConfig(
config.schema.validate({ ssl: { certificateAuthorities: ['some-path'] } })
);
expect(mockReadFileSync).toHaveBeenCalledTimes(1);
expect(configValue.ssl.certificateAuthorities).toEqual(['content-of-some-path']);
mockReadFileSync.mockClear();
configValue = new OpenSearchConfig(
config.schema.validate({
ssl: { certificateAuthorities: ['some-path', 'another-path'] },
})
);
expect(mockReadFileSync).toHaveBeenCalledTimes(2);
expect(configValue.ssl.certificateAuthorities).toEqual([
'content-of-some-path',
'content-of-another-path',
]);
});
it('reads certificate authorities when ssl.keystore.path, ssl.truststore.path, and ssl.certificateAuthorities are specified', () => {
const configValue = new OpenSearchConfig(
config.schema.validate({
ssl: {
keystore: { path: 'some-path' },
truststore: { path: 'another-path' },
certificateAuthorities: 'yet-another-path',
},
})
);
expect(mockReadPkcs12Keystore).toHaveBeenCalledTimes(1);
expect(mockReadPkcs12Truststore).toHaveBeenCalledTimes(1);
expect(mockReadFileSync).toHaveBeenCalledTimes(1);
expect(configValue.ssl.certificateAuthorities).toEqual([
'content-of-some-path.ca',
'content-of-another-path',
'content-of-yet-another-path',
]);
});
it('reads a private key and certificate when ssl.keystore.path is specified', () => {
const configValue = new OpenSearchConfig(
config.schema.validate({ ssl: { keystore: { path: 'some-path' } } })
);
expect(mockReadPkcs12Keystore).toHaveBeenCalledTimes(1);
expect(configValue.ssl.key).toEqual('content-of-some-path.key');
expect(configValue.ssl.certificate).toEqual('content-of-some-path.cert');
});
it('reads a private key when ssl.key is specified', () => {
const configValue = new OpenSearchConfig(config.schema.validate({ ssl: { key: 'some-path' } }));
expect(mockReadFileSync).toHaveBeenCalledTimes(1);
expect(configValue.ssl.key).toEqual('content-of-some-path');
});
it('reads a certificate when ssl.certificate is specified', () => {
const configValue = new OpenSearchConfig(
config.schema.validate({ ssl: { certificate: 'some-path' } })
);
expect(mockReadFileSync).toHaveBeenCalledTimes(1);
expect(configValue.ssl.certificate).toEqual('content-of-some-path');
});
});
describe('throws when config is invalid', () => {
beforeAll(() => {
const realFs = jest.requireActual('fs');
mockReadFileSync.mockImplementation((path: string) => realFs.readFileSync(path));
const utils = jest.requireActual('../utils');
mockReadPkcs12Keystore.mockImplementation((path: string, password?: string) =>
utils.readPkcs12Keystore(path, password)
);
mockReadPkcs12Truststore.mockImplementation((path: string, password?: string) =>
utils.readPkcs12Truststore(path, password)
);
});
it('throws if key is invalid', () => {
const value = { ssl: { key: '/invalid/key' } };
expect(
() => new OpenSearchConfig(config.schema.validate(value))
).toThrowErrorMatchingInlineSnapshot(
`"ENOENT: no such file or directory, open '/invalid/key'"`
);
});
it('throws if certificate is invalid', () => {
const value = { ssl: { certificate: '/invalid/cert' } };
expect(
() => new OpenSearchConfig(config.schema.validate(value))
).toThrowErrorMatchingInlineSnapshot(
`"ENOENT: no such file or directory, open '/invalid/cert'"`
);
});
it('throws if certificateAuthorities is invalid', () => {
const value = { ssl: { certificateAuthorities: '/invalid/ca' } };
expect(
() => new OpenSearchConfig(config.schema.validate(value))
).toThrowErrorMatchingInlineSnapshot(`"ENOENT: no such file or directory, open '/invalid/ca'"`);
});
it('throws if keystore path is invalid', () => {
const value = { ssl: { keystore: { path: '/invalid/keystore' } } };
expect(
() => new OpenSearchConfig(config.schema.validate(value))
).toThrowErrorMatchingInlineSnapshot(
`"ENOENT: no such file or directory, open '/invalid/keystore'"`
);
});
it('throws if keystore does not contain a key', () => {
mockReadPkcs12Keystore.mockReturnValueOnce({});
const value = { ssl: { keystore: { path: 'some-path' } } };
expect(
() => new OpenSearchConfig(config.schema.validate(value))
).toThrowErrorMatchingInlineSnapshot(`"Did not find key in OpenSearch keystore."`);
});
it('throws if keystore does not contain a certificate', () => {
mockReadPkcs12Keystore.mockReturnValueOnce({ key: 'foo' });
const value = { ssl: { keystore: { path: 'some-path' } } };
expect(
() => new OpenSearchConfig(config.schema.validate(value))
).toThrowErrorMatchingInlineSnapshot(`"Did not find certificate in OpenSearch keystore."`);
});
it('throws if truststore path is invalid', () => {
const value = { ssl: { keystore: { path: '/invalid/truststore' } } };
expect(
() => new OpenSearchConfig(config.schema.validate(value))
).toThrowErrorMatchingInlineSnapshot(
`"ENOENT: no such file or directory, open '/invalid/truststore'"`
);
});
it('throws if key and keystore.path are both specified', () => {
const value = { ssl: { key: 'foo', keystore: { path: 'bar' } } };
expect(() => config.schema.validate(value)).toThrowErrorMatchingInlineSnapshot(
`"[ssl]: cannot use [key] when [keystore.path] is specified"`
);
});
it('throws if certificate and keystore.path are both specified', () => {
const value = { ssl: { certificate: 'foo', keystore: { path: 'bar' } } };
expect(() => config.schema.validate(value)).toThrowErrorMatchingInlineSnapshot(
`"[ssl]: cannot use [certificate] when [keystore.path] is specified"`
);
});
});
describe('deprecations', () => {
it('logs a warning if opensearch.username is set to "elastic"', () => {
const { messages } = applyOpenSearchDeprecations({ username: 'elastic' });
expect(messages).toMatchInlineSnapshot(`
Array [
"Setting [opensearch.username] to \\"elastic\\" is deprecated. You should use the \\"opensearch_dashboards_system\\" user instead.",
]
`);
});
it('logs a warning if opensearch.username is set to "opensearchDashboards"', () => {
const { messages } = applyOpenSearchDeprecations({ username: 'opensearchDashboards' });
expect(messages).toMatchInlineSnapshot(`
Array [
"Setting [opensearch.username] to \\"opensearchDashboards\\" is deprecated. You should use the \\"opensearch_dashboards_system\\" user instead.",
]
`);
});
it('does not log a warning if opensearch.username is set to something besides "elastic" or "opensearchDashboards"', () => {
const { messages } = applyOpenSearchDeprecations({ username: 'otheruser' });
expect(messages).toHaveLength(0);
});
it('does not log a warning if opensearch.username is unset', () => {
const { messages } = applyOpenSearchDeprecations({});
expect(messages).toHaveLength(0);
});
it('logs a warning if ssl.key is set and ssl.certificate is not', () => {
const { messages } = applyOpenSearchDeprecations({ ssl: { key: '' } });
expect(messages).toMatchInlineSnapshot(`
Array [
"Setting [opensearch.ssl.key] without [opensearch.ssl.certificate] is deprecated. This has no effect, you should use both settings to enable TLS client authentication to OpenSearch.",
]
`);
});
it('logs a warning if ssl.certificate is set and ssl.key is not', () => {
const { messages } = applyOpenSearchDeprecations({ ssl: { certificate: '' } });
expect(messages).toMatchInlineSnapshot(`
Array [
"Setting [opensearch.ssl.certificate] without [opensearch.ssl.key] is deprecated. This has no effect, you should use both settings to enable TLS client authentication to OpenSearch.",
]
`);
});
it('does not log a warning if both ssl.key and ssl.certificate are set', () => {
const { messages } = applyOpenSearchDeprecations({ ssl: { key: '', certificate: '' } });
expect(messages).toEqual([]);
});
it('logs a warning if elasticsearch.sniffOnStart is set and opensearch.sniffOnStart is not', () => {
const { messages } = applyLegacyDeprecations({ sniffOnStart: true });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.sniffOnStart\\" is deprecated and has been replaced by \\"opensearch.sniffOnStart\\"",
]
`);
});
it('logs a warning if elasticsearch.sniffInterval is set and opensearch.sniffInterval is not', () => {
const { messages } = applyLegacyDeprecations({ sniffInterval: true });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.sniffInterval\\" is deprecated and has been replaced by \\"opensearch.sniffInterval\\"",
]
`);
});
it('logs a warning if elasticsearch.sniffOnConnectionFault is set and opensearch.sniffOnConnectionFault is not', () => {
const { messages } = applyLegacyDeprecations({ sniffOnConnectionFault: true });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.sniffOnConnectionFault\\" is deprecated and has been replaced by \\"opensearch.sniffOnConnectionFault\\"",
]
`);
});
it('logs a warning if elasticsearch.hosts is set and opensearch.hosts is not', () => {
const { messages } = applyLegacyDeprecations({ hosts: [''] });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.hosts\\" is deprecated and has been replaced by \\"opensearch.hosts\\"",
]
`);
});
it('logs a warning if elasticsearch.username is set and opensearch.username is not', () => {
const { messages } = applyLegacyDeprecations({ username: '' });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.username\\" is deprecated and has been replaced by \\"opensearch.username\\"",
]
`);
});
it('logs a warning if elasticsearch.password is set and opensearch.password is not', () => {
const { messages } = applyLegacyDeprecations({ password: '' });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.password\\" is deprecated and has been replaced by \\"opensearch.password\\"",
]
`);
});
it('logs a warning if elasticsearch.requestHeadersWhitelist is set and opensearch.requestHeadersWhitelist is not', () => {
const { messages } = applyLegacyDeprecations({ requestHeadersWhitelist: [''] });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.requestHeadersWhitelist\\" is deprecated and has been replaced by \\"opensearch.requestHeadersWhitelist\\"",
]
`);
});
it('logs a warning if elasticsearch.customHeaders is set and opensearch.customHeaders is not', () => {
const { messages } = applyLegacyDeprecations({ customHeaders: [''] });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.customHeaders\\" is deprecated and has been replaced by \\"opensearch.customHeaders\\"",
]
`);
});
it('logs a warning if elasticsearch.shardTimeout is set and opensearch.shardTimeout is not', () => {
const { messages } = applyLegacyDeprecations({ shardTimeout: 100 });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.shardTimeout\\" is deprecated and has been replaced by \\"opensearch.shardTimeout\\"",
]
`);
});
it('logs a warning if elasticsearch.requestTimeout is set and opensearch.requestTimeout is not', () => {
const { messages } = applyLegacyDeprecations({ requestTimeout: 100 });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.requestTimeout\\" is deprecated and has been replaced by \\"opensearch.requestTimeout\\"",
]
`);
});
it('logs a warning if elasticsearch.pingTimeout is set and opensearch.pingTimeout is not', () => {
const { messages } = applyLegacyDeprecations({ pingTimeout: 100 });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.pingTimeout\\" is deprecated and has been replaced by \\"opensearch.pingTimeout\\"",
]
`);
});
it('logs a warning if elasticsearch.logQueries is set and opensearch.logQueries is not', () => {
const { messages } = applyLegacyDeprecations({ logQueries: true });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.logQueries\\" is deprecated and has been replaced by \\"opensearch.logQueries\\"",
]
`);
});
it('logs a warning if elasticsearch.optimizedHealthcheckId is set and opensearch.optimizedHealthcheckId is not', () => {
const { messages } = applyLegacyDeprecations({ optimizedHealthcheckId: '' });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.optimizedHealthcheckId\\" is deprecated and has been replaced by \\"opensearch.optimizedHealthcheckId\\"",
]
`);
});
it('logs a warning if elasticsearch.ssl is set and opensearch.ssl is not', () => {
const { messages } = applyLegacyDeprecations({ ssl: true });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.ssl\\" is deprecated and has been replaced by \\"opensearch.ssl\\"",
]
`);
});
it('logs a warning if elasticsearch.ssl.certificate is set and opensearch.ssl.certificate is not', () => {
const { messages } = applyLegacyDeprecations({ ssl: { certificate: '' } });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.ssl\\" is deprecated and has been replaced by \\"opensearch.ssl\\"",
]
`);
});
it('logs a warning if elasticsearch.apiVersion is set and opensearch.apiVersion is not', () => {
const { messages } = applyLegacyDeprecations({ apiVersion: '' });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.apiVersion\\" is deprecated and has been replaced by \\"opensearch.apiVersion\\"",
]
`);
});
it('logs a warning if elasticsearch.healthCheck is set and opensearch.healthCheck is not', () => {
const { messages } = applyLegacyDeprecations({ healthCheck: true });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.healthCheck\\" is deprecated and has been replaced by \\"opensearch.healthCheck\\"",
]
`);
});
it('logs a warning if elasticsearch.ignoreVersionMismatch is set and opensearch.ignoreVersionMismatch is not', () => {
const { messages } = applyLegacyDeprecations({ ignoreVersionMismatch: true });
expect(messages).toMatchInlineSnapshot(`
Array [
"\\"elasticsearch.ignoreVersionMismatch\\" is deprecated and has been replaced by \\"opensearch.ignoreVersionMismatch\\"",
]
`);
});
});
test('#username throws if equal to "elastic", only while running from source', () => {
const obj = {
username: 'elastic',
};
expect(() => config.schema.validate(obj, { dist: false })).toThrowErrorMatchingInlineSnapshot(
`"[username]: value of \\"elastic\\" is forbidden. This is a superuser account that can obfuscate privilege-related issues. You should use the \\"opensearch_dashboards_system\\" user instead."`
);
expect(() => config.schema.validate(obj, { dist: true })).not.toThrow();
}); | the_stack |
import {Component, OnInit, ViewChild, Inject, OnDestroy} from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import {ApplicationSecurityService, ManageUngitService, StorageService} from '../../core/services';
import {FolderTreeComponent} from './folder-tree/folder-tree.component';
import {BucketBrowserService, TodoItemNode} from '../../core/services/bucket-browser.service';
import {FileUtils, HelpUtils} from '../../core/util';
import {BucketDataService} from './bucket-data.service';
import {BucketConfirmationDialogComponent} from './bucket-confirmation-dialog/bucket-confirmation-dialog.component';
import {HttpEventType} from '@angular/common/http';
import {CopyPathUtils} from '../../core/util/copyPathUtils';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
@Component({
selector: 'datalab-bucket-browser',
templateUrl: './bucket-browser.component.html',
styleUrls: ['./bucket-browser.component.scss', './upload-window.component.scss']
})
export class BucketBrowserComponent implements OnInit, OnDestroy {
public readonly uploadingQueueLength: number = 4;
public readonly maxFileSize: number = 4294967296;
public readonly refreshTokenLimit = 1500000;
private unsubscribe$ = new Subject();
private isTokenRefreshing = false;
public addedFiles = [];
public folderItems = [];
public originFolderItems = [];
public objectPath;
public path = '';
public pathInsideBucket = '';
public bucketName = '';
public endpoint = '';
public selectedFolder: any;
public selectedFolderForAction: any;
public selected: any[];
public bucketStatus;
public allDisable: boolean;
public isActionsOpen: boolean;
public folders: any[];
public selectedItems;
public searchValue: string;
public isQueueFull: boolean;
public isSelectionOpened: any;
public isFilterVisible: boolean;
public buckets;
public isFileUploading: boolean;
public cloud: string;
@ViewChild(FolderTreeComponent, {static: true}) folderTreeComponent;
constructor(
@Inject(MAT_DIALOG_DATA) public data: any,
public toastr: ToastrService,
public dialog: MatDialog,
public dialogRef: MatDialogRef<BucketBrowserComponent>,
private manageUngitService: ManageUngitService,
private _fb: FormBuilder,
private bucketBrowserService: BucketBrowserService,
public bucketDataService: BucketDataService,
private auth: ApplicationSecurityService,
private storage: StorageService,
) {
}
ngOnInit() {
this.bucketName = this.data.bucket;
this.endpoint = this.data.endpoint;
this.bucketDataService.refreshBucketdata(this.bucketName, this.endpoint);
this.bucketStatus = this.data.bucketStatus;
this.buckets = this.data.buckets;
this.cloud = this.getCloud();
// this.cloud = 'azure';
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
public getTokenValidTime(): number {
const token = JSON.parse(atob(this.storage.getToken().split('.')[1]));
return token.exp * 1000 - new Date().getTime();
}
private refreshToken(): void {
this.isTokenRefreshing = true;
this.auth.refreshToken()
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe(tokens => {
this.storage.storeTokens(tokens);
this.isTokenRefreshing = false;
this.sendFile();
});
}
public showItem(item): void {
const flatItem = this.folderTreeComponent.nestedNodeMap.get(item);
this.folderTreeComponent.showItem(flatItem);
}
public closeUploadWindow(): void {
this.addedFiles = [];
}
public toggleSelectedFile(file, type): void {
console.log(file, type);
type === 'file' ? file.isSelected = !file.isSelected : file.isFolderSelected = !file.isFolderSelected;
this.selected = this.folderItems.filter(item => item.isSelected);
this.selectedFolderForAction = this.folderItems.filter(item => item.isFolderSelected);
this.selectedItems = [...this.selected, ...this.selectedFolderForAction];
this.isActionsOpen = false;
}
filesPicked(files): void {
Array.prototype.forEach.call(files, file => {
this.addedFiles.push(file.webkitRelativePath);
});
}
public dissableAll(event): void {
this.allDisable = event;
}
public handleFileInput(event): void {
const fullFilesList = Object['values'](event.target.files);
if (fullFilesList.length > 0) {
const files = fullFilesList.filter(v => v.size < this.maxFileSize);
const toBigFile = fullFilesList.length !== files.length;
const toMany = files.length > 50;
if (toMany) {
files.length = 50;
}
if (toBigFile || toMany) {
this.dialog.open(BucketConfirmationDialogComponent, {data: {
items: {toBig: toBigFile, toMany: toMany}, type: 'upload_limitation'
} , width: '550px'})
.afterClosed().subscribe((res) => {
if (res) {
this.checkQueue(files);
}
});
} else {
this.checkQueue(files);
}
}
event.target.value = '';
}
private checkQueue(files) {
if (this.refreshTokenLimit > this.getTokenValidTime()) {
this.isTokenRefreshing = true;
this.auth.refreshToken()
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe(v => {
this.uploadingQueue(files);
this.isTokenRefreshing = false;
});
} else {
this.uploadingQueue(files);
}
}
private async uploadingQueue(files) {
if (files.length) {
let askForAll = true;
let skipAll = false;
const folderFiles = this.folderItems.reduce((existFiles, item) => {
if (!item.children) {
existFiles.push(item.item);
}
return existFiles;
}, []);
for (const file of files) {
const existFile = folderFiles.find(v => v === file['name']);
const uploadItem = {
name: file['name'],
file: file,
size: file.size,
path: this.path,
};
if (existFile && askForAll) {
const result = await this.openResolveDialog(existFile);
if (result) {
askForAll = !result.forAll;
if (result.forAll && !result.replaceObject) {
skipAll = true;
}
if (result.replaceObject) {
this.addedFiles.push(uploadItem);
this.uploadNewFile(uploadItem);
}
}
} else if (!existFile || (existFile && !askForAll && !skipAll)) {
this.addedFiles.push(uploadItem);
this.uploadNewFile(uploadItem);
}
}
}
setTimeout(() => {
const element = document.querySelector('#upload-list');
element && element.scrollIntoView({ block: 'end', behavior: 'smooth' });
}, 10);
}
async openResolveDialog(existFile) {
const dialog = this.dialog.open(BucketConfirmationDialogComponent, {
data: {items: existFile, type: 'resolve_conflicts'} , width: '550px'
});
return dialog.afterClosed().toPromise().then(result => {
return Promise.resolve(result);
});
}
public onFolderClick(event): void {
this.searchValue = '';
this.clearSelection();
this.selectedFolder = event.flatNode;
if (this.isSelectionOpened) {
this.isSelectionOpened = false;
}
this.folderItems = event.element ? event.element.children : event.children;
if (this.folderItems) {
this.folders = this.folderItems.filter(v => v.children);
const files = this.folderItems.filter(v => !v.children).sort((a, b) => a.item > b.item ? 1 : -1);
this.folderItems = [...this.folders, ...files];
this.objectPath = event.pathObject;
this.path = event.path;
this.originFolderItems = this.folderItems.map(v => v);
this.pathInsideBucket = this.path.indexOf('/') !== -1 ? this.path.slice(this.path.indexOf('/') + 1) + '/' : '';
this.folderItems.forEach(item => item.isSelected = false);
}
}
public filterObjects(): void {
this.folderItems = this.originFolderItems.filter(v => v.item.toLowerCase().indexOf(this.searchValue.toLowerCase()) !== -1);
}
private clearSelection(): void {
this.folderItems.forEach(item => item.isSelected = false);
this.folderItems.forEach(item => item.isFolderSelected = false);
this.selected = this.folderItems.filter(item => item.isSelected);
this.selectedFolderForAction = this.folderItems.filter(item => item.isFolderSelected);
this.selectedItems = [];
}
public deleteAddedFile(file): void {
if ( file.subscr && file.request) {
this.dialog.open(BucketConfirmationDialogComponent, {data: {items: file, type: 'cancel'} , width: '550px'})
.afterClosed().subscribe((res) => {
res && file.subscr.unsubscribe();
res && this.addedFiles.splice(this.addedFiles.indexOf(file), 1);
this.isFileUploading = this.addedFiles.some(v => v.status === 'uploading');
this.sendFile();
}, () => {
this.isFileUploading = this.addedFiles.some(v => v.status === 'uploading');
this.sendFile();
});
} else {
this.addedFiles.splice(this.addedFiles.indexOf(file), 1);
this.isFileUploading = this.addedFiles.some(v => v.status === 'uploading');
this.sendFile();
}
}
private uploadNewFile(file): void {
const path = file.path.indexOf('/') !== -1 ? this.path.slice(this.path.indexOf('/') + 1) : '';
const fullPath = path ? `${path}/${file.name}` : file.name;
const formData = new FormData();
formData.append('size', file.file.size);
formData.append('object', fullPath);
formData.append('bucket', this.bucketName);
formData.append('endpoint', this.endpoint);
formData.append('file', file.file);
file.status = 'waiting';
file.request = this.bucketBrowserService.uploadFile(formData);
this.sendFile(file);
}
public sendFile(file?): void {
const waitUploading = this.addedFiles.filter(v => v.status === 'waiting');
const uploading = this.addedFiles.filter(v => v.status === 'uploading');
this.isQueueFull = !!waitUploading.length;
this.isFileUploading = this.addedFiles.some(v => v.status === 'uploading');
// console.log((this.getTokenValidTime() / 1000 / 60 ).toFixed(0) + ' minutes');
if ((this.refreshTokenLimit > this.getTokenValidTime()) && !this.isTokenRefreshing) {
this.refreshToken();
}
if (waitUploading.length && uploading.length < this.uploadingQueueLength) {
if (!file) {
file = waitUploading[0];
}
file.status = 'uploading';
this.isFileUploading = this.addedFiles.some(v => v.status === 'uploading');
this.isQueueFull = this.addedFiles.some(v => v.status === 'waiting');
file.subscr = file.request.subscribe((event: any) => {
if (event.type === HttpEventType.UploadProgress) {
file.progress = Math.round(95 * event.loaded / event.total);
if (file.progress === 95 && !file.interval) {
file.interval = setInterval(() => {
if (file.progress < 99) {
return file.progress++;
}
}, file.size < 1094967296 ? 12000 : 20000);
}
} else if (event['type'] === HttpEventType.Response) {
window.clearInterval(file.interval);
file.status = 'uploaded';
delete file.request;
this.sendFile(this.addedFiles.find(v => v.status === 'waiting'));
this.bucketDataService.refreshBucketdata(this.bucketName, this.endpoint);
}
}, error => {
window.clearInterval(file.interval);
file.status = 'failed';
delete file.request;
this.sendFile(this.addedFiles.find(v => v.status === 'waiting'));
}
);
}
}
public refreshBucket(): void {
this.path = '';
this.bucketDataService.refreshBucketdata(this.bucketName, this.endpoint);
this.isSelectionOpened = false;
}
public openBucket($event): void {
this.bucketName = $event.name;
this.endpoint = $event.endpoint;
this.path = '';
this.bucketDataService.refreshBucketdata(this.bucketName, this.endpoint);
this.isSelectionOpened = false;
this.cloud = this.getCloud();
}
private getCloud(): string {
return this.buckets.filter(v => v.children.some(bucket => {
return bucket.name === this.bucketName;
}))[0].cloud.toLowerCase();
}
public createFolder(folder): void {
this.allDisable = true;
this.folderTreeComponent.addNewItem(folder, '', false);
}
public fileAction(action): void {
const selected = this.folderItems.filter(item => item.isSelected);
const folderSelected = this.folderItems.filter(item => item.isFolderSelected);
if (action === 'download') {
this.clearSelection();
this.isActionsOpen = false;
const path = encodeURIComponent(`${this.pathInsideBucket}${selected[0].item}`);
selected[0]['isDownloading'] = true;
this.folderItems.forEach(item => item.isSelected = false);
this.bucketBrowserService.downloadFile(`/${this.bucketName}/object/${path}/endpoint/${this.endpoint}/download`)
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe(event => {
if (event['type'] === HttpEventType.DownloadProgress) {
selected[0].progress = Math.round(100 * event['loaded'] / selected[0].object.size);
}
if (event['type'] === HttpEventType.Response) {
FileUtils.downloadBigFiles(event['body'], selected[0].item);
setTimeout(() => {
selected[0]['isDownloading'] = false;
selected[0].progress = 0;
}, 1000);
}
}, error => {
this.toastr.error(error.message || 'File downloading error!', 'Oops!');
selected[0]['isDownloading'] = false;
}
);
}
if (action === 'delete') {
const itemsForDeleting = [...folderSelected, ...selected];
const objects = itemsForDeleting.map(obj => obj.object.object);
let dataForServer = [];
objects.forEach(object => {
dataForServer.push(...this.bucketDataService.serverData.map(v => v.object).filter(v => v.indexOf(object) === 0));
});
dataForServer = [...dataForServer, ...objects].filter((v, i, arr) => i === arr.indexOf(v));
this.dialog.open(BucketConfirmationDialogComponent, {data: {items: itemsForDeleting, type: 'delete'} , width: '550px'})
.afterClosed().subscribe((res) => {
!res && this.clearSelection();
res && this.bucketBrowserService.deleteFile({
bucket: this.bucketName, endpoint: this.endpoint, 'objects': dataForServer
})
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe(() => {
this.bucketDataService.refreshBucketdata(this.bucketName, this.endpoint);
this.toastr.success('Objects successfully deleted!', 'Success!');
this.clearSelection();
}, error => {
this.toastr.error(error.message || 'Objects deleting error!', 'Oops!');
this.clearSelection();
});
});
}
}
public toogleActions(): void {
this.isActionsOpen = !this.isActionsOpen;
}
public closeActions(): void {
this.isActionsOpen = false;
}
public copyPath(): void {
const selected = this.folderItems.filter(item => item.isSelected || item.isFolderSelected)[0];
const cloud = this.getCloud();
const protocol = HelpUtils.getBucketProtocol(cloud);
if (cloud !== 'azure') {
CopyPathUtils.copyPath(protocol + selected.object.bucket + '/' + selected.object.object);
} else {
const bucketName = selected.object.bucket;
const accountName = this.bucketName.replace(selected.object.bucket, '').slice(0, -1);
const azureBucket = bucketName + '@' + accountName + '.blob.core.windows.net' + '/' + selected.object.object;
CopyPathUtils.copyPath(protocol + azureBucket);
}
this.clearSelection();
this.isActionsOpen = false;
this.toastr.success('Object path successfully copied!', 'Success!');
}
public toggleBucketSelection(): void {
this.isSelectionOpened = !this.isSelectionOpened;
}
public closeFilterInput(): void {
this.isFilterVisible = false;
this.searchValue = '';
this.filterObjects();
}
} | the_stack |
import * as gpgpu_util from './gpgpu_util';
import * as tex_util from './tex_util';
import * as webgl_util from './webgl_util';
import {WebGLLoseContextExtension} from './webgl_util';
export class GPGPUContext {
gl: WebGLRenderingContext;
textureFloatExtension: {};
colorBufferFloatExtension: {};
loseContextExtension: WebGLLoseContextExtension;
vertexBuffer: WebGLBuffer;
indexBuffer: WebGLBuffer;
framebuffer: WebGLFramebuffer;
outputTexture: WebGLTexture|null = null;
program: WebGLProgram|null = null;
private disposed = false;
private autoDebugValidate = false;
constructor(gl?: WebGLRenderingContext) {
if (gl != null) {
this.gl = gl;
} else {
this.gl = gpgpu_util.createWebGLContext();
}
// WebGL 2.0 enables texture floats without an extension.
if (!webgl_util.isWebGL2Enabled()) {
this.textureFloatExtension =
webgl_util.getExtensionOrThrow(this.gl, 'OES_texture_float');
} else {
this.colorBufferFloatExtension =
webgl_util.getExtensionOrThrow(this.gl, 'EXT_color_buffer_float');
}
this.loseContextExtension =
webgl_util.getExtensionOrThrow(this.gl, 'WEBGL_lose_context') as
WebGLLoseContextExtension;
this.vertexBuffer = gpgpu_util.createVertexBuffer(this.gl);
this.indexBuffer = gpgpu_util.createIndexBuffer(this.gl);
this.framebuffer = webgl_util.createFramebuffer(this.gl);
}
public dispose() {
this.throwIfDisposed();
if (this.program != null) {
console.warn(
'Disposing a GPGPUContext that still has a bound WebGLProgram.' +
' This is probably a resource leak, delete the program with ' +
'GPGPUContext.deleteProgram before disposing.');
}
if (this.outputTexture != null) {
console.warn(
'Disposing a GPGPUContext that still has a bound output matrix ' +
'texture. This is probably a resource leak, delete the output ' +
'matrix texture with GPGPUContext.deleteMatrixTexture before ' +
'disposing.');
}
const gl = this.gl;
webgl_util.callAndCheck(gl, () => gl.finish());
webgl_util.callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, null));
webgl_util.callAndCheck(gl, () => gl.deleteFramebuffer(this.framebuffer));
webgl_util.callAndCheck(gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, null));
webgl_util.callAndCheck(gl, () => gl.deleteBuffer(this.vertexBuffer));
webgl_util.callAndCheck(
gl, () => gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null));
webgl_util.callAndCheck(gl, () => gl.deleteBuffer(this.indexBuffer));
this.loseContextExtension.loseContext();
this.disposed = true;
}
public enableAutomaticDebugValidation(enabled: boolean) {
this.autoDebugValidate = enabled;
webgl_util.enableDebugWebGLErrorChecking(enabled);
}
public createMatrixTexture(rows: number, columns: number): WebGLTexture {
this.throwIfDisposed();
return gpgpu_util.createMatrixTexture(this.gl, rows, columns);
}
public uploadPixelDataToTexture(
texture: WebGLTexture,
pixels: ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement) {
this.throwIfDisposed();
gpgpu_util.uploadPixelDataToTexture(this.gl, texture, pixels);
}
public createPackedMatrixTexture(rows: number, columns: number):
WebGLTexture {
this.throwIfDisposed();
return gpgpu_util.createPackedMatrixTexture(this.gl, rows, columns);
}
public deleteMatrixTexture(texture: WebGLTexture) {
this.throwIfDisposed();
if (this.outputTexture === texture) {
webgl_util.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
this.outputTexture = null;
}
webgl_util.callAndCheck(this.gl, () => this.gl.deleteTexture(texture));
}
public uploadMatrixToTexture(
texture: WebGLTexture, rows: number, columns: number,
matrix: Float32Array) {
this.throwIfDisposed();
const numChannels = 1;
return gpgpu_util.uploadMatrixToTexture(
this.gl, texture, rows, columns, matrix, numChannels);
}
public uploadMatrixToPackedTexture(
texture: WebGLTexture, rows: number, columns: number,
matrix: Float32Array) {
this.throwIfDisposed();
return gpgpu_util.uploadMatrixToPackedTexture(
this.gl, texture, rows, columns, matrix);
}
public downloadMatrixFromTexture(
texture: WebGLTexture, rows: number, columns: number): Float32Array {
return this.downloadMatrixDriver(
texture,
() =>
gpgpu_util.downloadMatrixFromOutputTexture(this.gl, rows, columns));
}
public downloadMatrixFromPackedTexture(
texture: WebGLTexture, rows: number, columns: number): Float32Array {
return this.downloadMatrixDriver(
texture,
() => gpgpu_util.downloadMatrixFromPackedOutputTexture(
this.gl, rows, columns));
}
public createProgram(fragmentShaderSource: string): WebGLProgram {
this.throwIfDisposed();
const gl = this.gl;
const fragmentShader: WebGLShader =
webgl_util.createFragmentShader(gl, fragmentShaderSource);
const vertexShader: WebGLShader = gpgpu_util.createVertexShader(gl);
const program: WebGLProgram = webgl_util.createProgram(gl);
webgl_util.callAndCheck(gl, () => gl.attachShader(program, vertexShader));
webgl_util.callAndCheck(gl, () => gl.attachShader(program, fragmentShader));
webgl_util.linkProgram(gl, program);
if (this.autoDebugValidate) {
webgl_util.validateProgram(gl, program);
}
return program;
}
public deleteProgram(program: WebGLProgram) {
this.throwIfDisposed();
if (program === this.program) {
this.program = null;
}
if (program != null) {
webgl_util.callAndCheck(this.gl, () => this.gl.deleteProgram(program));
}
}
public setProgram(program: WebGLProgram|null) {
this.throwIfDisposed();
this.program = program;
if ((this.program != null) && this.autoDebugValidate) {
webgl_util.validateProgram(this.gl, this.program);
}
webgl_util.callAndCheck(this.gl, () => this.gl.useProgram(program));
}
public getUniformLocation(uniformName: string): WebGLUniformLocation {
this.throwIfDisposed();
this.throwIfNoProgram();
return webgl_util.getProgramUniformLocationOrThrow(
this.gl, this.program!, uniformName);
}
public setInputMatrixTexture(
inputMatrixTexture: WebGLTexture, uniformName: string,
textureUnit: number) {
this.throwIfDisposed();
this.throwIfNoProgram();
webgl_util.bindTextureToProgramUniformSampler(
this.gl, this.program!, inputMatrixTexture, uniformName, textureUnit);
}
public setOutputMatrixTexture(
outputMatrixTexture: WebGLTexture, rows: number, columns: number) {
this.setOutputMatrixTextureDriver(outputMatrixTexture, columns, rows);
}
public setOutputPackedMatrixTexture(
outputPackedMatrixTexture: WebGLTexture, rows: number, columns: number) {
this.throwIfDisposed();
const [width, height] =
tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns);
this.setOutputMatrixTextureDriver(outputPackedMatrixTexture, width, height);
}
public setOutputMatrixWriteRegion(
startRow: number, numRows: number, startColumn: number,
numColumns: number) {
this.setOutputMatrixWriteRegionDriver(
startColumn, startRow, numColumns, numRows);
}
public setOutputPackedMatrixWriteRegion(
startRow: number, numRows: number, startColumn: number,
numColumns: number) {
throw new Error('setOutputPackedMatrixWriteRegion not implemented.');
}
public debugValidate() {
if (this.program != null) {
webgl_util.validateProgram(this.gl, this.program);
}
webgl_util.validateFramebuffer(this.gl);
}
public executeProgram() {
this.throwIfDisposed();
this.throwIfNoProgram();
const gl = this.gl;
gpgpu_util.bindVertexProgramAttributeStreams(
gl, this.program!, this.vertexBuffer);
if (this.autoDebugValidate) {
this.debugValidate();
}
webgl_util.callAndCheck(
gl, () => gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0));
}
public blockUntilAllProgramsCompleted() {
this.throwIfDisposed();
webgl_util.callAndCheck(this.gl, () => this.gl.finish());
}
private downloadMatrixDriver(
texture: WebGLTexture,
downloadAndDecode: () => Float32Array): Float32Array {
this.throwIfDisposed();
webgl_util.bindColorTextureToFramebuffer(
this.gl, texture, this.framebuffer);
const result = downloadAndDecode();
if (this.outputTexture != null) {
webgl_util.bindColorTextureToFramebuffer(
this.gl, this.outputTexture, this.framebuffer);
if (this.autoDebugValidate) {
webgl_util.validateFramebuffer(this.gl);
}
} else {
webgl_util.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
}
return result;
}
private setOutputMatrixTextureDriver(
outputMatrixTextureMaybePacked: WebGLTexture, width: number,
height: number) {
this.throwIfDisposed();
const gl = this.gl;
webgl_util.bindColorTextureToFramebuffer(
gl, outputMatrixTextureMaybePacked, this.framebuffer);
if (this.autoDebugValidate) {
webgl_util.validateFramebuffer(gl);
}
this.outputTexture = outputMatrixTextureMaybePacked;
webgl_util.callAndCheck(gl, () => gl.viewport(0, 0, width, height));
webgl_util.callAndCheck(gl, () => gl.scissor(0, 0, width, height));
}
private setOutputMatrixWriteRegionDriver(
x: number, y: number, width: number, height: number) {
this.throwIfDisposed();
webgl_util.callAndCheck(
this.gl, () => this.gl.scissor(x, y, width, height));
}
private throwIfDisposed() {
if (this.disposed) {
throw new Error('Attempted to use disposed GPGPUContext.');
}
}
private throwIfNoProgram() {
if (this.program == null) {
throw new Error('No GPU program is currently set.');
}
}
} | the_stack |
import { ReactElement } from 'react';
import { render, screen, waitFor, act } from 'unit-test/testUtils';
import userEvent from '@testing-library/user-event';
import { AllTheProviders } from "unit-test/testUtils";
import { FetchMock } from 'jest-fetch-mock/types';
import * as StateHooks from 'core/state/hooks';
import { WORKSPACE_STATUS } from 'modules/Workspaces/enums';
import { Actions, Subjects } from 'core/utils/abilities';
import CirclesComparationItem from '..';
import * as DatasourceHooks from 'modules/Settings/Credentials/Sections/MetricProvider/hooks';
import { COLOR_SANTAS_GREY, COLOR_COMET } from 'core/assets/colors';
import { setUserAbilities } from 'core/utils/abilities';
import { saveWorkspace } from 'core/utils/workspace';
import { saveProfile } from 'core/utils/profile';
(global as any).MutationObserver = MutationObserver
interface fakeCanProps {
I?: Actions;
a?: Subjects;
passThrough?: boolean;
isDisabled?: boolean;
allowedRoutes?: boolean;
children: ReactElement;
}
jest.mock('containers/Can', () => {
return {
__esModule: true,
default: ({ children }: fakeCanProps) => {
return <div>{children}</div>;
}
};
});
beforeEach(() => {
(fetch as FetchMock).resetMocks();
});
const props = {
id: 'circle-001'
}
const circle = {
name: 'Circle',
deployment: {
status: 'DEPLOYED'
}
}
const circleWithoutDeployment = {
name: 'Circle',
}
const defaultCircle = {
name: 'Default',
deployment: {
status: 'DEPLOYED'
}
}
const defaultCircleWithoutDeployment = {
name: 'Default',
deployment: {}
}
test('render CircleComparationItem default component', async () => {
const handleChange = jest.fn();
const updateCircle = jest.fn();
render(
<CirclesComparationItem id={props.id} onChange={handleChange} updateCircle={updateCircle} circlesListResponse={null} />
);
const comparationItem = await screen.findByTestId(`circle-comparation-item-${props.id}`)
const tabPanel = await screen.findByTestId(`tabpanel-Untitled`);
expect(comparationItem).toBeInTheDocument();
expect(tabPanel).toBeInTheDocument();
});
test('render CircleComparationItem with release', async () => {
const useGlobalStateSpy = jest.spyOn(StateHooks, 'useGlobalState').mockImplementation(() => ({
item: {
id: '123-workspace',
status: WORKSPACE_STATUS.COMPLETE
},
status: 'resolved'
}));
const useDatasourceSpy = jest.spyOn(DatasourceHooks, 'useDatasource').mockReturnValueOnce({
responseAll: [],
getAll: jest.fn
});
(fetch as FetchMock)
.mockResponseOnce(JSON.stringify(circle))
.mockResponseOnce(JSON.stringify(circle));
const handleChange = jest.fn();
const updateCircle = jest.fn();
render(
<AllTheProviders>
<CirclesComparationItem id={props.id} onChange={handleChange} updateCircle={updateCircle} circlesListResponse={null} />
</AllTheProviders>
);
await waitFor(() => {
expect(screen.getByTestId('layer-metrics-groups')).toBeInTheDocument();
expect(screen.getByText('Override release')).toBeInTheDocument();
expect(screen.getByText('Last release deployed')).toBeInTheDocument();
});
useGlobalStateSpy.mockRestore();
useDatasourceSpy.mockRestore();
});
test('should render CircleComparationItem with an Inactive Default Circle', async () => {
(fetch as FetchMock)
.mockResponseOnce(JSON.stringify(defaultCircleWithoutDeployment))
.mockResponseOnce(JSON.stringify(defaultCircleWithoutDeployment));
const handleChange = jest.fn();
const updateCircle = jest.fn();
render(
<CirclesComparationItem id={props.id} onChange={handleChange} updateCircle={updateCircle} circlesListResponse={null} />
);
const dropdownIcon = await screen.findByTestId('icon-vertical-dots');
expect(dropdownIcon).toBeInTheDocument();
act(() => userEvent.click(dropdownIcon));
const dropdownActions = screen.getByTestId('dropdown-actions');
await waitFor(() => {
expect(dropdownActions).toBeInTheDocument();
expect(screen.queryByTestId('dropdown-item-undeploy-Undeploy')).not.toBeInTheDocument();
});
const iconEdit = await screen.findByTestId('icon-edit');
expect(iconEdit).toBeInTheDocument();
act(() => userEvent.click(iconEdit));
const iconBack = await screen.findByTestId('icon-arrow-left');
expect(iconBack).toBeInTheDocument();
});
test('should try to delete a circle', async () => {
(fetch as FetchMock)
.mockResponseOnce(JSON.stringify(circleWithoutDeployment))
.mockResponseOnce(JSON.stringify(circleWithoutDeployment));
const handleChange = jest.fn();
const updateCircle = jest.fn();
saveWorkspace({id: '1', name: 'workspace 1', permissions: ['circles_write']});
setUserAbilities();
render(
<AllTheProviders>
<CirclesComparationItem id={props.id} onChange={handleChange} updateCircle={updateCircle} circlesListResponse={null} />
</AllTheProviders>
);
const dropdownIcon = await screen.findByTestId('icon-vertical-dots');
expect(dropdownIcon).toBeInTheDocument();
act(() => userEvent.click(dropdownIcon));
const deleteButton = await screen.findByTestId('dropdown-item-delete-Delete');
expect(deleteButton).toBeInTheDocument();
const deleteButtonText = await screen.findByText('Delete');
expect(deleteButtonText).toHaveStyle(`color: ${COLOR_SANTAS_GREY}`);
expect(deleteButtonText).not.toHaveStyle('opacity: 0.7');
await act(async () => userEvent.click(deleteButton));
const deleteCircleModal = screen.getByTestId('modal-trigger');
expect(deleteCircleModal).toBeInTheDocument();
});
test('should disable delete button and show tooltip when is an Active Default Circle', async () => {
jest.spyOn(StateHooks, 'useGlobalState').mockImplementation(() => ({
item: {
id: '123-workspace',
status: WORKSPACE_STATUS.COMPLETE
},
status: 'resolved'
}));
jest.spyOn(DatasourceHooks, 'useDatasource').mockReturnValueOnce({
responseAll: [],
getAll: jest.fn
});
(fetch as FetchMock)
.mockResponseOnce(JSON.stringify(defaultCircle))
.mockResponseOnce(JSON.stringify(defaultCircle));
const handleChange = jest.fn();
const updateCircle = jest.fn();
render(
<CirclesComparationItem id={props.id} onChange={handleChange} updateCircle={updateCircle} circlesListResponse={null} />
);
const DropdownIcon = await screen.findByTestId('icon-vertical-dots');
expect(DropdownIcon).toBeInTheDocument();
act(() => userEvent.click(DropdownIcon));
const deleteButton = await screen.findByTestId('dropdown-item-delete-Delete');
expect(deleteButton).toBeInTheDocument();
const deleteButtonText = await screen.findByText('Delete');
expect(deleteButtonText).toHaveStyle(`color: ${COLOR_COMET}`);
userEvent.hover(deleteButton);
expect(screen.getByText('Default circle is deployed to all')).toBeInTheDocument();
expect(screen.getByText('users, so it cannot be deleted.')).toBeInTheDocument();
});
test('should disable delete button and show tooltip when is an Inactive Default Circle', async () => {
(fetch as FetchMock)
.mockResponseOnce(JSON.stringify(defaultCircleWithoutDeployment))
.mockResponseOnce(JSON.stringify(defaultCircleWithoutDeployment));
const handleChange = jest.fn();
const updateCircle = jest.fn();
render(
<CirclesComparationItem id={props.id} onChange={handleChange} updateCircle={updateCircle} circlesListResponse={null} />
);
const dropdownIcon = await screen.findByTestId('icon-vertical-dots');
expect(dropdownIcon).toBeInTheDocument();
act(() => userEvent.click(dropdownIcon));
const deleteButton = await screen.findByTestId('dropdown-item-delete-Delete');
expect(deleteButton).toBeInTheDocument();
const deleteButtonText = await screen.findByText('Delete');
expect(deleteButtonText).toHaveStyle(`color: ${COLOR_COMET}`);
userEvent.hover(deleteButton);
expect(screen.getByText('Default circle cannot be deleted.')).toBeInTheDocument();
});
test('should show a tooltip when permission READER tries to delete a circle', async () => {
(fetch as FetchMock)
.mockResponseOnce(JSON.stringify(circle))
.mockResponseOnce(JSON.stringify(circle));
const handleChange = jest.fn();
const updateCircle = jest.fn();
saveWorkspace({id: '1', name: 'workspace 1', permissions: ['circles_read']});
setUserAbilities();
render(
<AllTheProviders>
<CirclesComparationItem id={props.id} onChange={handleChange} updateCircle={updateCircle} circlesListResponse={null} />
</AllTheProviders>
);
const dropdownIcon = await screen.findByTestId('icon-vertical-dots');
expect(dropdownIcon).toBeInTheDocument();
act(() => userEvent.click(dropdownIcon));
const deleteButton = await screen.findByTestId('dropdown-item-delete-Delete');
expect(deleteButton).toBeInTheDocument();
userEvent.hover(deleteButton);
expect(screen.getByText(/Not allowed/)).toBeInTheDocument();
});
test('should disable delete button and show tooltip when is an Active Circle', async () => {
jest.spyOn(StateHooks, 'useGlobalState').mockImplementation(() => ({
item: {
id: '123-workspace',
status: WORKSPACE_STATUS.COMPLETE
},
status: 'resolved'
}));
jest.spyOn(DatasourceHooks, 'useDatasource').mockReturnValueOnce({
responseAll: [],
getAll: jest.fn
});
(fetch as FetchMock)
.mockResponseOnce(JSON.stringify(circle))
.mockResponseOnce(JSON.stringify(circle));
const handleChange = jest.fn();
const updateCircle = jest.fn();
saveProfile({ id: '123', name: 'charles admin', email: 'charlesadmin@admin', root: true});
saveWorkspace({id: '1', name: 'workspace 1', permissions: ['circles_write']});
setUserAbilities();
render(
<AllTheProviders>
<CirclesComparationItem id={props.id} onChange={handleChange} updateCircle={updateCircle} circlesListResponse={null} />
</AllTheProviders>
);
const dropdownIcon = await screen.findByTestId('icon-vertical-dots');
expect(dropdownIcon).toBeInTheDocument();
act(() => userEvent.click(dropdownIcon));
const deleteButton = await screen.findByTestId('dropdown-item-delete-Delete');
expect(deleteButton).toBeInTheDocument();
const deleteButtonText = await screen.findByText('Delete');
expect(deleteButtonText).toHaveStyle(`color: ${COLOR_COMET}`);
userEvent.hover(deleteButton);
await waitFor(() => expect(screen.getByText(/Active circle cannot be deleted,/)).toBeInTheDocument());
expect(screen.getByText(/you can undeploy first and then/)).toBeInTheDocument();
expect(screen.getByText(/delete this circle./)).toBeInTheDocument();
}); | the_stack |
import * as fs from "fs";
import * as nearley from "nearley";
import grammar from "parser/SubstanceParser";
import * as path from "path";
import { PenroseError } from "types/errors";
import { Result, showError, showType } from "utils/Error";
import { compileDomain } from "./Domain";
import { compileSubstance, prettySubstance } from "./Substance";
import { SubstanceEnv } from "types/substance";
import { Env } from "types/domain";
const printError = false;
const saveContexts = false;
const outputDir = "/tmp/contexts";
const subPaths = [
// "linear-algebra-domain/twoVectorsPerp.sub",
["set-theory-domain/setTheory.dsl", "set-theory-domain/tree.sub"],
["set-theory-domain/setTheory.dsl", "set-theory-domain/continuousmap.sub"],
["set-theory-domain/setTheory.dsl", "set-theory-domain/twosets-simple.sub"],
["set-theory-domain/setTheory.dsl", "set-theory-domain/multisets.sub"],
["set-theory-domain/setTheory.dsl", "set-theory-domain/nested.sub"],
// "hyperbolic-domain/hyperbolic-example.sub",
// "geometry-domain/pythagorean-theorem-sugared.sub",
// "mesh-set-domain/DomainInterop.sub",
];
const hasVars = (env: Env, vars: [string, string][]) => {
vars.map(([name, type]: [string, string]) => {
expect(env.vars.has(name)).toBe(true);
expect(showType(env.vars.get(name)!)).toEqual(type);
});
};
const domainProg = `
type Set
type OpenSet
type Vector
type List('T)
type Tuple('T, 'U)
type Point
OpenSet <: Set
constructor Subset: Set A * Set B -> Set
constructor Intersection: Set A * Set B -> Set
constructor Cons ['X] : 'X head * List('X) tail -> List('X)
constructor Nil['X] -> List('X)
constructor CreateTuple['T, 'U] : 'T fst * 'U snd -> Tuple('T, 'U)
function AddPoint : Point p * Set s1 -> Set
predicate Not : Prop p1
predicate Both : Prop p1 * Prop p2
predicate Empty : Set s
predicate Intersecting : Set s1 * Set s2
predicate IsSubset : Set s1 * Set s2
`;
const domainProgWithPrelude = `
type Set
type OpenSet
type Vector
type List('T)
type Tuple('T, 'U)
type Point
OpenSet <: Set
constructor Subset: Set A * Set B -> Set
constructor Intersection: Set A * Set B -> Set
constructor Cons ['X] : 'X head * List('X) tail -> List('X)
constructor Nil['X] -> List('X)
constructor CreateTuple['T, 'U] : 'T fst * 'U snd -> Tuple('T, 'U)
function AddPoint : Point p * Set s1 -> Set
predicate Not : Prop p1
predicate Both : Prop p1 * Prop p2
predicate Empty : Set s
predicate Intersecting : Set s1 * Set s2
predicate IsSubset : Set s1 * Set s2
value X: Set
`;
const envOrError = (prog: string): Env => {
const res = compileDomain(prog);
if (res.isErr()) fail(showError(res.error));
return res.value;
};
const compileOrError = (prog: string, env: Env) => {
const res = compileSubstance(prog, env);
if (res.isOk()) {
return;
} else {
fail(`unexpected error ${showError(res.error)}`);
}
};
let parser: nearley.Parser;
beforeEach(() => {
// NOTE: Neither `feed` nor `finish` will reset the parser state. Therefore recompiling before each unit test
parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
});
describe("Common", () => {
test("empty program", () => {
const prog = ``;
const env = envOrError(domainProg);
const res = compileSubstance(prog, env);
expect(res.isOk()).toBe(true);
});
test("trailing comment", () => {
const prog = `
Set A
Set B
Set C
Set D
-- Set E`;
const env = envOrError(domainProg);
const res = compileSubstance(prog, env);
expect(res.isOk()).toBe(true);
});
test("preludes", () => {
const env = envOrError(domainProgWithPrelude);
const prog = `
Set A, B, C
List(Set) l
OpenSet D
A := D
`;
const res = compileSubstance(prog, env);
expect(res.isOk()).toBe(true);
if (res.isOk()) {
hasVars(res.value[1], [
["A", "Set"],
["X", "Set"], // defined in prelude
["l", "List(Set)"],
]);
}
});
});
describe("Postprocess", () => {
test("labels", () => {
const prog = `
Set A, B, C, D, E
AutoLabel All
Label A $\\vec{A}$
Label B $B_1$
NoLabel D, E
`;
const env = envOrError(domainProg);
const res = compileSubstance(prog, env);
if (res.isOk()) {
const expected = [
["A", "\\vec{A}"],
["B", "B_1"],
["C", "C"],
["D", ""],
["E", ""],
];
const labelMap = res.value[0].labels;
expected.map(([id, value]) =>
expect(labelMap.get(id)!.unwrapOr("")).toEqual(value)
);
} else {
fail("Unexpected error when processing labels: " + showError(res.error));
}
});
});
describe("Check statements", () => {
test("decls", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B, C
List(Set) l
OpenSet D
A := D
`;
const res = compileSubstance(prog, env);
expect(res.isOk()).toBe(true);
if (res.isOk()) {
hasVars(res.value[1], [
["A", "Set"],
["l", "List(Set)"],
]);
}
});
test("decl bind", () => {
const env = envOrError(domainProg);
const prog = `
OpenSet D
Set B, C
Set A := D
Set E := Subset(B, C)
`;
const res = compileSubstance(prog, env);
expect(res.isOk()).toBe(true);
if (res.isOk()) {
expect(res.value[1].constructorsBindings.get("E")![0].name.value).toEqual(
"Subset"
);
// TODO: not caching var bindings for now. Add to checker if needed
// expect(res.value[1].bindings.get("A")![0].name.value).toEqual("Subset");
hasVars(res.value[1], [
["A", "Set"],
["E", "Set"],
["D", "OpenSet"],
]);
}
});
test("func: function", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B
Point p
B := AddPoint(p, B)
`;
const res = compileSubstance(prog, env);
if (res.isOk()) {
hasVars(res.value[1], [
["A", "Set"],
["B", "Set"],
["p", "Point"],
]);
} else {
fail(`unexpected error ${showError(res.error)}`);
}
});
test("func: constructor", () => {
const env = envOrError(domainProg);
const prog = `
List(Set) l, nil
nil := Nil()
Set A
l := Cons(A, nil)
`;
const res = compileSubstance(prog, env);
if (res.isOk()) {
hasVars(res.value[1], [
["A", "Set"],
["l", "List(Set)"],
["nil", "List(Set)"],
]);
} else {
fail(`unexpected error ${showError(res.error)}`);
}
});
test("deconstructor: plain types", () => {
const prog = `
Set A, B, C, D, E
C := Subset(A, B)
D := C.A
E := C.B
`;
const env = envOrError(domainProg);
compileOrError(prog, env);
});
test("predicates: non-nesting", () => {
const prog = `
Set A, B, C, D, E
C := Intersection(A, B)
Empty(C)
IsSubset(D, E)
IsSubset(D, A)
IsSubset(Subset(D, E), A) -- anon. constructor
`;
const env = envOrError(domainProg);
compileOrError(prog, env);
});
test("predicates: nesting", () => {
const prog = `
Set A, B, C, D, E
C := Intersection(A, B)
Not(Empty(C))
Not(IsSubset(D, E))
Not(IsSubset(Subset(D, E), A)) -- anon. constructor
Both(IsSubset(A, B), IsSubset(C, D))
`;
const env = envOrError(domainProg);
compileOrError(prog, env);
});
test("predicates: nesting", () => {
const prog = `
Set A, B, C
Label A $\\vec{A}$
Label B $B_1$
AutoLabel All
AutoLabel B, C
NoLabel B, C
`;
const env = envOrError(domainProg);
compileOrError(prog, env);
});
});
describe("Errors", () => {
const expectErrorOf = (
result: Result<[SubstanceEnv, Env], PenroseError>,
errorType: string
) => {
if (result.isErr()) {
if (printError) console.log(showError(result.error));
expect(result.error.tag).toBe(errorType);
} else {
fail(`Error ${errorType} was suppoed to occur.`);
}
};
test("parse error", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B, C ;;; shouldn't parse
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "ParseError");
});
test("duplicate name error", () => {
const env = envOrError(domainProg);
const prog = `
Set A
Point A
AutoLabel All
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "DuplicateName");
});
test("type not found", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B, C
List(Set) l
Alien a
NotExistentType b
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "TypeNotFound");
});
test("var not found", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B, C
D := Subset(B, C)
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "VarNotFound");
});
test("type mismatch: var", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B
Vector v
A := B -- ok
A := v -- error
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "TypeMismatch");
});
test("func: arg length mismatch", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B, C
C := Subset(A) -- error
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "ArgLengthMismatch");
});
test("func: arg type mismatch", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B, C
Vector v
C := Subset(A, B) -- ok
C := Subset(A, v) -- error
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "TypeMismatch");
});
test("func: output type mismatch", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B, C
Vector v
C := Subset(A, B) -- ok
v := Subset(A, B) -- error
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "TypeMismatch");
});
// TODO: fix typeconstructor check and pass this test
test("func: type argument mismatch", () => {
const env = envOrError(domainProg);
const prog = `
-- type Tuple('T, 'U)
-- constructor CreateTuple['T, 'U] : 'T fst * 'U snd -> Tuple('T, 'U)
List(Set) nil
Tuple(Set, Set) t -- Maybe an error?
t := CreateTuple(nil, nil) -- Definitely an error
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "TypeMismatch");
});
test("func: type argument mismatch 2", () => {
const env = envOrError(domainProg);
const prog = `
-- Substance program for type checking
List(Set) l, nil
nil := Nil()
Set A
l := Cons(nil, A)
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "TypeMismatch");
});
test("func: argument of too general type", () => {
const env = envOrError(domainProg);
const prog = `
List(OpenSet) l, nil
nil := Nil()
Set A
l := Cons(A, nil)
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "TypeMismatch");
});
test("unbound field access", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B
B := A.field
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "DeconstructNonconstructor");
});
test("unbound field access of a function", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B,
Point p, q
B := AddPoint(p, A)
q := B.p1 -- although the function has named args, one still cannot deconstruct functions. Only constructors are okay.
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "DeconstructNonconstructor");
});
test("wrong return type of anon constructor in predicate", () => {
const env = envOrError(domainProg);
const prog = `
List(Set) nil
nil := Nil()
OpenSet A
IsSubset(nil, A) -- error because nil is not a Set
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "TypeMismatch");
});
test("unexpected var when nested pred is expected", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B
Not(IsSubset(A, B)) -- ok
Not(Intersection(A, B))
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "UnexpectedExprForNestedPred");
});
test("variables not found in label statements", () => {
const env = envOrError(domainProg);
const prog = `
Set A, B
Label D $\\vec{d}$
`;
const res = compileSubstance(prog, env);
expectErrorOf(res, "VarNotFound");
});
});
describe("Subtypes", () => {
test("func argument subtypes", () => {
const env = envOrError(domainProg);
const prog = `
List(Set) l, nil
nil := Nil()
OpenSet A
l := Cons(A, nil)
`;
compileOrError(prog, env);
});
test("func argument parametrized subtypes", () => {
const env = envOrError(domainProg);
const prog = `
List(Set) l
List(OpenSet) nil
nil := Nil()
OpenSet A
l := Cons(A, nil)
`;
compileOrError(prog, env);
});
});
describe("Real Programs", () => {
// create output folder
if (saveContexts && !fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
subPaths.map(([domainPath, examplePath]) => {
const domFile = path.join("../../examples/", domainPath);
const subFile = path.join("../../examples/", examplePath);
const domProg = fs.readFileSync(domFile, "utf8");
const subProg = fs.readFileSync(subFile, "utf8");
test(examplePath, () => {
// do testing
const env = envOrError(domProg);
const res = compileSubstance(subProg, env);
expect(res.isOk()).toBe(true);
// write to output folder
if (res.isOk() && saveContexts) {
const domainName = path.basename(domainPath, ".dsl");
const exampleName = path.basename(examplePath, ".sub");
const envPath = path.join(outputDir, domainName + ".env.json");
const subenvPath = path.join(outputDir, exampleName + ".env.json");
fs.writeFileSync(subenvPath, JSON.stringify(res.value[0]), "utf8");
fs.writeFileSync(envPath, JSON.stringify(res.value[1]), "utf8");
}
});
});
});
describe("Pretty printer", () => {
test("decls and args", () => {
const env = envOrError(domainProg);
const prog = `Set A
Set B
Set C
Set D
Set E
Vector v
C := Subset(A, B)
D := C.A
E := C.B
List(Set) l
List(OpenSet) nil
OpenSet Z
nil := Nil()
l := Cons(Z, nil)
Empty(C)
IsSubset(D, E)
IsSubset(D, A)
IsSubset(A, B) <-> IsSubset(B, C)
Subset(A, B) = Subset(B, C)
AutoLabel All
Label A $\\vec{A}$
Label B $B_1$
NoLabel D, E`;
const res = compileSubstance(prog, env);
sameAsSource(prog, res);
});
});
const sameAsSource = (
source: string,
res: Result<[SubstanceEnv, Env], PenroseError>
) => {
if (res.isOk()) {
const ast = res.value[0].ast;
const strFromAST = prettySubstance(ast);
expect(strFromAST).toEqual(source);
} else {
fail(`unexpected error ${showError(res.error)}`);
}
}; | the_stack |
import { Component, h, Host, Prop } from '@stencil/core';
import {
ResponsiveContainer,
Heading,
Button,
PrismicRichText,
PrismicResponsiveImage,
Paragraph,
} from '@ionic-internal/ionic-ds';
import { getAssetPath, State } from '@stencil/core/internal';
@Component({
tag: 'enterprise-page',
styleUrl: 'enterprise-page.scss',
scoped: true,
assetsDirs: ['./assets-enterprise-page'],
})
export class EnterprisePage {
@Prop() data: any;
@State() ebookModalOpen = false;
render() {
const {
Top,
Companies,
Native,
Ebook,
Plugins,
Security,
Delivery,
SupportGuidance,
Features,
Demo,
Editions,
} = this;
return (
<Host>
<meta-tags />
<enterprise-subnav />
<Top />
<Companies />
<Native />
<Ebook />
{/* <Approach /> */}
<Plugins />
<Security />
<Delivery />
<SupportGuidance />
<Features />
<Editions />
<Demo />
<pre-footer />
<capacitor-site-footer />
</Host>
);
}
Top = () => {
const { top } = this.data;
const { title, text, cta_1, background } = top[0];
return (
<section id="top">
<PrismicResponsiveImage image={background} class="background" />
<ResponsiveContainer>
<div class="heading-group">
<Heading level={1}>{title}</Heading>
<Paragraph level={2}>{text}</Paragraph>
<div class="cta-row">
<Button anchor href="#demo" kind="round">
{cta_1}
<span class="arrow"> -></span>
</Button>
{/* <a href="https://ionic.io/contact/sales" class="link btn-link">
{cta_2}
<span class="arrow"> -></span>
</a> */}
</div>
</div>
</ResponsiveContainer>
</section>
);
};
Companies = () => {
const { companies } = this.data;
const companies__list = [
['nationwide', '34x42'],
['target', '31x42'],
['burger-king', '32x36'],
['home-depot', '34x34'],
['nbc', '51x30'],
['microsoft', '35x35'],
['amtrak', '58x25'],
['general-electric', '35x35'],
];
return (
<section id="companies">
<ResponsiveContainer>
<Heading level={2}>{companies}</Heading>
<div class="logos">
<div class="row1">
{companies__list.slice(0, 4).map((stats, i) => (
<img
width={stats[1].split('x')[0]}
height={stats[1].split('x')[1]}
src={getAssetPath(
`./assets-enterprise-page/companies/${i}@2x.png`,
)}
loading="lazy"
alt={`${stats[0]} logo`}
/>
))}
</div>
<div class="row2">
{companies__list.slice(0, 4).map((stats, i) => (
<img
width={stats[1].split('x')[0]}
height={stats[1].split('x')[1]}
src={getAssetPath(
`./assets-enterprise-page/companies/${
i + companies__list.length / 2
}@2x.png`,
)}
loading="lazy"
alt={`${stats[0]} logo`}
/>
))}
</div>
</div>
</ResponsiveContainer>
</section>
);
};
Native = () => {
const { native, native__list } = this.data;
const { supertext, title, subtext } = native[0];
const icons = [
['three blocks with up arrow', '64x64'],
['fingerprint icon with lock symbol', '76x64'],
['clock icon with up arrow', '64x64'],
];
return (
<ResponsiveContainer id="native" as="section">
<div class="heading-group">
<p class="ui-heading-6">
<sup>{supertext}</sup>
</p>
<PrismicRichText richText={title} />
<Paragraph level={2}>{subtext}</Paragraph>
</div>
<ul class="list">
{native__list.map(({ title, text }, i) => (
<li key={icons[i][0]}>
<img
width={icons[i][1].split('x')[0]}
height={icons[i][1].split('x')[1]}
src={getAssetPath(
`./assets-enterprise-page/native/${i}@2x.png`,
)}
loading="lazy"
/>
<Heading level={4} as="h3">
{title}
</Heading>
<Paragraph leading="prose">{text}</Paragraph>
</li>
))}
</ul>
</ResponsiveContainer>
);
};
Ebook = () => {
const { ebook } = this.data;
const { text, cta, background, book } = ebook[0];
return (
<section id="ebook">
<ResponsiveContainer>
<site-modal
open={this.ebookModalOpen}
onModalClose={() => (this.ebookModalOpen = false)}
>
<Heading level={2}>
Building Cross-platform Apps with Capacitor
</Heading>
<hubspot-form formId="9151dc0b-42d9-479f-b7b8-649e0e7bd1bc" />
</site-modal>
<div class="wrapper">
<PrismicResponsiveImage image={background} class="background" />
<div class="content">
<div class="image-wrapper">
<PrismicResponsiveImage image={book} />
</div>
<div class="heading-group">
<PrismicRichText paragraphLevel={1} richText={text} />
<Button
kind="round"
size="md"
onClick={() => (this.ebookModalOpen = true)}
>
{cta} <span class="arrow"> -></span>
</Button>
</div>
</div>
</div>
</ResponsiveContainer>
</section>
);
};
// Approach = () => {
// const {
// approach,
// approach_traditional,
// approach_traditional__list,
// approach_web,
// approach_web__list,
// } = this.data;
// const { supertext, title } = approach[0];
// return (
// <section id="approach">
// <ResponsiveContainer>
// <div class="heading-group">
// <p class="ui-heading-6">
// <sup>{supertext}</sup>
// </p>
// <PrismicRichText richText={title} />
// </div>
// <div class="split">
// <article class="traditional column">
// <Heading>{approach_traditional[0]['title']}</Heading>
// <Paragraph>{approach_traditional[0]['text']}</Paragraph>
// <PrismicResponsiveImage
// image={approach_traditional[0]['image']}
// />
// <div class="list">
// <Heading level={4}>
// {approach_traditional[0]['subtitle']}
// </Heading>
// <ul>
// {approach_traditional__list.map(({ text, icon }) => (
// <li>
// <PrismicResponsiveImage image={icon} />
// <Paragraph>{text}</Paragraph>
// </li>
// ))}
// </ul>
// </div>
// </article>
// <article class="web column">
// <Heading>{approach_web[0]['title']}</Heading>
// <Paragraph>{approach_web[0]['text']}</Paragraph>
// <PrismicResponsiveImage image={approach_web[0]['image']} />
// <div class="list">
// <Heading level={4}>{approach_web[0]['subtitle']}</Heading>
// <ul>
// {approach_web__list.map(({ text, icon }) => (
// <li>
// <PrismicResponsiveImage image={icon} />
// <Paragraph>{text}</Paragraph>
// </li>
// ))}
// </ul>
// </div>
// </article>
// </div>
// </ResponsiveContainer>
// </section>
// );
// };
Plugins = () => {
const { plugins } = this.data;
const { supertext, title, subtext, image } = plugins[0];
return (
<section id="plugins">
<ResponsiveContainer>
<div class="wrapper">
<div class="heading-group">
<p class="ui-heading-6">
<sup>{supertext}</sup>
</p>
<PrismicRichText richText={title} />
<Paragraph level={2}>{subtext}</Paragraph>
</div>
<div class="image-wrapper">
<PrismicResponsiveImage image={image} />
</div>
</div>
</ResponsiveContainer>
</section>
);
};
Security = () => {
const { security } = this.data;
const { supertext, title, subtext, image } = security[0];
return (
<section id="security">
<ResponsiveContainer>
<div class="wrapper">
<div class="image-wrapper">
<PrismicResponsiveImage image={image} />
</div>
<div class="heading-group">
<p class="ui-heading-6">
<sup>{supertext}</sup>
</p>
<PrismicRichText richText={title} />
<PrismicRichText richText={subtext} paragraphLevel={2} />
</div>
</div>
</ResponsiveContainer>
</section>
);
};
Delivery = () => {
const { delivery } = this.data;
const { supertext, title, subtext, image } = delivery[0];
return (
<section id="delivery">
<ResponsiveContainer>
<div class="wrapper">
<div class="heading-group">
<p class="ui-heading-6">
<sup>{supertext}</sup>
</p>
<PrismicRichText richText={title} />
<PrismicRichText richText={subtext} paragraphLevel={2} />
</div>
<div class="image-wrapper">
<PrismicResponsiveImage image={image} />
</div>
</div>
</ResponsiveContainer>
</section>
);
};
SupportGuidance = () => {
const { support_guidance } = this.data;
return (
<section id="support-guidance">
<ResponsiveContainer>
<div class="wrapper">
{support_guidance.map(({ image, title, text }) => (
<article>
<PrismicResponsiveImage image={image} />
<Heading level={3}>{title}</Heading>
<Paragraph level={2}>{text}</Paragraph>
</article>
))}
</div>
</ResponsiveContainer>
</section>
);
};
Features = () => {
const { features, features__list } = this.data;
const { supertext, title, subtext } = features[0];
return (
<section id="features">
<ResponsiveContainer>
<div class="wrapper">
<div class="heading-group">
<p class="ui-heading-6">
<sup>{supertext}</sup>
</p>
<PrismicRichText richText={title} />
<Paragraph level={2}>{subtext}</Paragraph>
</div>
<ul>
{features__list.map(({ icon, title, text }) => (
<li>
<div class="image-wrapper">
<PrismicResponsiveImage image={icon} />
</div>
<div>
<Heading level={4} as="h3">
{title}
</Heading>
<Paragraph>{text}</Paragraph>
</div>
</li>
))}
</ul>
</div>
</ResponsiveContainer>
</section>
);
};
Editions = () => {
const { editions } = this.data;
const { supertext, title, paragraph_1, paragraph_2, cta_1 } = editions[0];
const images = [
['burger-king', '36x38'],
['fidelity', '113x32'],
['hr-block', '32x32'],
['communo', '102x24'],
['usaa', '27x32'],
['ibm', '64x26'],
['bcbs', '62x32'],
['test-kitchen', '77x28'],
['home-depot', '32x32'],
];
return (
<section id="editions">
<ResponsiveContainer>
<div class="wrapper">
<div class="heading-group">
<p class="ui-heading-6">
<sup>{supertext}</sup>
</p>
<PrismicRichText richText={title} />
<PrismicRichText richText={paragraph_1} paragraphLevel={2} />
<PrismicRichText richText={paragraph_2} paragraphLevel={2} />
<div class="cta-row">
<Button href="#demo" anchor kind="round">
{cta_1}
<span class="arrow"> -></span>
</Button>
{/* <a href="https://ionic.io/contact/sales" class="link btn-link">
{cta_2}
<span class="arrow"> -></span>
</a> */}
</div>
</div>
<div class="logos">
<div class="row0">
{images.slice(0, 3).map((stats, i) => (
<div class="image-wrapper">
<img
src={getAssetPath(
`./assets-enterprise-page/editions/${i}@2x.png`,
)}
width={stats[1].split('x')[0]}
height={stats[1].split('x')[1]}
loading="lazy"
/>
</div>
))}
</div>
<div class="row1">
{images.slice(3, 6).map((stats, i) => (
<div class="image-wrapper">
<img
src={getAssetPath(
`./assets-enterprise-page/editions/${i + 3}@2x.png`,
)}
width={stats[1].split('x')[0]}
height={stats[1].split('x')[1]}
loading="lazy"
/>
</div>
))}
</div>
<div class="row2">
{images.slice(6, 9).map((stats, i) => (
<div class="image-wrapper">
<img
src={getAssetPath(
`./assets-enterprise-page/editions/${i + 6}@2x.png`,
)}
width={stats[1].split('x')[0]}
height={stats[1].split('x')[1]}
loading="lazy"
/>
</div>
))}
</div>
</div>
</div>
</ResponsiveContainer>
</section>
);
};
Demo = () => {
const { demo } = this.data;
const { supertext, title } = demo[0];
return (
<section id="demo">
<ResponsiveContainer>
<div class="heading-group">
<p class="ui-heading-6">
<sup>{supertext}</sup>
</p>
<Heading level={2}>{title}</Heading>
</div>
<hubspot-form formId="d0019a78-110e-4d28-b356-56357b4abe4b" />
</ResponsiveContainer>
</section>
);
};
} | the_stack |
import {
Address,
isTimestampTimeout,
SendTransaction,
SwapAbortTransaction,
SwapClaimTransaction,
SwapOfferTransaction,
UnsignedTransaction,
} from "@iov/bcp";
import { fromHex, toUtf8 } from "@iov/encoding";
import { encodeAmount, encodeInt, encodeNumericId, encodeString } from "./encodinghelpers";
import * as codecImpl from "./generated/codecimpl";
import {
AccountConfiguration,
AccountMsgFee,
AddAccountCertificateTx,
BnsdTxMsg,
ChainAddressPair,
CreateEscrowTx,
CreateMultisignatureTx,
CreateProposalTx,
DeleteAccountCertificateTx,
DeleteAccountTx,
DeleteAllAccountsTx,
DeleteDomainTx,
isBnsTx,
isCreateTextResolutionAction,
isExecuteMigrationAction,
isExecuteProposalBatchAction,
isReleaseEscrowAction,
isSendAction,
isSetMsgFeeAction,
isSetValidatorsAction,
isUpdateElectionRuleAction,
isUpdateElectorateAction,
Participant,
RegisterAccountTx,
RegisterDomainTx,
RegisterUsernameTx,
ReleaseEscrowTx,
RenewAccountTx,
RenewDomainTx,
ReplaceAccountMsgFeesTx,
ReplaceAccountTargetsTx,
ReturnEscrowTx,
TransferAccountTx,
TransferDomainTx,
TransferUsernameTx,
UpdateAccountConfigurationTx,
UpdateEscrowPartiesTx,
UpdateMultisignatureTx,
UpdateTargetsOfUsernameTx,
Validators,
VoteOption,
VoteTx,
} from "./types";
import { decodeBnsAddress } from "./util";
const maxMemoLength = 128;
function encodeMemo(data: string | undefined): string | null {
if (data && toUtf8(data).length > maxMemoLength) {
throw new Error(`Invalid memo length: maximum ${maxMemoLength} bytes`);
}
return encodeString(data);
}
function encodeParticipants(
participants: readonly Participant[],
// tslint:disable-next-line:readonly-array
): codecImpl.multisig.IParticipant[] {
return participants.map(
(participant): codecImpl.multisig.IParticipant => ({
signature: decodeBnsAddress(participant.address).data,
weight: participant.weight,
}),
);
}
// Token sends
function encodeSendTransaction(tx: SendTransaction): BnsdTxMsg {
return {
cashSendMsg: codecImpl.cash.SendMsg.create({
metadata: { schema: 1 },
source: decodeBnsAddress(tx.sender).data,
destination: decodeBnsAddress(tx.recipient).data,
amount: encodeAmount(tx.amount),
memo: encodeMemo(tx.memo),
}),
};
}
// Atomic swaps
function encodeSwapOfferTx(tx: SwapOfferTransaction): BnsdTxMsg {
if (!isTimestampTimeout(tx.timeout)) {
throw new Error("Got unsupported timeout type");
}
return {
aswapCreateMsg: codecImpl.aswap.CreateMsg.create({
metadata: { schema: 1 },
source: decodeBnsAddress(tx.sender).data,
preimageHash: tx.hash,
destination: decodeBnsAddress(tx.recipient).data,
amount: tx.amounts.map(encodeAmount),
timeout: encodeInt(tx.timeout.timestamp),
memo: encodeMemo(tx.memo),
}),
};
}
function encodeSwapClaimTx(tx: SwapClaimTransaction): BnsdTxMsg {
return {
aswapReleaseMsg: codecImpl.aswap.ReleaseMsg.create({
metadata: { schema: 1 },
swapId: tx.swapId.data,
preimage: tx.preimage,
}),
};
}
function encodeSwapAbortTransaction(tx: SwapAbortTransaction): BnsdTxMsg {
return {
aswapReturnMsg: codecImpl.aswap.ReturnMsg.create({
metadata: { schema: 1 },
swapId: tx.swapId.data,
}),
};
}
// Usernames
function encodeChainAddressPair(pair: ChainAddressPair): codecImpl.username.IBlockchainAddress {
return {
blockchainId: pair.chainId,
address: pair.address,
};
}
function encodeRegisterUsernameTx(tx: RegisterUsernameTx): BnsdTxMsg {
if (!tx.username.endsWith("*iov")) {
throw new Error(
"Starting with IOV-Core 0.16, the username property needs to be a full human readable address, including the namespace suffix (e.g. '*iov').",
);
}
return {
usernameRegisterTokenMsg: {
metadata: { schema: 1 },
username: tx.username,
targets: tx.targets.map(encodeChainAddressPair),
},
};
}
function encodeUpdateTargetsOfUsernameTx(tx: UpdateTargetsOfUsernameTx): BnsdTxMsg {
return {
usernameChangeTokenTargetsMsg: {
metadata: { schema: 1 },
username: tx.username,
newTargets: tx.targets.map(encodeChainAddressPair),
},
};
}
function encodeTransferUsernameTx(tx: TransferUsernameTx): BnsdTxMsg {
return {
usernameTransferTokenMsg: {
metadata: { schema: 1 },
username: tx.username,
newOwner: decodeBnsAddress(tx.newOwner).data,
},
};
}
// Accounts
function encodeAccountConfiguration(configuration: AccountConfiguration): codecImpl.account.IConfiguration {
return {
metadata: { schema: 1 },
owner: decodeBnsAddress(configuration.owner).data,
validDomain: configuration.validDomain,
validName: configuration.validName,
validBlockchainId: configuration.validBlockchainId,
validBlockchainAddress: configuration.validBlockchainAddress,
domainRenew: configuration.domainRenew,
domainGracePeriod: configuration.domainGracePeriod,
};
}
function encodeUpdateAccountConfigurationTx(tx: UpdateAccountConfigurationTx): BnsdTxMsg {
return {
accountUpdateConfigurationMsg: {
metadata: { schema: 1 },
patch: encodeAccountConfiguration(tx.configuration),
},
};
}
function encodeAccountMsgFee(msgFee: AccountMsgFee): codecImpl.account.IAccountMsgFee {
return {
msgPath: msgFee.msgPath,
fee: encodeAmount(msgFee.fee),
};
}
function encodeRegisterDomainTx(tx: RegisterDomainTx): BnsdTxMsg {
return {
accountRegisterDomainMsg: {
metadata: { schema: 1 },
domain: tx.domain,
admin: decodeBnsAddress(tx.admin).data,
hasSuperuser: tx.hasSuperuser,
broker: tx.broker ? decodeBnsAddress(tx.broker).data : null,
msgFees: tx.msgFees.map(encodeAccountMsgFee),
accountRenew: tx.accountRenew,
},
};
}
function encodeTransferDomainTx(tx: TransferDomainTx): BnsdTxMsg {
return {
accountTransferDomainMsg: {
metadata: { schema: 1 },
domain: tx.domain,
newAdmin: decodeBnsAddress(tx.newAdmin).data,
},
};
}
function encodeRenewDomainTx(tx: RenewDomainTx): BnsdTxMsg {
return {
accountRenewDomainMsg: {
metadata: { schema: 1 },
domain: tx.domain,
},
};
}
function encodeDeleteDomainTx(tx: DeleteDomainTx): BnsdTxMsg {
return {
accountDeleteDomainMsg: {
metadata: { schema: 1 },
domain: tx.domain,
},
};
}
function encodeAccountChainAddress(
blockchainAddress: ChainAddressPair,
): codecImpl.account.IBlockchainAddress {
return {
blockchainId: blockchainAddress.chainId,
address: blockchainAddress.address,
};
}
function encodeRegisterAccountTx(tx: RegisterAccountTx): BnsdTxMsg {
return {
accountRegisterAccountMsg: {
metadata: { schema: 1 },
domain: tx.domain,
name: tx.name,
owner: decodeBnsAddress(tx.owner).data,
targets: tx.targets.map(encodeAccountChainAddress),
broker: tx.broker ? decodeBnsAddress(tx.broker).data : null,
},
};
}
function encodeTransferAccountTx(tx: TransferAccountTx): BnsdTxMsg {
return {
accountTransferAccountMsg: {
metadata: { schema: 1 },
domain: tx.domain,
name: tx.name,
newOwner: decodeBnsAddress(tx.newOwner).data,
},
};
}
function encodeReplaceAccountTargetsTx(tx: ReplaceAccountTargetsTx): BnsdTxMsg {
return {
accountReplaceAccountTargetsMsg: {
metadata: { schema: 1 },
domain: tx.domain,
name: tx.name,
newTargets: tx.newTargets.map(encodeAccountChainAddress),
},
};
}
function encodeDeleteAccountTx(tx: DeleteAccountTx): BnsdTxMsg {
return {
accountDeleteAccountMsg: {
metadata: { schema: 1 },
domain: tx.domain,
name: tx.name,
},
};
}
function encodeDeleteAllAccountsTx(tx: DeleteAllAccountsTx): BnsdTxMsg {
return {
accountFlushDomainMsg: {
metadata: { schema: 1 },
domain: tx.domain,
},
};
}
function encodeRenewAccountTx(tx: RenewAccountTx): BnsdTxMsg {
return {
accountRenewAccountMsg: {
metadata: { schema: 1 },
domain: tx.domain,
name: tx.name,
},
};
}
function encodeAddAccountCertificateTx(tx: AddAccountCertificateTx): BnsdTxMsg {
return {
accountAddAccountCertificateMsg: {
metadata: { schema: 1 },
domain: tx.domain,
name: tx.name,
certificate: tx.certificate,
},
};
}
function encodeReplaceAccountMsgFeesTx(tx: ReplaceAccountMsgFeesTx): BnsdTxMsg {
return {
accountReplaceAccountMsgFeesMsg: {
metadata: { schema: 1 },
domain: tx.domain,
newMsgFees: tx.newMsgFees.map(encodeAccountMsgFee),
},
};
}
function encodeDeleteAccountCertificateTx(tx: DeleteAccountCertificateTx): BnsdTxMsg {
return {
accountDeleteAccountCertificateMsg: {
metadata: { schema: 1 },
domain: tx.domain,
name: tx.name,
certificateHash: tx.certificateHash,
},
};
}
// Multisignature contracts
function encodeCreateMultisignatureTx(tx: CreateMultisignatureTx): BnsdTxMsg {
return {
multisigCreateMsg: {
metadata: { schema: 1 },
participants: encodeParticipants(tx.participants),
activationThreshold: tx.activationThreshold,
adminThreshold: tx.adminThreshold,
},
};
}
function encodeUpdateMultisignatureTx(tx: UpdateMultisignatureTx): BnsdTxMsg {
return {
multisigUpdateMsg: {
metadata: { schema: 1 },
contractId: encodeNumericId(tx.contractId),
participants: encodeParticipants(tx.participants),
activationThreshold: tx.activationThreshold,
adminThreshold: tx.adminThreshold,
},
};
}
// Escrows
function encodeCreateEscrowTx(tx: CreateEscrowTx): BnsdTxMsg {
return {
escrowCreateMsg: {
metadata: { schema: 1 },
source: decodeBnsAddress(tx.sender).data,
arbiter: decodeBnsAddress(tx.arbiter).data,
destination: decodeBnsAddress(tx.recipient).data,
amount: tx.amounts.map(encodeAmount),
timeout: encodeInt(tx.timeout.timestamp),
memo: encodeMemo(tx.memo),
},
};
}
function encodeReleaseEscrowTx(tx: ReleaseEscrowTx): BnsdTxMsg {
return {
escrowReleaseMsg: {
metadata: { schema: 1 },
escrowId: encodeNumericId(tx.escrowId),
amount: tx.amounts.map(encodeAmount),
},
};
}
function encodeReturnEscrowTx(tx: ReturnEscrowTx): BnsdTxMsg {
return {
escrowReturnMsg: {
metadata: { schema: 1 },
escrowId: encodeNumericId(tx.escrowId),
},
};
}
function encodeUpdateEscrowPartiesTx(tx: UpdateEscrowPartiesTx): BnsdTxMsg {
const numPartiesToUpdate = [tx.sender, tx.arbiter, tx.recipient].filter(Boolean).length;
if (numPartiesToUpdate !== 1) {
throw new Error(`Only one party can be updated at a time, got ${numPartiesToUpdate}`);
}
return {
escrowUpdatePartiesMsg: {
metadata: { schema: 1 },
escrowId: encodeNumericId(tx.escrowId),
source: tx.sender && decodeBnsAddress(tx.sender).data,
arbiter: tx.arbiter && decodeBnsAddress(tx.arbiter).data,
destination: tx.recipient && decodeBnsAddress(tx.recipient).data,
},
};
}
// Governance
// tslint:disable-next-line: readonly-array
function encodeValidators(validators: Validators): codecImpl.weave.IValidatorUpdate[] {
return Object.entries(validators).map(([key, { power }]) => {
const matches = key.match(/^ed25519_([0-9a-fA-F]{64})$/);
if (!matches) {
throw new Error("Got validators object key of unexpected format. Must be 'ed25519_<pubkey_hex>'");
}
return {
pubKey: { data: fromHex(matches[1]), type: "ed25519" },
power: power,
};
});
}
function encodeCreateProposalTx(tx: CreateProposalTx): BnsdTxMsg {
const { action } = tx;
let option: codecImpl.bnsd.IProposalOptions;
if (isCreateTextResolutionAction(action)) {
option = {
govCreateTextResolutionMsg: {
metadata: { schema: 1 },
resolution: action.resolution,
},
};
} else if (isExecuteProposalBatchAction(action)) {
option = {
executeProposalBatchMsg: {
messages: action.messages.map((message) => {
if (!isSendAction(message)) {
throw new Error("Only send actions are currently supported in proposal batch");
}
return {
sendMsg: {
metadata: { schema: 1 },
source: decodeBnsAddress(message.sender).data,
destination: decodeBnsAddress(message.recipient).data,
amount: encodeAmount(message.amount),
memo: encodeMemo(message.memo),
},
};
}),
},
};
} else if (isReleaseEscrowAction(action)) {
option = {
escrowReleaseMsg: {
metadata: { schema: 1 },
escrowId: encodeNumericId(action.escrowId),
amount: [encodeAmount(action.amount)],
},
};
} else if (isSetValidatorsAction(action)) {
option = {
validatorsApplyDiffMsg: {
metadata: { schema: 1 },
validatorUpdates: encodeValidators(action.validatorUpdates),
},
};
} else if (isUpdateElectorateAction(action)) {
option = {
govUpdateElectorateMsg: {
metadata: { schema: 1 },
electorateId: encodeNumericId(action.electorateId),
diffElectors: Object.entries(action.diffElectors).map(([address, { weight }]) => ({
address: decodeBnsAddress(address as Address).data,
weight: weight,
})),
},
};
} else if (isUpdateElectionRuleAction(action)) {
option = {
govUpdateElectionRuleMsg: {
metadata: { schema: 1 },
electionRuleId: encodeNumericId(action.electionRuleId),
threshold: action.threshold,
quorum: action.quorum,
votingPeriod: action.votingPeriod,
},
};
} else if (isSetMsgFeeAction(action)) {
option = {
msgfeeSetMsgFeeMsg: {
metadata: { schema: 1 },
msgPath: action.msgPath,
fee: encodeAmount(action.fee),
},
};
} else if (isExecuteMigrationAction(action)) {
if (!action.id) throw new Error("Migration ID must not be empty");
option = {
datamigrationExecuteMigrationMsg: {
metadata: { schema: 1 },
migrationId: action.id,
},
};
} else {
throw new Error("Got unsupported type of ProposalOption");
}
return {
govCreateProposalMsg: {
metadata: { schema: 1 },
title: tx.title,
rawOption: codecImpl.bnsd.ProposalOptions.encode(option).finish(),
description: tx.description,
electionRuleId: encodeNumericId(tx.electionRuleId),
startTime: tx.startTime,
author: decodeBnsAddress(tx.author).data,
},
};
}
function encodeVoteOption(option: VoteOption): codecImpl.gov.VoteOption {
switch (option) {
case VoteOption.Yes:
return codecImpl.gov.VoteOption.VOTE_OPTION_YES;
case VoteOption.No:
return codecImpl.gov.VoteOption.VOTE_OPTION_NO;
case VoteOption.Abstain:
return codecImpl.gov.VoteOption.VOTE_OPTION_ABSTAIN;
}
}
function encodeVoteTx(tx: VoteTx, strictMode: boolean): BnsdTxMsg {
if (strictMode) {
if (!tx.voter) throw new Error("In strict mode VoteTx.voter must be set");
}
return {
govVoteMsg: {
metadata: { schema: 1 },
proposalId: encodeNumericId(tx.proposalId),
selected: encodeVoteOption(tx.selection),
voter: tx.voter ? decodeBnsAddress(tx.voter).data : undefined,
},
};
}
export function encodeMsg(tx: UnsignedTransaction, strictMode = true): BnsdTxMsg {
if (!isBnsTx(tx)) {
throw new Error("Transaction is not a BNS transaction");
}
switch (tx.kind) {
// BCP: Token sends
case "bcp/send":
return encodeSendTransaction(tx);
// BCP: Atomic swaps
case "bcp/swap_offer":
return encodeSwapOfferTx(tx);
case "bcp/swap_claim":
return encodeSwapClaimTx(tx);
case "bcp/swap_abort":
return encodeSwapAbortTransaction(tx);
// BNS: Usernames
case "bns/register_username":
return encodeRegisterUsernameTx(tx);
case "bns/update_targets_of_username":
return encodeUpdateTargetsOfUsernameTx(tx);
case "bns/transfer_username":
return encodeTransferUsernameTx(tx);
// BNS: Accounts
case "bns/update_account_configuration":
return encodeUpdateAccountConfigurationTx(tx);
case "bns/register_domain":
return encodeRegisterDomainTx(tx);
case "bns/transfer_domain":
return encodeTransferDomainTx(tx);
case "bns/renew_domain":
return encodeRenewDomainTx(tx);
case "bns/delete_domain":
return encodeDeleteDomainTx(tx);
case "bns/register_account":
return encodeRegisterAccountTx(tx);
case "bns/transfer_account":
return encodeTransferAccountTx(tx);
case "bns/replace_account_targets":
return encodeReplaceAccountTargetsTx(tx);
case "bns/delete_account":
return encodeDeleteAccountTx(tx);
case "bns/delete_all_accounts":
return encodeDeleteAllAccountsTx(tx);
case "bns/renew_account":
return encodeRenewAccountTx(tx);
case "bns/add_account_certificate":
return encodeAddAccountCertificateTx(tx);
case "bns/replace_account_msg_fees":
return encodeReplaceAccountMsgFeesTx(tx);
case "bns/delete_account_certificate":
return encodeDeleteAccountCertificateTx(tx);
// BNS: Multisignature contracts
case "bns/create_multisignature_contract":
return encodeCreateMultisignatureTx(tx);
case "bns/update_multisignature_contract":
return encodeUpdateMultisignatureTx(tx);
// BNS: Escrows
case "bns/create_escrow":
return encodeCreateEscrowTx(tx);
case "bns/release_escrow":
return encodeReleaseEscrowTx(tx);
case "bns/return_escrow":
return encodeReturnEscrowTx(tx);
case "bns/update_escrow_parties":
return encodeUpdateEscrowPartiesTx(tx);
// BNS: Governance
case "bns/create_proposal":
return encodeCreateProposalTx(tx);
case "bns/vote":
return encodeVoteTx(tx, strictMode);
default:
throw new Error("Received transaction of unsupported kind.");
}
} | the_stack |
import * as p from "@bokehjs/core/properties"
import {div} from "@bokehjs/core/dom"
import {clone} from "@bokehjs/core/util/object"
import {isEqual} from "@bokehjs/core/util/eq"
import {HTMLBox} from "@bokehjs/models/layouts/html_box"
import {ColumnDataSource} from "@bokehjs/models/sources/column_data_source";
import {debounce} from "debounce"
import {deepCopy, isPlainObject, get, throttle} from "./util"
import {PanelHTMLBoxView, set_size} from "./layout"
interface PlotlyHTMLElement extends HTMLDivElement {
_fullLayout: any
layout: any;
on(event: 'plotly_relayout', callback: (eventData: any) => void): void;
on(event: 'plotly_relayouting', callback: (eventData: any) => void): void;
on(event: 'plotly_restyle', callback: (eventData: any) => void): void;
on(event: 'plotly_click', callback: (eventData: any) => void): void;
on(event: 'plotly_hover', callback: (eventData: any) => void): void;
on(event: 'plotly_clickannotation', callback: (eventData: any) => void): void;
on(event: 'plotly_selected', callback: (eventData: any) => void): void;
on(event: 'plotly_deselect', callback: () => void): void;
on(event: 'plotly_unhover', callback: () => void): void;
}
const filterEventData = (gd: any, eventData: any, event: string) => {
// Ported from dash-core-components/src/components/Graph.react.js
let filteredEventData: {[k: string]: any} = Array.isArray(eventData)? []: {};
if (event === "click" || event === "hover" || event === "selected") {
const points = [];
if (eventData === undefined || eventData === null) {
return null;
}
/*
* remove `data`, `layout`, `xaxis`, etc
* objects from the event data since they're so big
* and cause JSON stringify ciricular structure errors.
*
* also, pull down the `customdata` point from the data array
* into the event object
*/
const data = gd.data;
for (let i = 0; i < eventData.points.length; i++) {
const fullPoint = eventData.points[i];
let pointData: {[k: string]: any} = {};
for (let property in fullPoint) {
const val = fullPoint[property];
if (fullPoint.hasOwnProperty(property) &&
!Array.isArray(val) && !isPlainObject(val)) {
pointData[property] = val;
}
}
if (fullPoint !== undefined && fullPoint !== null) {
if(fullPoint.hasOwnProperty("curveNumber") &&
fullPoint.hasOwnProperty("pointNumber") &&
data[fullPoint["curveNumber"]].hasOwnProperty("customdata")) {
pointData["customdata"] =
data[fullPoint["curveNumber"]].customdata[
fullPoint["pointNumber"]
]
}
// specific to histogram. see https://github.com/plotly/plotly.js/pull/2113/
if (fullPoint.hasOwnProperty('pointNumbers')) {
pointData["pointNumbers"] = fullPoint.pointNumbers;
}
}
points[i] = pointData;
}
filteredEventData["points"] = points;
} else if (event === 'relayout' || event === 'restyle') {
/*
* relayout shouldn't include any big objects
* it will usually just contain the ranges of the axes like
* "xaxis.range[0]": 0.7715822247381828,
* "xaxis.range[1]": 3.0095292008680063`
*/
for (let property in eventData) {
if (eventData.hasOwnProperty(property)) {
filteredEventData[property] = eventData[property];
}
}
}
if (eventData.hasOwnProperty('range')) {
filteredEventData["range"] = eventData["range"];
}
if (eventData.hasOwnProperty('lassoPoints')) {
filteredEventData["lassoPoints"] = eventData["lassoPoints"];
}
return filteredEventData;
};
const _isHidden = (gd: any) => {
var display = window.getComputedStyle(gd).display;
return !display || display === 'none';
};
export class PlotlyPlotView extends PanelHTMLBoxView {
model: PlotlyPlot
_setViewport: Function
_settingViewport: boolean = false
_plotInitialized: boolean = false
_reacting: boolean = false
_relayouting: boolean = false
_layout_wrapper: PlotlyHTMLElement
_watched_sources: string[]
_end_relayouting = debounce(() => {
this._relayouting = false
}, 2000, false)
initialize(): void {
super.initialize()
this._layout_wrapper = <PlotlyHTMLElement>div({style: "height: 100%; width: 100%;"})
}
connect_signals(): void {
super.connect_signals();
const {data, data_sources, layout, relayout, restyle} = this.model.properties
this.on_change([data, data_sources, layout], () => {
const render_count = this.model._render_count
setTimeout(() => {
if (this.model._render_count === render_count)
this.model._render_count += 1;
}, 250)
});
this.on_change([relayout], () => {
if (this.model.relayout == null)
return
(window as any).Plotly.relayout(this._layout_wrapper, this.model.relayout)
this.model.relayout = null
})
this.on_change([restyle], () => {
if (this.model.restyle == null)
return
(window as any).Plotly.restyle(this._layout_wrapper, this.model.restyle.data, this.model.restyle.traces)
this.model.restyle = null
})
this.connect(this.model.properties.viewport_update_policy.change, () => {
this._updateSetViewportFunction()
});
this.connect(this.model.properties.viewport_update_throttle.change, () => {
this._updateSetViewportFunction()
});
this.connect(this.model.properties._render_count.change, () => {
this.plot()
});
this.connect(this.model.properties.frames.change, () => {
this.plot(true)
});
this.connect(this.model.properties.viewport.change, () => this._updateViewportFromProperty());
this.connect(this.model.properties.visibility.change, () => {
this.el.style.visibility = this.model.visibility ? 'visible' : 'hidden'
})
}
async render(): Promise<void> {
super.render()
this.el.style.visibility = this.model.visibility ? 'visible' : 'hidden'
this.el.appendChild(this._layout_wrapper)
await this.plot();
(window as any).Plotly.relayout(this._layout_wrapper, this.model.relayout)
}
_trace_data(): any {
const data = [];
for (let i = 0; i < this.model.data.length; i++)
data.push(this._get_trace(i, false))
return data
}
_layout_data(): any {
const newLayout = deepCopy(this.model.layout);
if (this._relayouting) {
const {layout} = this._layout_wrapper;
// For each xaxis* and yaxis* property of layout, if the value has a 'range'
// property then use this in newLayout
Object.keys(layout).reduce((value: any, key: string) => {
if (key.slice(1, 5) === "axis" && 'range' in value) {
newLayout[key].range = value.range;
}
}, {});
}
return newLayout
}
_install_callbacks(): void {
// - plotly_relayout
this._layout_wrapper.on('plotly_relayout', (eventData: any) => {
if (eventData['_update_from_property'] !== true) {
this.model.relayout_data = filterEventData(
this._layout_wrapper, eventData, 'relayout');
this._updateViewportProperty();
this._end_relayouting();
}
});
// - plotly_relayouting
this._layout_wrapper.on('plotly_relayouting', () => {
if (this.model.viewport_update_policy !== 'mouseup') {
this._relayouting = true;
this._updateViewportProperty();
}
});
// - plotly_restyle
this._layout_wrapper.on('plotly_restyle', (eventData: any) => {
this.model.restyle_data = filterEventData(
this._layout_wrapper, eventData, 'restyle');
this._updateViewportProperty();
});
// - plotly_click
this._layout_wrapper.on('plotly_click', (eventData: any) => {
this.model.click_data = filterEventData(
this._layout_wrapper, eventData, 'click');
});
// - plotly_hover
this._layout_wrapper.on('plotly_hover', (eventData: any) => {
this.model.hover_data = filterEventData(
this._layout_wrapper, eventData, 'hover');
});
// - plotly_selected
this._layout_wrapper.on('plotly_selected', (eventData: any) => {
this.model.selected_data = filterEventData(
this._layout_wrapper, eventData, 'selected');
});
// - plotly_clickannotation
this._layout_wrapper.on('plotly_clickannotation', (eventData: any) => {
delete eventData["event"];
delete eventData["fullAnnotation"];
this.model.clickannotation_data = eventData
});
// - plotly_deselect
this._layout_wrapper.on('plotly_deselect', () => {
this.model.selected_data = null;
});
// - plotly_unhover
this._layout_wrapper.on('plotly_unhover', () => {
this.model.hover_data = null;
});
}
async plot(new_plot: boolean=false): Promise<void> {
if (!(window as any).Plotly)
return
const data = this._trace_data()
const newLayout = this._layout_data()
this._reacting = true
if (new_plot) {
const obj = {data: data, layout: newLayout, config: this.model.config, frames: this.model.frames}
await (window as any).Plotly.newPlot(this._layout_wrapper, obj)
} else {
await (window as any).Plotly.react(this._layout_wrapper, data, newLayout, this.model.config)
if (this.model.frames != null)
await (window as any).Plotly.addFrames(this._layout_wrapper, this.model.frames)
}
this._updateSetViewportFunction()
this._updateViewportProperty()
if (!this._plotInitialized)
this._install_callbacks()
else if (!_isHidden(this._layout_wrapper))
(window as any).Plotly.Plots.resize(this._layout_wrapper)
this._reacting = false
this._plotInitialized = true
}
after_layout(): void{
super.after_layout()
set_size(this.el, this.model)
if ((window as any).Plotly && this._plotInitialized)
(window as any).Plotly.Plots.resize(this._layout_wrapper)
}
_get_trace(index: number, update: boolean): any {
const trace = clone(this.model.data[index]);
const cds = this.model.data_sources[index];
for (const column of cds.columns()) {
let array = cds.get_array(column)[0];
if (array.shape != null && array.shape.length > 1) {
const arrays = [];
const shape = array.shape;
for (let s = 0; s < shape[0]; s++) {
arrays.push(array.slice(s*shape[1], (s+1)*shape[1]));
}
array = arrays;
}
let prop_path = column.split(".");
let prop = prop_path[prop_path.length - 1];
let prop_parent = trace;
for (let k of prop_path.slice(0, -1)) {
prop_parent = (prop_parent[k] as any)
}
if (update && prop_path.length == 1) {
prop_parent[prop] = [array];
} else {
prop_parent[prop] = array;
}
}
return trace;
}
_updateViewportFromProperty(): void {
if (!(window as any).Plotly || this._settingViewport || this._reacting || !this.model.viewport ) { return }
const fullLayout = this._layout_wrapper._fullLayout;
// Call relayout if viewport differs from fullLayout
Object.keys(this.model.viewport).reduce((value: any, key: string) => {
if (!isEqual(get(fullLayout, key), value)) {
let clonedViewport = deepCopy(this.model.viewport)
clonedViewport['_update_from_property'] = true
this._settingViewport = true;
(window as any).Plotly.relayout(this.el, clonedViewport).then(() => {
this._settingViewport = false;
})
return false
} else {
return true
}
}, {});
}
_updateViewportProperty(): void {
const fullLayout = this._layout_wrapper._fullLayout;
let viewport: any = {};
// Get range for all xaxis and yaxis properties
for (let prop in fullLayout) {
if (!fullLayout.hasOwnProperty(prop))
continue
let maybe_axis = prop.slice(0, 5);
if (maybe_axis === 'xaxis' || maybe_axis === 'yaxis')
viewport[prop + '.range'] = deepCopy(fullLayout[prop].range)
}
if (!isEqual(viewport, this.model.viewport))
this._setViewport(viewport)
}
_updateSetViewportFunction(): void {
if (this.model.viewport_update_policy === "continuous" ||
this.model.viewport_update_policy === "mouseup") {
this._setViewport = (viewport: any) => {
if (!this._settingViewport) {
this._settingViewport = true
this.model.viewport = viewport
this._settingViewport = false
}
}
} else {
this._setViewport = throttle((viewport: any) => {
if (!this._settingViewport) {
this._settingViewport = true
this.model.viewport = viewport
this._settingViewport = false
}
}, this.model.viewport_update_throttle)
}
}
}
export namespace PlotlyPlot {
export type Attrs = p.AttrsOf<Props>
export type Props = HTMLBox.Props & {
data: p.Property<any[]>
frames: p.Property<any[] | null>
layout: p.Property<any>
config: p.Property<any>
data_sources: p.Property<any[]>
relayout: p.Property<any>
restyle: p.Property<any>
relayout_data: p.Property<any>
restyle_data: p.Property<any>
click_data: p.Property<any>
hover_data: p.Property<any>
clickannotation_data: p.Property<any>
selected_data: p.Property<any>
viewport: p.Property<any>
viewport_update_policy: p.Property<string>
viewport_update_throttle: p.Property<number>
visibility: p.Property<boolean>
_render_count: p.Property<number>
}
}
export interface PlotlyPlot extends PlotlyPlot.Attrs {}
export class PlotlyPlot extends HTMLBox {
properties: PlotlyPlot.Props
constructor(attrs?: Partial<PlotlyPlot.Attrs>) {
super(attrs)
}
static __module__ = "panel.models.plotly"
static init_PlotlyPlot(): void {
this.prototype.default_view = PlotlyPlotView
this.define<PlotlyPlot.Props>(({Array, Any, Boolean, Ref, String, Nullable, Number}) => ({
data: [ Array(Any), [] ],
layout: [ Any, {} ],
config: [ Any, {} ],
frames: [ Nullable(Array(Any)), null ],
data_sources: [ Array(Ref(ColumnDataSource)), [] ],
relayout: [ Nullable(Any), {} ],
restyle: [ Nullable(Any), {} ],
relayout_data: [ Any, {} ],
restyle_data: [ Array(Any), [] ],
click_data: [ Any, {} ],
hover_data: [ Any, {} ],
clickannotation_data: [ Any, {} ],
selected_data: [ Any, {} ],
viewport: [ Any, {} ],
viewport_update_policy: [ String, "mouseup" ],
viewport_update_throttle: [ Number, 200 ],
visibility: [ Boolean, true],
_render_count: [ Number, 0 ],
}))
}
} | the_stack |
import * as protos from '../protos/protos';
import * as assert from 'assert';
import * as sinon from 'sinon';
import {SinonStub} from 'sinon';
import {describe, it} from 'mocha';
import * as databaseadminModule from '../src';
import {PassThrough} from 'stream';
import {protobuf, LROperation, operationsProtos} from 'google-gax';
function generateSampleMessage<T extends object>(instance: T) {
const filledObject = (
instance.constructor as typeof protobuf.Message
).toObject(instance as protobuf.Message<T>, {defaults: true});
return (instance.constructor as typeof protobuf.Message).fromObject(
filledObject
) as T;
}
function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) {
return error
? sinon.stub().rejects(error)
: sinon.stub().resolves([response]);
}
function stubSimpleCallWithCallback<ResponseType>(
response?: ResponseType,
error?: Error
) {
return error
? sinon.stub().callsArgWith(2, error)
: sinon.stub().callsArgWith(2, null, response);
}
function stubLongRunningCall<ResponseType>(
response?: ResponseType,
callError?: Error,
lroError?: Error
) {
const innerStub = lroError
? sinon.stub().rejects(lroError)
: sinon.stub().resolves([response]);
const mockOperation = {
promise: innerStub,
};
return callError
? sinon.stub().rejects(callError)
: sinon.stub().resolves([mockOperation]);
}
function stubLongRunningCallWithCallback<ResponseType>(
response?: ResponseType,
callError?: Error,
lroError?: Error
) {
const innerStub = lroError
? sinon.stub().rejects(lroError)
: sinon.stub().resolves([response]);
const mockOperation = {
promise: innerStub,
};
return callError
? sinon.stub().callsArgWith(2, callError)
: sinon.stub().callsArgWith(2, null, mockOperation);
}
function stubPageStreamingCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
const pagingStub = sinon.stub();
if (responses) {
for (let i = 0; i < responses.length; ++i) {
pagingStub.onCall(i).callsArgWith(2, null, responses[i]);
}
}
const transformStub = error
? sinon.stub().callsArgWith(2, error)
: pagingStub;
const mockStream = new PassThrough({
objectMode: true,
transform: transformStub,
});
// trigger as many responses as needed
if (responses) {
for (let i = 0; i < responses.length; ++i) {
setImmediate(() => {
mockStream.write({});
});
}
setImmediate(() => {
mockStream.end();
});
} else {
setImmediate(() => {
mockStream.write({});
});
setImmediate(() => {
mockStream.end();
});
}
return sinon.stub().returns(mockStream);
}
function stubAsyncIterationCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
let counter = 0;
const asyncIterable = {
[Symbol.asyncIterator]() {
return {
async next() {
if (error) {
return Promise.reject(error);
}
if (counter >= responses!.length) {
return Promise.resolve({done: true, value: undefined});
}
return Promise.resolve({done: false, value: responses![counter++]});
},
};
},
};
return sinon.stub().returns(asyncIterable);
}
describe('v1.DatabaseAdminClient', () => {
it('has servicePath', () => {
const servicePath = databaseadminModule.v1.DatabaseAdminClient.servicePath;
assert(servicePath);
});
it('has apiEndpoint', () => {
const apiEndpoint = databaseadminModule.v1.DatabaseAdminClient.apiEndpoint;
assert(apiEndpoint);
});
it('has port', () => {
const port = databaseadminModule.v1.DatabaseAdminClient.port;
assert(port);
assert(typeof port === 'number');
});
it('should create a client with no option', () => {
const client = new databaseadminModule.v1.DatabaseAdminClient();
assert(client);
});
it('should create a client with gRPC fallback', () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
fallback: true,
});
assert(client);
});
it('has initialize method and supports deferred initialization', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
assert.strictEqual(client.databaseAdminStub, undefined);
await client.initialize();
assert(client.databaseAdminStub);
});
it('has close method', () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.close();
});
it('has getProjectId method', async () => {
const fakeProjectId = 'fake-project-id';
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.auth.getProjectId = sinon.stub().resolves(fakeProjectId);
const result = await client.getProjectId();
assert.strictEqual(result, fakeProjectId);
assert((client.auth.getProjectId as SinonStub).calledWithExactly());
});
it('has getProjectId method with callback', async () => {
const fakeProjectId = 'fake-project-id';
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.auth.getProjectId = sinon
.stub()
.callsArgWith(0, null, fakeProjectId);
const promise = new Promise((resolve, reject) => {
client.getProjectId((err?: Error | null, projectId?: string | null) => {
if (err) {
reject(err);
} else {
resolve(projectId);
}
});
});
const result = await promise;
assert.strictEqual(result, fakeProjectId);
});
describe('getDatabase', () => {
it('invokes getDatabase without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetDatabaseRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
);
client.innerApiCalls.getDatabase = stubSimpleCall(expectedResponse);
const [response] = await client.getDatabase(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getDatabase without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetDatabaseRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
);
client.innerApiCalls.getDatabase =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getDatabase(
request,
(
err?: Error | null,
result?: protos.google.spanner.admin.database.v1.IDatabase | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getDatabase with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetDatabaseRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getDatabase = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getDatabase(request), expectedError);
assert(
(client.innerApiCalls.getDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('dropDatabase', () => {
it('invokes dropDatabase without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.DropDatabaseRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.dropDatabase = stubSimpleCall(expectedResponse);
const [response] = await client.dropDatabase(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.dropDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes dropDatabase without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.DropDatabaseRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.dropDatabase =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.dropDatabase(
request,
(
err?: Error | null,
result?: protos.google.protobuf.IEmpty | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.dropDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes dropDatabase with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.DropDatabaseRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.dropDatabase = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.dropDatabase(request), expectedError);
assert(
(client.innerApiCalls.dropDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getDatabaseDdl', () => {
it('invokes getDatabaseDdl without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetDatabaseDdlRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetDatabaseDdlResponse()
);
client.innerApiCalls.getDatabaseDdl = stubSimpleCall(expectedResponse);
const [response] = await client.getDatabaseDdl(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getDatabaseDdl as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getDatabaseDdl without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetDatabaseDdlRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetDatabaseDdlResponse()
);
client.innerApiCalls.getDatabaseDdl =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getDatabaseDdl(
request,
(
err?: Error | null,
result?: protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getDatabaseDdl as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getDatabaseDdl with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetDatabaseDdlRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getDatabaseDdl = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getDatabaseDdl(request), expectedError);
assert(
(client.innerApiCalls.getDatabaseDdl as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setIamPolicy', () => {
it('invokes setIamPolicy without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.SetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.Policy()
);
client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse);
const [response] = await client.setIamPolicy(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setIamPolicy without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.SetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.Policy()
);
client.innerApiCalls.setIamPolicy =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setIamPolicy(
request,
(
err?: Error | null,
result?: protos.google.iam.v1.IPolicy | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setIamPolicy with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.SetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setIamPolicy = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setIamPolicy(request), expectedError);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getIamPolicy', () => {
it('invokes getIamPolicy without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.GetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.Policy()
);
client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse);
const [response] = await client.getIamPolicy(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getIamPolicy without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.GetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.Policy()
);
client.innerApiCalls.getIamPolicy =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getIamPolicy(
request,
(
err?: Error | null,
result?: protos.google.iam.v1.IPolicy | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getIamPolicy with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.GetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getIamPolicy = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getIamPolicy(request), expectedError);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('testIamPermissions', () => {
it('invokes testIamPermissions without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsResponse()
);
client.innerApiCalls.testIamPermissions =
stubSimpleCall(expectedResponse);
const [response] = await client.testIamPermissions(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes testIamPermissions without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsResponse()
);
client.innerApiCalls.testIamPermissions =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.testIamPermissions(
request,
(
err?: Error | null,
result?: protos.google.iam.v1.ITestIamPermissionsResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes testIamPermissions with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.testIamPermissions = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.testIamPermissions(request), expectedError);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getBackup', () => {
it('invokes getBackup without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetBackupRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
);
client.innerApiCalls.getBackup = stubSimpleCall(expectedResponse);
const [response] = await client.getBackup(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getBackup without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetBackupRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
);
client.innerApiCalls.getBackup =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getBackup(
request,
(
err?: Error | null,
result?: protos.google.spanner.admin.database.v1.IBackup | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getBackup with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.GetBackupRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getBackup = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.getBackup(request), expectedError);
assert(
(client.innerApiCalls.getBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('updateBackup', () => {
it('invokes updateBackup without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.UpdateBackupRequest()
);
request.backup = {};
request.backup.name = '';
const expectedHeaderRequestParams = 'backup.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
);
client.innerApiCalls.updateBackup = stubSimpleCall(expectedResponse);
const [response] = await client.updateBackup(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateBackup without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.UpdateBackupRequest()
);
request.backup = {};
request.backup.name = '';
const expectedHeaderRequestParams = 'backup.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
);
client.innerApiCalls.updateBackup =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.updateBackup(
request,
(
err?: Error | null,
result?: protos.google.spanner.admin.database.v1.IBackup | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes updateBackup with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.UpdateBackupRequest()
);
request.backup = {};
request.backup.name = '';
const expectedHeaderRequestParams = 'backup.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateBackup = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.updateBackup(request), expectedError);
assert(
(client.innerApiCalls.updateBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('deleteBackup', () => {
it('invokes deleteBackup without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.DeleteBackupRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteBackup = stubSimpleCall(expectedResponse);
const [response] = await client.deleteBackup(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes deleteBackup without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.DeleteBackupRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteBackup =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.deleteBackup(
request,
(
err?: Error | null,
result?: protos.google.protobuf.IEmpty | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes deleteBackup with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.DeleteBackupRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.deleteBackup = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.deleteBackup(request), expectedError);
assert(
(client.innerApiCalls.deleteBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('createDatabase', () => {
it('invokes createDatabase without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.CreateDatabaseRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.createDatabase =
stubLongRunningCall(expectedResponse);
const [operation] = await client.createDatabase(request);
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes createDatabase without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.CreateDatabaseRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.createDatabase =
stubLongRunningCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.createDatabase(
request,
(
err?: Error | null,
result?: LROperation<
protos.google.spanner.admin.database.v1.IDatabase,
protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata
> | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const operation = (await promise) as LROperation<
protos.google.spanner.admin.database.v1.IDatabase,
protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata
>;
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes createDatabase with call error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.CreateDatabaseRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.createDatabase = stubLongRunningCall(
undefined,
expectedError
);
await assert.rejects(client.createDatabase(request), expectedError);
assert(
(client.innerApiCalls.createDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes createDatabase with LRO error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.CreateDatabaseRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.createDatabase = stubLongRunningCall(
undefined,
undefined,
expectedError
);
const [operation] = await client.createDatabase(request);
await assert.rejects(operation.promise(), expectedError);
assert(
(client.innerApiCalls.createDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes checkCreateDatabaseProgress without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedResponse = generateSampleMessage(
new operationsProtos.google.longrunning.Operation()
);
expectedResponse.name = 'test';
expectedResponse.response = {type_url: 'url', value: Buffer.from('')};
expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')};
client.operationsClient.getOperation = stubSimpleCall(expectedResponse);
const decodedOperation = await client.checkCreateDatabaseProgress(
expectedResponse.name
);
assert.deepStrictEqual(decodedOperation.name, expectedResponse.name);
assert(decodedOperation.metadata);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
it('invokes checkCreateDatabaseProgress with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedError = new Error('expected');
client.operationsClient.getOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.checkCreateDatabaseProgress(''),
expectedError
);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
});
describe('updateDatabaseDdl', () => {
it('invokes updateDatabaseDdl without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.updateDatabaseDdl =
stubLongRunningCall(expectedResponse);
const [operation] = await client.updateDatabaseDdl(request);
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateDatabaseDdl as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateDatabaseDdl without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.updateDatabaseDdl =
stubLongRunningCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.updateDatabaseDdl(
request,
(
err?: Error | null,
result?: LROperation<
protos.google.protobuf.IEmpty,
protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata
> | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const operation = (await promise) as LROperation<
protos.google.protobuf.IEmpty,
protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata
>;
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateDatabaseDdl as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes updateDatabaseDdl with call error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateDatabaseDdl = stubLongRunningCall(
undefined,
expectedError
);
await assert.rejects(client.updateDatabaseDdl(request), expectedError);
assert(
(client.innerApiCalls.updateDatabaseDdl as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateDatabaseDdl with LRO error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest()
);
request.database = '';
const expectedHeaderRequestParams = 'database=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateDatabaseDdl = stubLongRunningCall(
undefined,
undefined,
expectedError
);
const [operation] = await client.updateDatabaseDdl(request);
await assert.rejects(operation.promise(), expectedError);
assert(
(client.innerApiCalls.updateDatabaseDdl as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes checkUpdateDatabaseDdlProgress without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedResponse = generateSampleMessage(
new operationsProtos.google.longrunning.Operation()
);
expectedResponse.name = 'test';
expectedResponse.response = {type_url: 'url', value: Buffer.from('')};
expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')};
client.operationsClient.getOperation = stubSimpleCall(expectedResponse);
const decodedOperation = await client.checkUpdateDatabaseDdlProgress(
expectedResponse.name
);
assert.deepStrictEqual(decodedOperation.name, expectedResponse.name);
assert(decodedOperation.metadata);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
it('invokes checkUpdateDatabaseDdlProgress with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedError = new Error('expected');
client.operationsClient.getOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.checkUpdateDatabaseDdlProgress(''),
expectedError
);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
});
describe('createBackup', () => {
it('invokes createBackup without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.CreateBackupRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.createBackup = stubLongRunningCall(expectedResponse);
const [operation] = await client.createBackup(request);
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes createBackup without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.CreateBackupRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.createBackup =
stubLongRunningCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.createBackup(
request,
(
err?: Error | null,
result?: LROperation<
protos.google.spanner.admin.database.v1.IBackup,
protos.google.spanner.admin.database.v1.ICreateBackupMetadata
> | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const operation = (await promise) as LROperation<
protos.google.spanner.admin.database.v1.IBackup,
protos.google.spanner.admin.database.v1.ICreateBackupMetadata
>;
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes createBackup with call error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.CreateBackupRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.createBackup = stubLongRunningCall(
undefined,
expectedError
);
await assert.rejects(client.createBackup(request), expectedError);
assert(
(client.innerApiCalls.createBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes createBackup with LRO error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.CreateBackupRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.createBackup = stubLongRunningCall(
undefined,
undefined,
expectedError
);
const [operation] = await client.createBackup(request);
await assert.rejects(operation.promise(), expectedError);
assert(
(client.innerApiCalls.createBackup as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes checkCreateBackupProgress without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedResponse = generateSampleMessage(
new operationsProtos.google.longrunning.Operation()
);
expectedResponse.name = 'test';
expectedResponse.response = {type_url: 'url', value: Buffer.from('')};
expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')};
client.operationsClient.getOperation = stubSimpleCall(expectedResponse);
const decodedOperation = await client.checkCreateBackupProgress(
expectedResponse.name
);
assert.deepStrictEqual(decodedOperation.name, expectedResponse.name);
assert(decodedOperation.metadata);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
it('invokes checkCreateBackupProgress with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedError = new Error('expected');
client.operationsClient.getOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.checkCreateBackupProgress(''), expectedError);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
});
describe('restoreDatabase', () => {
it('invokes restoreDatabase without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.RestoreDatabaseRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.restoreDatabase =
stubLongRunningCall(expectedResponse);
const [operation] = await client.restoreDatabase(request);
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.restoreDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes restoreDatabase without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.RestoreDatabaseRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.longrunning.Operation()
);
client.innerApiCalls.restoreDatabase =
stubLongRunningCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.restoreDatabase(
request,
(
err?: Error | null,
result?: LROperation<
protos.google.spanner.admin.database.v1.IDatabase,
protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata
> | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const operation = (await promise) as LROperation<
protos.google.spanner.admin.database.v1.IDatabase,
protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata
>;
const [response] = await operation.promise();
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.restoreDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes restoreDatabase with call error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.RestoreDatabaseRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.restoreDatabase = stubLongRunningCall(
undefined,
expectedError
);
await assert.rejects(client.restoreDatabase(request), expectedError);
assert(
(client.innerApiCalls.restoreDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes restoreDatabase with LRO error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.RestoreDatabaseRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.restoreDatabase = stubLongRunningCall(
undefined,
undefined,
expectedError
);
const [operation] = await client.restoreDatabase(request);
await assert.rejects(operation.promise(), expectedError);
assert(
(client.innerApiCalls.restoreDatabase as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes checkRestoreDatabaseProgress without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedResponse = generateSampleMessage(
new operationsProtos.google.longrunning.Operation()
);
expectedResponse.name = 'test';
expectedResponse.response = {type_url: 'url', value: Buffer.from('')};
expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')};
client.operationsClient.getOperation = stubSimpleCall(expectedResponse);
const decodedOperation = await client.checkRestoreDatabaseProgress(
expectedResponse.name
);
assert.deepStrictEqual(decodedOperation.name, expectedResponse.name);
assert(decodedOperation.metadata);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
it('invokes checkRestoreDatabaseProgress with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const expectedError = new Error('expected');
client.operationsClient.getOperation = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.checkRestoreDatabaseProgress(''),
expectedError
);
assert((client.operationsClient.getOperation as SinonStub).getCall(0));
});
});
describe('listDatabases', () => {
it('invokes listDatabases without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabasesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
];
client.innerApiCalls.listDatabases = stubSimpleCall(expectedResponse);
const [response] = await client.listDatabases(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDatabases as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDatabases without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabasesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
];
client.innerApiCalls.listDatabases =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listDatabases(
request,
(
err?: Error | null,
result?: protos.google.spanner.admin.database.v1.IDatabase[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDatabases as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listDatabases with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabasesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listDatabases = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.listDatabases(request), expectedError);
assert(
(client.innerApiCalls.listDatabases as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDatabasesStream without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabasesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
];
client.descriptors.page.listDatabases.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listDatabasesStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.spanner.admin.database.v1.Database[] =
[];
stream.on(
'data',
(response: protos.google.spanner.admin.database.v1.Database) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptors.page.listDatabases.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listDatabases, request)
);
assert.strictEqual(
(
client.descriptors.page.listDatabases.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listDatabasesStream with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabasesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listDatabases.createStream =
stubPageStreamingCall(undefined, expectedError);
const stream = client.listDatabasesStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.spanner.admin.database.v1.Database[] =
[];
stream.on(
'data',
(response: protos.google.spanner.admin.database.v1.Database) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(client.descriptors.page.listDatabases.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listDatabases, request)
);
assert.strictEqual(
(
client.descriptors.page.listDatabases.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listDatabases without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabasesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Database()
),
];
client.descriptors.page.listDatabases.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.spanner.admin.database.v1.IDatabase[] = [];
const iterable = client.listDatabasesAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(
client.descriptors.page.listDatabases.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listDatabases.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listDatabases with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabasesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listDatabases.asyncIterate =
stubAsyncIterationCall(undefined, expectedError);
const iterable = client.listDatabasesAsync(request);
await assert.rejects(async () => {
const responses: protos.google.spanner.admin.database.v1.IDatabase[] =
[];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(
client.descriptors.page.listDatabases.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listDatabases.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('listBackups', () => {
it('invokes listBackups without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
];
client.innerApiCalls.listBackups = stubSimpleCall(expectedResponse);
const [response] = await client.listBackups(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listBackups as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listBackups without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
];
client.innerApiCalls.listBackups =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listBackups(
request,
(
err?: Error | null,
result?: protos.google.spanner.admin.database.v1.IBackup[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listBackups as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listBackups with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listBackups = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.listBackups(request), expectedError);
assert(
(client.innerApiCalls.listBackups as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listBackupsStream without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
];
client.descriptors.page.listBackups.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listBackupsStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.spanner.admin.database.v1.Backup[] = [];
stream.on(
'data',
(response: protos.google.spanner.admin.database.v1.Backup) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptors.page.listBackups.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listBackups, request)
);
assert.strictEqual(
(client.descriptors.page.listBackups.createStream as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listBackupsStream with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listBackups.createStream = stubPageStreamingCall(
undefined,
expectedError
);
const stream = client.listBackupsStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.spanner.admin.database.v1.Backup[] = [];
stream.on(
'data',
(response: protos.google.spanner.admin.database.v1.Backup) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(client.descriptors.page.listBackups.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listBackups, request)
);
assert.strictEqual(
(client.descriptors.page.listBackups.createStream as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listBackups without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
generateSampleMessage(
new protos.google.spanner.admin.database.v1.Backup()
),
];
client.descriptors.page.listBackups.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.spanner.admin.database.v1.IBackup[] = [];
const iterable = client.listBackupsAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(client.descriptors.page.listBackups.asyncIterate as SinonStub).getCall(
0
).args[1],
request
);
assert.strictEqual(
(client.descriptors.page.listBackups.asyncIterate as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listBackups with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listBackups.asyncIterate = stubAsyncIterationCall(
undefined,
expectedError
);
const iterable = client.listBackupsAsync(request);
await assert.rejects(async () => {
const responses: protos.google.spanner.admin.database.v1.IBackup[] = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(client.descriptors.page.listBackups.asyncIterate as SinonStub).getCall(
0
).args[1],
request
);
assert.strictEqual(
(client.descriptors.page.listBackups.asyncIterate as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('listDatabaseOperations', () => {
it('invokes listDatabaseOperations without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.innerApiCalls.listDatabaseOperations =
stubSimpleCall(expectedResponse);
const [response] = await client.listDatabaseOperations(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDatabaseOperations as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDatabaseOperations without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.innerApiCalls.listDatabaseOperations =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listDatabaseOperations(
request,
(
err?: Error | null,
result?: protos.google.longrunning.IOperation[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDatabaseOperations as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listDatabaseOperations with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listDatabaseOperations = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.listDatabaseOperations(request),
expectedError
);
assert(
(client.innerApiCalls.listDatabaseOperations as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDatabaseOperationsStream without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.descriptors.page.listDatabaseOperations.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listDatabaseOperationsStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.longrunning.Operation[] = [];
stream.on('data', (response: protos.google.longrunning.Operation) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(
client.descriptors.page.listDatabaseOperations
.createStream as SinonStub
)
.getCall(0)
.calledWith(client.innerApiCalls.listDatabaseOperations, request)
);
assert.strictEqual(
(
client.descriptors.page.listDatabaseOperations
.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listDatabaseOperationsStream with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listDatabaseOperations.createStream =
stubPageStreamingCall(undefined, expectedError);
const stream = client.listDatabaseOperationsStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.longrunning.Operation[] = [];
stream.on('data', (response: protos.google.longrunning.Operation) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(
client.descriptors.page.listDatabaseOperations
.createStream as SinonStub
)
.getCall(0)
.calledWith(client.innerApiCalls.listDatabaseOperations, request)
);
assert.strictEqual(
(
client.descriptors.page.listDatabaseOperations
.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listDatabaseOperations without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.descriptors.page.listDatabaseOperations.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.longrunning.IOperation[] = [];
const iterable = client.listDatabaseOperationsAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(
client.descriptors.page.listDatabaseOperations
.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listDatabaseOperations
.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listDatabaseOperations with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listDatabaseOperations.asyncIterate =
stubAsyncIterationCall(undefined, expectedError);
const iterable = client.listDatabaseOperationsAsync(request);
await assert.rejects(async () => {
const responses: protos.google.longrunning.IOperation[] = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(
client.descriptors.page.listDatabaseOperations
.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listDatabaseOperations
.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('listBackupOperations', () => {
it('invokes listBackupOperations without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.innerApiCalls.listBackupOperations =
stubSimpleCall(expectedResponse);
const [response] = await client.listBackupOperations(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listBackupOperations as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listBackupOperations without error using callback', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.innerApiCalls.listBackupOperations =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listBackupOperations(
request,
(
err?: Error | null,
result?: protos.google.longrunning.IOperation[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listBackupOperations as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listBackupOperations with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listBackupOperations = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.listBackupOperations(request), expectedError);
assert(
(client.innerApiCalls.listBackupOperations as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listBackupOperationsStream without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.descriptors.page.listBackupOperations.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listBackupOperationsStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.longrunning.Operation[] = [];
stream.on('data', (response: protos.google.longrunning.Operation) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptors.page.listBackupOperations.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listBackupOperations, request)
);
assert.strictEqual(
(
client.descriptors.page.listBackupOperations.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listBackupOperationsStream with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listBackupOperations.createStream =
stubPageStreamingCall(undefined, expectedError);
const stream = client.listBackupOperationsStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.longrunning.Operation[] = [];
stream.on('data', (response: protos.google.longrunning.Operation) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(client.descriptors.page.listBackupOperations.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listBackupOperations, request)
);
assert.strictEqual(
(
client.descriptors.page.listBackupOperations.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listBackupOperations without error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
generateSampleMessage(new protos.google.longrunning.Operation()),
];
client.descriptors.page.listBackupOperations.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.longrunning.IOperation[] = [];
const iterable = client.listBackupOperationsAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(
client.descriptors.page.listBackupOperations.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listBackupOperations.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listBackupOperations with error', async () => {
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listBackupOperations.asyncIterate =
stubAsyncIterationCall(undefined, expectedError);
const iterable = client.listBackupOperationsAsync(request);
await assert.rejects(async () => {
const responses: protos.google.longrunning.IOperation[] = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(
client.descriptors.page.listBackupOperations.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listBackupOperations.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('Path templates', () => {
describe('backup', () => {
const fakePath = '/rendered/path/backup';
const expectedParameters = {
project: 'projectValue',
instance: 'instanceValue',
backup: 'backupValue',
};
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.backupPathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.backupPathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('backupPath', () => {
const result = client.backupPath(
'projectValue',
'instanceValue',
'backupValue'
);
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.backupPathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromBackupName', () => {
const result = client.matchProjectFromBackupName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.backupPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchInstanceFromBackupName', () => {
const result = client.matchInstanceFromBackupName(fakePath);
assert.strictEqual(result, 'instanceValue');
assert(
(client.pathTemplates.backupPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchBackupFromBackupName', () => {
const result = client.matchBackupFromBackupName(fakePath);
assert.strictEqual(result, 'backupValue');
assert(
(client.pathTemplates.backupPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('cryptoKey', () => {
const fakePath = '/rendered/path/cryptoKey';
const expectedParameters = {
project: 'projectValue',
location: 'locationValue',
key_ring: 'keyRingValue',
crypto_key: 'cryptoKeyValue',
};
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.cryptoKeyPathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.cryptoKeyPathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('cryptoKeyPath', () => {
const result = client.cryptoKeyPath(
'projectValue',
'locationValue',
'keyRingValue',
'cryptoKeyValue'
);
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.cryptoKeyPathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromCryptoKeyName', () => {
const result = client.matchProjectFromCryptoKeyName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.cryptoKeyPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchLocationFromCryptoKeyName', () => {
const result = client.matchLocationFromCryptoKeyName(fakePath);
assert.strictEqual(result, 'locationValue');
assert(
(client.pathTemplates.cryptoKeyPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchKeyRingFromCryptoKeyName', () => {
const result = client.matchKeyRingFromCryptoKeyName(fakePath);
assert.strictEqual(result, 'keyRingValue');
assert(
(client.pathTemplates.cryptoKeyPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchCryptoKeyFromCryptoKeyName', () => {
const result = client.matchCryptoKeyFromCryptoKeyName(fakePath);
assert.strictEqual(result, 'cryptoKeyValue');
assert(
(client.pathTemplates.cryptoKeyPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('database', () => {
const fakePath = '/rendered/path/database';
const expectedParameters = {
project: 'projectValue',
instance: 'instanceValue',
database: 'databaseValue',
};
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.databasePathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.databasePathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('databasePath', () => {
const result = client.databasePath(
'projectValue',
'instanceValue',
'databaseValue'
);
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.databasePathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromDatabaseName', () => {
const result = client.matchProjectFromDatabaseName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.databasePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchInstanceFromDatabaseName', () => {
const result = client.matchInstanceFromDatabaseName(fakePath);
assert.strictEqual(result, 'instanceValue');
assert(
(client.pathTemplates.databasePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchDatabaseFromDatabaseName', () => {
const result = client.matchDatabaseFromDatabaseName(fakePath);
assert.strictEqual(result, 'databaseValue');
assert(
(client.pathTemplates.databasePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('instance', () => {
const fakePath = '/rendered/path/instance';
const expectedParameters = {
project: 'projectValue',
instance: 'instanceValue',
};
const client = new databaseadminModule.v1.DatabaseAdminClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.instancePathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.instancePathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('instancePath', () => {
const result = client.instancePath('projectValue', 'instanceValue');
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.instancePathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromInstanceName', () => {
const result = client.matchProjectFromInstanceName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.instancePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchInstanceFromInstanceName', () => {
const result = client.matchInstanceFromInstanceName(fakePath);
assert.strictEqual(result, 'instanceValue');
assert(
(client.pathTemplates.instancePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
});
}); | the_stack |
import { Buffer } from 'buffer';
import { ChildProcess, spawn } from 'child_process';
import { EventEmitter } from 'events';
import os from 'os';
import timers from 'timers';
import { KubeConfig } from '@kubernetes/client-node/dist/config';
import * as K8s from '@/k8s-engine/k8s';
import * as window from '@/window';
import mainEvents from '@/main/mainEvents';
import Logging from '@/utils/logging';
import LimaBackend from '@/k8s-engine/lima';
const REFRESH_INTERVAL = 5 * 1000;
const APP_NAME = 'rancher-desktop';
const KUBE_CONTEXT = 'rancher-desktop';
const console = Logging.images;
function defined<T>(input: T | undefined | null): input is T {
return typeof input !== 'undefined' && input !== null;
}
/**
* The fields that cover the results of a finished process.
* Not all fields are set for every process.
*/
export interface childResultType {
stdout: string;
stderr: string;
code: number;
signal?: string;
}
/**
* The fields for display in the images table
*/
export interface imageType {
imageName: string,
tag: string,
imageID: string,
size: string,
}
/**
* ImageProcessors take requests, from the UI or caused by state transitions
* (such as a K8s engine hitting the STARTED state), and invokes the appropriate
* client to run commands and send output to the UI.
*
* Each concrete ImageProcessor is a singleton, with a 1:1 correspondence between
* the current container engine the user has selected, and its ImageProcessor.
*
* Currently some events are handled directly by the concrete ImageProcessor subclasses,
* and some are handled by the ImageEventHandler singleton, which calls methods on
* the current ImageProcessor. Because these events are sent to all imageProcessors, but
* only one should actually act on them, we use the concept of the `active` processor
* to determine which processor acts on its events.
*
* When all the event-handlers have been moved into the ImageEventHandler the concept of
* an active ImageProcessor can be dropped.
*/
export abstract class ImageProcessor extends EventEmitter {
protected k8sManager: K8s.KubernetesBackend|null;
// Sometimes the `images` subcommand repeatedly fires the same error message.
// Instead of logging it every time, keep track of the current error and give a count instead.
private lastErrorMessage = '';
private sameErrorMessageCount = 0;
protected showedStderr = false;
private refreshInterval: ReturnType<typeof timers.setInterval> | null = null;
protected images:imageType[] = [];
protected _isReady = false;
protected isK8sReady = false;
private hasImageListeners = false;
private isWatching = false;
_refreshImages: () => Promise<void>;
protected currentNamespace = 'default';
// See https://github.com/rancher-sandbox/rancher-desktop/issues/977
// for a task to get rid of the concept of an active imageProcessor.
// All the event handlers should be on the imageEventHandler, which knows
// which imageProcessor is currently active, and it can direct events to that.
protected active = false;
protected constructor(k8sManager: K8s.KubernetesBackend) {
super();
this.k8sManager = k8sManager;
this._refreshImages = this.refreshImages.bind(this);
this.on('newListener', (event: string | symbol) => {
if (!this.active) {
return;
}
if (event === 'images-changed' && !this.hasImageListeners) {
this.hasImageListeners = true;
this.updateWatchStatus();
}
});
this.on('removeListener', (event: string | symbol) => {
if (!this.active) {
return;
}
if (event === 'images-changed' && this.hasImageListeners) {
this.hasImageListeners = this.listeners('images-changed').length > 0;
this.updateWatchStatus();
}
});
this.on('readiness-changed', (state: boolean) => {
if (!this.active) {
return;
}
window.send('images-check-state', state);
});
this.on('images-process-output', (data: string, isStderr: boolean) => {
if (!this.active) {
return;
}
window.send('images-process-output', data, isStderr);
});
mainEvents.on('settings-update', (cfg) => {
if (!this.active) {
return;
}
if (this.namespace !== cfg.images.namespace) {
this.namespace = cfg.images.namespace;
this.refreshImages()
.catch((err: Error) => {
console.log(`Error refreshing images:`, err);
});
}
});
}
activate() {
this.active = true;
}
deactivate() {
this.active = false;
}
protected updateWatchStatus() {
const shouldWatch = this.isK8sReady && this.hasImageListeners;
if (this.isWatching === shouldWatch) {
return;
}
if (this.refreshInterval) {
timers.clearInterval(this.refreshInterval);
}
if (shouldWatch) {
this.refreshInterval = timers.setInterval(this._refreshImages, REFRESH_INTERVAL);
timers.setImmediate(this._refreshImages);
}
this.isWatching = shouldWatch;
}
/**
* Are images ready for display in the UI?
*/
get isReady() {
return this._isReady;
}
/**
* Wrapper around the trivy command to scan the specified image.
* @param taggedImageName
*/
async scanImage(taggedImageName: string): Promise<childResultType> {
return await this.runTrivyCommand([
'--quiet',
'image',
'--format',
'json',
taggedImageName
]);
}
/**
* This method figures out which command to run for scanning, based on the platform
* and provided args.
* @param args
* @param sendNotifications
*/
async runTrivyCommand(args: string[], sendNotifications = true): Promise<childResultType> {
let child: ChildProcess;
const subcommandName = args[0];
if (os.platform().startsWith('win')) {
args = ['-d', APP_NAME, 'trivy'].concat(args);
child = spawn('wsl', args);
} else if (os.platform().startsWith('darwin') || os.platform().startsWith('linux')) {
const limaBackend = this.k8sManager as LimaBackend;
args = ['trivy'].concat(args);
child = limaBackend.limaSpawn(args);
} else {
throw new Error(`Don't know how to run trivy on platform ${ os.platform() }`);
}
return await this.processChildOutput(child, subcommandName, sendNotifications);
}
/**
* Returns the current list of cached images.
*/
listImages(): imageType[] {
return this.images;
}
isChildResultType(object: any): object is childResultType {
return 'stderr' in object &&
'stdout' in object &&
'signal' in object &&
'code' in object;
}
/**
* Refreshes the current cache of processed images.
*/
async refreshImages() {
try {
const result:childResultType = await this.getImages();
if (result.stderr) {
if (!this.showedStderr) {
console.log(`${ this.processorName } images: ${ result.stderr } `);
this.showedStderr = true;
}
} else {
this.showedStderr = false;
}
this.images = this.parse(result.stdout);
if (!this._isReady) {
this._isReady = true;
this.emit('readiness-changed', true);
}
this.emit('images-changed', this.images);
} catch (err) {
if (!this.showedStderr) {
if (this.isChildResultType(err) && !err.stdout && !err.signal) {
console.log(err.stderr);
} else {
console.log(err);
}
}
this.showedStderr = true;
if (this.isChildResultType(err) && this._isReady) {
this._isReady = false;
this.emit('readiness-changed', false);
}
}
}
protected parse(data: string): imageType[] {
const results = data.trimEnd().split(/\r?\n/).slice(1).map((line) => {
const [imageName, tag, imageID, size] = line.split(/\s+/);
return {
imageName, tag, imageID, size
};
});
return results;
}
/**
* Takes the `childProcess` returned by a command like `child_process.spawn` and processes the
* output streams and exit code and signal.
*
* @param child
* @param subcommandName - used for error messages only
* @param sendNotifications
*/
async processChildOutput(child: ChildProcess, subcommandName: string, sendNotifications: boolean): Promise<childResultType> {
const result = { stdout: '', stderr: '' };
return await new Promise((resolve, reject) => {
child.stdout?.on('data', (data: Buffer) => {
const dataString = data.toString();
if (sendNotifications) {
this.emit('images-process-output', dataString, false);
}
result.stdout += dataString;
});
child.stderr?.on('data', (data: Buffer) => {
let dataString = data.toString();
if (this.processorName === 'nerdctl' && subcommandName === 'images') {
/**
* `nerdctl images` issues some dubious error messages
* (see https://github.com/containerd/nerdctl/issues/353 , logged 2021-09-10)
* Pull them out for now
*/
dataString = dataString
.replace(/time=".+?"\s+level=.+?\s+msg="failed to compute image\(s\) size"\s*/g, '')
.replace(/time=".+?"\s+level=.+?\s+msg="unparsable image name.*?sha256:[0-9a-fA-F]{64}.*?\\""\s*/g, '');
if (!dataString) {
return;
}
}
result.stderr += dataString;
if (sendNotifications) {
this.emit('images-process-output', dataString, true);
}
});
child.on('exit', (code, signal) => {
if (result.stderr) {
const timeLessMessage = result.stderr.replace(/\btime=".*?"/g, '');
if (this.lastErrorMessage !== timeLessMessage) {
this.lastErrorMessage = timeLessMessage;
this.sameErrorMessageCount = 1;
console.log(result.stderr.replace(/(?!<\r)\n/g, '\r\n'));
} else {
const m = /(Error: .*)/.exec(this.lastErrorMessage);
this.sameErrorMessageCount += 1;
console.log(`${ this.processorName } ${ subcommandName }: ${ m ? m[1] : 'same error message' } #${ this.sameErrorMessageCount }\r`);
}
}
if (code === 0) {
if (sendNotifications) {
window.send('ok:images-process-output', result.stdout);
}
resolve({ ...result, code });
} else if (signal) {
reject({
...result, code: -1, signal
});
} else {
reject({ ...result, code });
}
});
});
}
/**
* Called normally when the UI requests the current list of namespaces
* for the current imageProcessor.
*
* Containerd starts with two namespaces: "k8s.io" and "default".
* There's no way to add other namespaces in the UI,
* but they can easily be added from the command-line.
*
* See https://github.com/rancher-sandbox/rancher-desktop/issues/978 for being notified
* without polling on changes in the namespaces.
*/
async relayNamespaces() {
const namespaces = await this.getNamespaces();
const comparator = Intl.Collator(undefined, { sensitivity: 'base' }).compare;
if (!namespaces.includes('default')) {
namespaces.push('default');
}
window.send('images-namespaces', namespaces.sort(comparator));
}
get namespace() {
return this.currentNamespace;
}
set namespace(value: string) {
this.currentNamespace = value;
}
/* Subclass-specific method definitions here: */
protected abstract get processorName(): string;
abstract getNamespaces(): Promise<Array<string>>;
abstract buildImage(dirPart: string, filePart: string, taggedImageName: string): Promise<childResultType>;
abstract deleteImage(imageID: string): Promise<childResultType>;
abstract pullImage(taggedImageName: string): Promise<childResultType>;
abstract pushImage(taggedImageName: string): Promise<childResultType>;
abstract getImages(): Promise<childResultType>;
abstract removeKimBuilder(client: KubeConfig): Promise<void>;
} | the_stack |
import groupBy from "lodash-es/groupBy";
import { computed } from "mobx";
import binarySearch from "terriajs-cesium/Source/Core/binarySearch";
import JulianDate from "terriajs-cesium/Source/Core/JulianDate";
import TimeInterval from "terriajs-cesium/Source/Core/TimeInterval";
import filterOutUndefined from "../Core/filterOutUndefined";
import isDefined from "../Core/isDefined";
import ConstantColorMap from "../Map/ConstantColorMap";
import ConstantPointSizeMap from "../Map/ConstantPointSizeMap";
import DiscreteColorMap from "../Map/DiscreteColorMap";
import EnumColorMap from "../Map/EnumColorMap";
import PointSizeMap from "../Map/PointSizeMap";
import ScalePointSizeMap from "../Map/ScalePointSizeMap";
import TableMixin from "../ModelMixins/TableMixin";
import createCombinedModel from "../Models/Definition/createCombinedModel";
import Model from "../Models/Definition/Model";
import TableChartStyleTraits from "../Traits/TraitsClasses/TableChartStyleTraits";
import TableColorStyleTraits from "../Traits/TraitsClasses/TableColorStyleTraits";
import TablePointSizeStyleTraits from "../Traits/TraitsClasses/TablePointSizeStyleTraits";
import TableStyleTraits from "../Traits/TraitsClasses/TableStyleTraits";
import TableTimeStyleTraits from "../Traits/TraitsClasses/TableTimeStyleTraits";
import TableColorMap from "./TableColorMap";
import TableColumn from "./TableColumn";
import TableColumnType from "./TableColumnType";
const DEFAULT_FINAL_DURATION_SECONDS = 3600 * 24 - 1; // one day less a second, if there is only one date.
/**
* A style controlling how tabular data is displayed.
*/
export default class TableStyle {
readonly styleNumber: number;
readonly tableModel: TableMixin.Instance;
constructor(tableModel: TableMixin.Instance, styleNumber: number) {
this.styleNumber = styleNumber;
this.tableModel = tableModel;
}
/** Is style ready to be used.
* This will be false if any of dependent columns are not ready
*/
@computed
get ready() {
return filterOutUndefined([
this.longitudeColumn,
this.latitudeColumn,
this.regionColumn,
this.timeColumn,
this.endTimeColumn,
this.xAxisColumn,
this.colorColumn,
this.pointSizeColumn,
...(this.idColumns ?? [])
]).every(col => col.ready);
}
/**
* Gets the ID of the style.
*/
@computed
get id(): string {
return this.styleTraits.id || "Style" + this.styleNumber;
}
@computed
get title(): string {
return (
this.styleTraits.title ??
this.tableModel.tableColumns.find(col => col.name === this.id)?.title ??
this.id
);
}
/** Hide style from "Display Variable" selector if number of colors (EnumColorMap or DiscreteColorMapw) is less than 2. As a ColorMap with a single color isn't super useful. */
@computed
get hidden() {
if (isDefined(this.styleTraits.hidden)) return this.styleTraits.hidden;
if (this.colorMap instanceof ConstantColorMap) return true;
if (
(this.colorMap instanceof EnumColorMap ||
this.colorMap instanceof DiscreteColorMap) &&
this.colorMap.colors.length < 2
)
return true;
}
/**
* Gets the {@link TableStyleTraits} for this style. The traits are derived
* from the default styles plus this style layered on top of the default.
*/
@computed
get styleTraits(): Model<TableStyleTraits> {
if (
this.styleNumber >= 0 &&
this.styleNumber < this.tableModel.styles.length
) {
const result = createCombinedModel(
this.tableModel.styles[this.styleNumber],
this.tableModel.defaultStyle
);
return result;
} else {
return this.tableModel.defaultStyle;
}
}
/**
* Gets the {@link TableColorStyleTraits} from the {@link #styleTraits}.
* Returns a default instance of no color traits are specified explicitly.
*/
@computed
get colorTraits(): Model<TableColorStyleTraits> {
return this.styleTraits.color;
}
/**
* Gets the {@link TableScaleStyleTraits} from the {@link #styleTraits}.
* Returns a default instance of no scale traits are specified explicitly.
*/
@computed
get pointSizeTraits(): Model<TablePointSizeStyleTraits> {
return this.styleTraits.pointSize;
}
/**
* Gets the {@link TableChartStyleTraits} from the {@link #styleTraits}.
* Returns a default instance of no chart traits are specified explicitly.
*/
@computed
get chartTraits(): Model<TableChartStyleTraits> {
return this.styleTraits.chart;
}
/**
* Gets the {@link TableTimeStyleTraits} from the {@link #styleTraits}.
* Returns a default instance if no time traits are specified explicitly.
*/
@computed
get timeTraits(): Model<TableTimeStyleTraits> {
return this.styleTraits.time;
}
/**
* Gets the longitude column for this style, if any.
*/
@computed
get longitudeColumn(): TableColumn | undefined {
return this.resolveColumn(this.styleTraits.longitudeColumn);
}
/**
* Gets the latitude column for this style, if any.
*/
@computed
get latitudeColumn(): TableColumn | undefined {
return this.resolveColumn(this.styleTraits.latitudeColumn);
}
/**
* Gets the region column for this style, if any.
*/
@computed
get regionColumn(): TableColumn | undefined {
if (this.styleTraits.regionColumn === null) return;
return this.resolveColumn(this.styleTraits.regionColumn);
}
/**
* Gets the columns that together constitute the id, eg: ["lat", "lon"] for
* fixed features or ["id"].
*/
@computed
get idColumns(): TableColumn[] | undefined {
const idColumns = filterOutUndefined(
this.timeTraits.idColumns
? this.timeTraits.idColumns.map(name => this.resolveColumn(name))
: []
);
return idColumns.length > 0 ? idColumns : undefined;
}
/**
* Gets the time column for this style, if any.
*/
@computed
get timeColumn(): TableColumn | undefined {
return this.timeTraits.timeColumn === null
? undefined
: this.resolveColumn(this.timeTraits.timeColumn);
}
/**
* Gets the end time column for this style, if any.
*/
@computed
get endTimeColumn(): TableColumn | undefined {
return this.resolveColumn(this.timeTraits.endTimeColumn);
}
/**
* Gets the chart X-axis column for this style, if any.
*/
@computed
get xAxisColumn(): TableColumn | undefined {
return this.resolveColumn(this.chartTraits.xAxisColumn);
}
/**
* Gets the color column for this style, if any.
*/
@computed
get colorColumn(): TableColumn | undefined {
return this.resolveColumn(this.colorTraits.colorColumn);
}
/**
* Gets the scale column for this style, if any.
*/
@computed
get pointSizeColumn(): TableColumn | undefined {
return this.resolveColumn(this.pointSizeTraits.pointSizeColumn);
}
/**
* Determines if this style is visualized as points on a map.
*/
isPoints(): this is {
readonly longitudeColumn: TableColumn;
readonly latitudeColumn: TableColumn;
} {
return (
this.longitudeColumn !== undefined && this.latitudeColumn !== undefined
);
}
/**
* Determines if this style is visualized as time varying points tracked by id
*/
isTimeVaryingPointsWithId(): this is {
readonly longitudeColumn: TableColumn;
readonly latitudeColumn: TableColumn;
readonly idColumns: TableColumn[];
readonly timeColumn: TableColumn;
readonly timeIntervals: (JulianDate | null)[];
} {
return (
this.longitudeColumn !== undefined &&
this.latitudeColumn !== undefined &&
this.idColumns !== undefined &&
this.timeColumn !== undefined &&
this.timeIntervals !== undefined &&
this.moreThanOneTimeInterval
);
}
/**
* Determines if this style is visualized as regions on a map.
*/
isRegions(): this is { readonly regionColumn: TableColumn } {
return this.regionColumn !== undefined;
}
/**
* Determines if this style is visualized on a chart.
*/
isChart(): this is {
readonly xAxisColumn: TableColumn;
} {
return this.xAxisColumn !== undefined && this.chartTraits.lines.length > 0;
}
/** Style isSampled by default. TimeTraits.isSampled will be used if defined. If not, and color column is binary - isSampled will be false. */
@computed get isSampled() {
if (isDefined(this.timeTraits.isSampled)) return this.timeTraits.isSampled;
if (isDefined(this.colorColumn) && this.colorColumn.isScalarBinary)
return false;
return true;
}
@computed get tableColorMap() {
return new TableColorMap(
this.tableModel.name ?? this.tableModel.uniqueId,
this.colorColumn,
this.colorTraits
);
}
@computed get colorMap() {
return this.tableColorMap.colorMap;
}
@computed
get pointSizeMap(): PointSizeMap {
const pointSizeColumn = this.pointSizeColumn;
const pointSizeTraits = this.pointSizeTraits;
if (pointSizeColumn && pointSizeColumn.type === TableColumnType.scalar) {
const maximum = pointSizeColumn.valuesAsNumbers.maximum;
const minimum = pointSizeColumn.valuesAsNumbers.minimum;
if (isDefined(maximum) && isDefined(minimum) && maximum !== minimum) {
return new ScalePointSizeMap(
minimum,
maximum,
pointSizeTraits.nullSize,
pointSizeTraits.sizeFactor,
pointSizeTraits.sizeOffset
);
}
}
// can't scale point size by values in this column, so use same point size for every value
return new ConstantPointSizeMap(pointSizeTraits.sizeOffset);
}
/**
* Returns a `TimeInterval` for each row in the table.
*/
@computed
get timeIntervals(): (TimeInterval | null)[] | undefined {
const timeColumn = this.timeColumn;
if (timeColumn === undefined) {
return;
}
const lastDate = timeColumn.valuesAsJulianDates.maximum;
const intervals = timeColumn.valuesAsJulianDates.values.map((date, i) => {
if (!date) {
return null;
}
const startDate = this.startJulianDates?.[i] ?? date;
const finishDate = this.finishJulianDates?.[i] ?? undefined;
return new TimeInterval({
start: startDate,
stop: finishDate,
isStopIncluded: JulianDate.equals(finishDate, lastDate),
data: date
});
});
return intervals;
}
/** Is there more than one unique time interval */
@computed get moreThanOneTimeInterval() {
if (this.timeIntervals) {
// Find first non-null time interval
const firstInterval = this.timeIntervals?.find(t => t) as
| TimeInterval
| undefined;
if (firstInterval) {
// Does there exist an interval which is different from firstInterval (that is to say, does there exist at least two unique intervals)
return !!this.timeIntervals?.find(
t =>
t &&
(!firstInterval.start.equals(t.start) ||
!firstInterval.stop.equals(t.stop))
);
}
}
return false;
}
/**
* Returns a start date for each row in the table.
* If `timeTraits.spreadStartTime` is true - the start dates will be the earliest value for all features (eg sensor IDs) - even if the time value is **after** the earliest time step. This means that at time step 0, all features will be displayed.
*/
@computed
private get startJulianDates(): (JulianDate | null)[] | undefined {
const timeColumn = this.timeColumn;
if (timeColumn === undefined) {
return;
}
const firstDate = timeColumn.valuesAsJulianDates.minimum;
if (!this.timeTraits.spreadStartTime || !firstDate)
return timeColumn.valuesAsJulianDates.values;
const startDates = timeColumn.valuesAsJulianDates.values.slice();
this.rowGroups.forEach(([groupId, rowIds]) => {
// Find row ID with earliest date in this rowGroup
const firstRowId = rowIds
.filter(id => startDates[id])
.sort((idA, idB) =>
JulianDate.compare(startDates[idA]!, startDates[idB]!)
)[0];
// Set it to earliest date in the entire column
if (isDefined(firstRowId)) startDates[firstRowId] = firstDate;
});
return startDates;
}
/**
* Returns a finish date for each row in the table.
*/
@computed
private get finishJulianDates(): (JulianDate | null)[] | undefined {
if (this.endTimeColumn) {
return this.endTimeColumn.valuesAsJulianDates.values;
}
const timeColumn = this.timeColumn;
if (timeColumn === undefined) {
return;
}
const startDates = timeColumn.valuesAsJulianDates.values;
// If displayDuration trait is set, use that to set finish date
if (this.timeTraits.displayDuration !== undefined) {
return startDates.map(date =>
date
? JulianDate.addMinutes(
date,
this.timeTraits.displayDuration!,
new JulianDate()
)
: null
);
}
const finishDates: (JulianDate | null)[] = [];
// Otherwise estimate a final duration value to calculate the end date for groups
// that have only one row. Fallback to a global default if an estimate
// cannot be found.
for (let i = 0; i < this.rowGroups.length; i++) {
const rowIds = this.rowGroups[i][1];
const sortedStartDates = sortedUniqueDates(
rowIds.map(id => timeColumn.valuesAsJulianDates.values[id])
);
const finalDuration =
estimateFinalDurationSeconds(sortedStartDates) ??
DEFAULT_FINAL_DURATION_SECONDS;
const startDatesForGroup = rowIds.map(id => startDates[id]);
const finishDatesForGroup = this.calculateFinishDatesFromStartDates(
startDatesForGroup,
finalDuration
);
finishDatesForGroup.forEach((date, i) => {
finishDates[rowIds[i]] = date;
});
}
return finishDates;
}
/** Get rows grouped by id. Id will be calculated using idColumns, latitude/longitude columns or region column
*/
@computed get rowGroups() {
let groupByCols = this.idColumns;
if (!groupByCols) {
// If points use lat long
if (this.latitudeColumn && this.longitudeColumn) {
groupByCols = [this.latitudeColumn, this.longitudeColumn];
// If region - use region col
} else if (this.regionColumn) groupByCols = [this.regionColumn];
}
if (!groupByCols) groupByCols = [];
const tableRowIds = this.tableModel.rowIds;
return (
Object.entries(
groupBy(tableRowIds, rowId =>
groupByCols!
.map(col => {
// If using region column as ID - only use valid regions
if (col.type === TableColumnType.region) {
return col.valuesAsRegions.regionIds[rowId];
}
return col.values[rowId];
})
.join("-")
)
)
// Filter out bad IDs
.filter(value => value[0] !== "")
);
}
/**
* Computes an and end date for each given start date. The end date for a
* given start date is the next higher date in the input. To compute the end
* date for the last date in the input, we estimate a duration based on the
* average interval between dates in the input. If the input has only one
* date, then an estimate cannot be made, in that case we use the
* `defaultFinalDurationSeconds` to compute the end date.
*/
private calculateFinishDatesFromStartDates(
startDates: (JulianDate | null | undefined)[],
defaultFinalDurationSeconds: number
) {
const sortedStartDates: JulianDate[] = sortedUniqueDates(startDates);
// Calculate last date based on if spreadFinishTime is true:
// - If true, use the maximum date in the entire timeColumn
// - If false, use the last date in startDates - which is the last date in the current row group
const lastDate =
this.timeTraits.spreadFinishTime &&
this.timeColumn?.valuesAsJulianDates.maximum
? this.timeColumn.valuesAsJulianDates.maximum
: sortedStartDates[sortedStartDates.length - 1];
return startDates.map(date => {
if (!date) {
return null;
}
const nextDateIndex = binarySearch(
sortedStartDates,
date,
(d1: JulianDate, d2: JulianDate) => JulianDate.compare(d1, d2)
);
const nextDate = sortedStartDates[nextDateIndex + 1];
if (nextDate) {
return nextDate;
} else {
// This is the last date in the row, so calculate a final date
const finalDurationSeconds =
estimateFinalDurationSeconds(sortedStartDates) ||
defaultFinalDurationSeconds;
return addSecondsToDate(lastDate, finalDurationSeconds);
}
});
}
private resolveColumn(name: string | undefined): TableColumn | undefined {
if (name === undefined) {
return undefined;
}
return this.tableModel.tableColumns.find(column => column.name === name);
}
}
/**
* Returns an array of sorted unique dates
*/
function sortedUniqueDates(
dates: Readonly<(JulianDate | null | undefined)[]>
): JulianDate[] {
const nonNullDates: JulianDate[] = dates.filter((d): d is JulianDate => !!d);
return nonNullDates
.sort((a, b) => JulianDate.compare(a, b))
.filter((d, i, ds) => i === 0 || !JulianDate.equals(d, ds[i - 1]));
}
function addSecondsToDate(date: JulianDate, seconds: number) {
return JulianDate.addSeconds(date, seconds, new JulianDate());
}
function estimateFinalDurationSeconds(
sortedDates: JulianDate[]
): number | undefined {
const n = sortedDates.length;
if (n > 1) {
const finalDurationSeconds =
JulianDate.secondsDifference(sortedDates[n - 1], sortedDates[0]) /
(n - 1);
return finalDurationSeconds;
}
} | the_stack |
import * as vscode from 'vscode';
import type Bluebird from 'bluebird';
import type MWBot from 'mwbot';
import { Action, Prop, RvProp, alterNativeValues } from './args';
import { ReadPageConvert, ReadPageResult, Main, Revision, Jump, Page } from '../../interface_definition/readPageInterface';
import { OldTokensConvert, OldTokensResult } from '../../interface_definition/oldTokensInterface';
import { getDefaultBot, getLoggedInBot } from './bot';
import { TokensConvert, TokensResult } from '../../interface_definition/tokensInterface';
import { showMWErrorMessage } from './err_msg';
interface ContentInfo {
content: string;
info?: Record<string, string | undefined>;
}
/**
* Write/Post Page
*/
export async function postPage(): Promise<void> {
async function getEditToken(bot: MWBot): Promise<string> {
const errors: unknown[] = [undefined, undefined];
try {
const args: Record<string, string> = {
action: Action.query,
meta: 'tokens',
type: 'csrf'
};
const result: Bluebird<unknown> = await bot.request(args);
const reNew: TokensResult = TokensConvert.toTokensResult(result);
const token: string | undefined = reNew.query?.tokens?.csrftoken;
if (token) {
return token;
}
}
catch (error) {
errors[0] = error;
}
if (errors[0] !== undefined) {
try {
const args: Record<string, string> = {
action: "tokens",
type: "edit"
};
const result = await bot.request(args);
const reOld: OldTokensResult = OldTokensConvert.toOldTokensResult(result);
const token: string | undefined = reOld.tokens?.edittoken;
if (token) {
return token;
}
}
catch (error) {
errors[1] = error;
}
}
const error = Error('Could not get edit token:' +
'NEW: ' + ((errors[0] instanceof Error) ? errors[0].message : "") +
'OLD: ' + ((errors[1] instanceof Error) ? errors[1].message : ""));
throw error;
}
const config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("wikitext");
const tBot: MWBot | undefined = await getLoggedInBot();
if (tBot === undefined) {
vscode.window.showErrorMessage("Bot is undefined! You may be not logged in.");
return undefined;
}
const wikiContent: string | undefined = vscode.window.activeTextEditor?.document.getText();
if (wikiContent === undefined) {
vscode.window.showWarningMessage("There is no active text editor.");
return undefined;
}
const contentInfo: ContentInfo = getContentInfo(wikiContent);
// console.log(contentInfo);
const skip: boolean = config.get("skipEnteringPageTitle") as boolean;
const wikiTitle: string | undefined = skip && contentInfo.info?.pageTitle || await vscode.window.showInputBox({
value: contentInfo.info?.pageTitle || "",
ignoreFocusOut: true,
prompt: "Enter the page name here."
});
if (!wikiTitle) {
return undefined;
}
let wikiSummary: string | undefined = await vscode.window.showInputBox({
ignoreFocusOut: false,
prompt: 'Enter the summary of this edit action.',
placeHolder: '// Edit via Wikitext Extension for VSCode'
});
if (wikiSummary === undefined) {
return undefined;
}
wikiSummary = `{wikiSummary} // Edit via Wikitext Extension for VSCode`.trim();
const barMessage: vscode.Disposable = vscode.window.setStatusBarMessage("Wikitext: Posting...");
try {
tBot.editToken = await getEditToken(tBot);
await tBot.edit(wikiTitle, contentInfo.content, wikiSummary).then(response => {
if (response.edit.nochange !== undefined) {
vscode.window.showWarningMessage(
`No changes have occurred: "${response.edit.nochange}", Edit page "${response.edit.title}" (Page ID: "${response.edit.pageid}") action status is "${response.edit.result}" with Content Model "${response.edit.contentmodel}". Watched by: "${response.edit.watched}".`
);
}
else {
vscode.window.showInformationMessage(
`Edit page "${response.edit.title}" (Page ID: "${response.edit.pageid}") action status is "${response.edit.result}" with Content Model "${response.edit.contentmodel}" (Version: "${response.edit.oldrevid}" => "${response.edit.newrevid}", Time: "${response.edit.newtimestamp}"). Watched by: "${response.edit.watched}".`
);
}
});
}
catch (error) {
showMWErrorMessage('postPage', error, `Your Token: ${tBot?.editToken}`);
}
finally {
barMessage.dispose();
}
}
/**
* Read/Pull Page
*/
export async function pullPage(): Promise<void> {
const config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("wikitext");
// constructing
const tBot: MWBot | undefined = await getDefaultBot();
if (tBot === undefined) { return undefined; }
// get title name
const title: string | undefined = await vscode.window.showInputBox({
prompt: "Enter the page name here.",
ignoreFocusOut: true
});
// if title is null or empty, do nothing
if (!title) { return undefined; }
const args: Record<string, string> = {
action: Action.query,
prop: Prop.reVisions,
rvprop: alterNativeValues(RvProp.content, RvProp.ids),
rvslots: "*",
titles: title
};
if (config.get("redirects")) {
args['redirects'] = "true";
}
getPageCode(args, tBot);
}
export function closeEditor() {
const editor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
// Delete all text
editor?.edit((editBuilder: vscode.TextEditorEdit) =>
editBuilder.delete(
new vscode.Range( // All
new vscode.Position(0, 0), // Start
editor.document.lineAt(editor.document.lineCount - 1).rangeIncludingLineBreak.end // End
)
)
).then(() =>
// Close editor
vscode.commands.executeCommand('workbench.action.closeActiveEditor')
);
}
type PageInfo = "pageTitle" | "pageID" | "revisionID" | "contentModel" | "contentFormat";
export async function getPageCode(args: Record<string, string>, tBot: MWBot): Promise<void> {
function getInfoHead(info: Record<PageInfo, string | undefined>): string {
const commentList: Record<string, [string, string]> = {
wikitext: ["", ""],
jsonc: ["/*", "*/"],
lua: ["--[=[", "--]=]"],
javascript: ["/*", "*/"],
css: ["/*", "*/"],
php: ["/*", "*/"],
'flow-board': ["/*", "*/"],
};
const headInfo: Record<string, string | undefined> = {
comment: "Please do not remove this struct. It's record contains some important information of edit. This struct will be removed automatically after you push edits.",
...info
};
const infoLine: string = Object.keys(headInfo).
map((key: string) => ` ${key} = #${headInfo[key]}#`).
join("\r");
return commentList[info?.['contentModel'] || "wikitext"].join(`<%-- [PAGE_INFO]
${infoLine}
[END_PAGE_INFO] --%>`);
}
const barMessage: vscode.Disposable = vscode.window.setStatusBarMessage("Wikitext: Getting code...");
try {
// get request result
const result = await tBot.request(args);
// console.log(result);
// Convert result as class
const re: ReadPageResult = ReadPageConvert.toReadPageResult(result);
if (re.query?.interwiki) {
vscode.window.showWarningMessage(
`Interwiki page "${re.query.interwiki[0].title}" in space "${re.query.interwiki[0].iw}" are currently not supported. Please try to modify host.`
);
}
// get first page
const page: Page | undefined = re.query?.pages?.[Object.keys(re.query.pages)[0]];
// need a page elements
if (!page) { return undefined; }
if (page.missing !== undefined || page.invalid !== undefined) {
vscode.window.showWarningMessage(
`The page "${page.title}" you are looking for does not exist. ${page.invalidreason ?? ""}`);
return undefined;
}
// first revision
const revision: Revision | undefined = page.revisions?.[0];
const content: Main | Revision | undefined = revision?.slots?.main || revision;
const info: Record<PageInfo, string | undefined> = {
pageTitle: page.title,
pageID: page.pageid?.toString(),
revisionID: revision?.revid?.toString(),
contentModel: content?.contentmodel,
contentFormat: content?.contentformat
};
const infoHead: string = getInfoHead(info);
const textDocument: vscode.TextDocument = await vscode.workspace.openTextDocument({
language: (content?.contentmodel === "flow-board") ? "jsonc" : content?.contentmodel,
content: infoHead + "\r\r" + content?.["*"]
});
vscode.window.showTextDocument(textDocument);
const normalized: Jump | undefined = re.query?.normalized?.[0];
const redirects: Jump | undefined = re.query?.redirects?.[0];
vscode.window.showInformationMessage(
`Opened page "${page.title}" with Model ${content?.contentmodel}.` +
(normalized ? ` Normalized: ${normalized.from} => ${normalized.to}` : "") +
(redirects ? ` Redirect: ${redirects.from} => ${redirects.to}` : "")
);
}
catch (error) {
showMWErrorMessage('getPageCode', error);
}
finally {
barMessage.dispose();
}
}
// TODO: uploadFile, deletedPage
export function getContentInfo(content: string): ContentInfo {
const info: string | undefined = content.match(
/(?<=<%--\s*\[PAGE_INFO\])[\s\S]*?(?=\[END_PAGE_INFO\]\s*--%>)/
)?.[0];
let pageInfo: Record<PageInfo, string | undefined> | undefined;
if (info) {
const getInfo = (infoName: PageInfo): string | undefined => {
const nameFirst: string = infoName[0];
const nameRest: string = infoName.substring(1);
const reg = new RegExp(`(?<=[${nameFirst.toLowerCase()}${nameFirst.toUpperCase()}]${nameRest}\\s*=\\s*#).*?(?=#)`);
return info.match(reg)?.[0];
};
pageInfo = {
pageTitle: getInfo("pageTitle"),
pageID: getInfo("pageID"),
revisionID: getInfo("revisionID"),
contentModel: getInfo("contentModel"),
contentFormat: getInfo("contentFormat")
};
content = content.replace(/\s*(?:\/\*|--\[=\[)?<%--\s*\[PAGE_INFO\][\s\S]*?\[END_PAGE_INFO\]\s*--%>\s*(?:\*\/|--\]=\])?/, '');
}
return { content: content, info: pageInfo };
} | the_stack |
import * as collabs from "@collabs/collabs";
import { Message } from "@collabs/collabs";
import { GroupComponentMessage } from "../generated/proto_compiled";
export interface GroupTranslateEvent extends collabs.CollabEvent {
readonly dX1: number;
readonly dY1: number;
readonly dX2: number;
readonly dY2: number;
}
export interface GroupRotateEvent extends collabs.CollabEvent {
readonly rotated1: number;
readonly rotated2: number;
}
export interface GroupReflectXEvent extends collabs.CollabEvent {
readonly reflect1: number;
readonly reflect2: number;
}
export interface GroupReflectYEvent extends collabs.CollabEvent {
readonly reflect1: number;
readonly reflect2: number;
}
export interface GroupEventsRecord extends collabs.CollabEventsRecord {
Translate: GroupTranslateEvent;
Rotate: GroupRotateEvent;
ReflectX: GroupReflectXEvent;
ReflectY: GroupReflectYEvent;
}
export class GroupState {
X1: number;
Y1: number;
rotate1: number;
reflectX1: number;
reflectY1: number;
X2: number;
Y2: number;
rotate2: number;
reflectX2: number;
reflectY2: number;
constructor() {
this.X1 = 0;
this.Y1 = 0;
this.reflectX1 = 1;
this.reflectY1 = 1;
this.rotate1 = 0;
this.X2 = 0;
this.Y2 = 0;
this.reflectX2 = 1;
this.reflectY2 = 1;
this.rotate2 = 0;
}
}
export class TranslateComponent extends collabs.CPrimitive<GroupEventsRecord> {
readonly state: GroupState;
constructor(initToken: collabs.InitToken, initialState: GroupState) {
super(initToken);
this.state = initialState;
}
translate(newX: number, newY: number, img: number) {
if (newX !== 0 || newY !== 0) {
var message;
if (img === 1) {
message = GroupComponentMessage.create({ X1: newX, Y1: newY });
} else if (img === 2) {
message = GroupComponentMessage.create({ X2: newX, Y2: newY });
} else {
message = GroupComponentMessage.create({
X1: newX,
Y1: newY,
X2: newX,
Y2: newY,
});
}
let buffer = GroupComponentMessage.encode(message).finish();
super.sendPrimitive(buffer);
}
}
protected receivePrimitive(message: Uint8Array, meta: collabs.MessageMeta) {
let decoded = GroupComponentMessage.decode(message);
this.state.X1 += decoded.X1;
this.state.Y1 += decoded.Y1;
this.state.X2 += decoded.X2;
this.state.Y2 += decoded.Y2;
this.emit("Translate", {
meta,
dX1: decoded.X1,
dY1: decoded.Y1,
dX2: decoded.X2,
dY2: decoded.Y2,
});
}
canGC() {
return (
this.state.X1 === 0 &&
this.state.Y1 === 0 &&
this.state.X2 === 0 &&
this.state.Y2 === 0
);
}
save(): Uint8Array {
let message = GroupComponentMessage.create({
X1: this.state.X1,
Y1: this.state.Y1,
X2: this.state.X2,
Y2: this.state.Y2,
});
return GroupComponentMessage.encode(message).finish();
}
load(saveData: collabs.Optional<Uint8Array>) {
if (!saveData.isPresent) return;
this.state.X1 = GroupComponentMessage.decode(saveData.get()).X1;
this.state.Y1 = GroupComponentMessage.decode(saveData.get()).Y1;
this.state.X2 = GroupComponentMessage.decode(saveData.get()).X2;
this.state.Y2 = GroupComponentMessage.decode(saveData.get()).Y2;
}
}
export class RotateComponent extends collabs.CPrimitive<GroupEventsRecord> {
readonly state: GroupState;
constructor(initToken: collabs.InitToken, initialState: GroupState) {
super(initToken);
this.state = initialState;
}
rotate(degrees: number, img: number) {
if (degrees !== 0) {
var message;
if (img === 1) {
message = GroupComponentMessage.create({ rotate1: degrees });
} else if (img === 2) {
message = GroupComponentMessage.create({ rotate2: degrees });
} else {
message = GroupComponentMessage.create({
rotate1: degrees,
rotate2: degrees,
});
}
let buffer = GroupComponentMessage.encode(message).finish();
super.sendPrimitive(buffer);
}
}
semidirectDiffs(
dDegrees: number,
X1: number,
Y1: number,
X2: number,
Y2: number
) {
let toRadians = (degrees: number) => {
return degrees * (Math.PI / 180);
};
let cos = Math.cos(toRadians(dDegrees));
let sin = Math.sin(toRadians(dDegrees));
let newX1 = X1 * cos - Y1 * sin;
let newY1 = X1 * sin + Y1 * cos;
let newX2 = X2 * cos - Y2 * sin;
let newY2 = X2 * sin + Y2 * cos;
return [newX1, newX2, newY1, newY2];
}
protected receivePrimitive(message: Uint8Array, meta: collabs.MessageMeta) {
let decoded = GroupComponentMessage.decode(message);
this.state.rotate1 += decoded.rotate1;
this.state.rotate2 += decoded.rotate2;
// Check for group rotation
if (decoded.rotate1 === decoded.rotate2) {
if (decoded.rotate1 < 0) {
[this.state.X1, this.state.X2, this.state.Y1, this.state.Y2] =
this.semidirectDiffs(
decoded.rotate1,
this.state.X1,
this.state.Y1,
this.state.X2,
this.state.Y2
);
} else {
[this.state.X1, this.state.X2, this.state.Y1, this.state.Y2] =
this.semidirectDiffs(
decoded.rotate1 - 360,
this.state.X1,
this.state.Y1,
this.state.X2,
this.state.Y2
);
}
}
this.emit("Rotate", {
meta,
rotated1: decoded.rotate1,
rotated2: decoded.rotate2,
});
}
canGC() {
return this.state.rotate1 === 0 && this.state.rotate2 === 0;
}
save(): Uint8Array {
let message = GroupComponentMessage.create({
rotate1: this.state.rotate1,
rotate2: this.state.rotate2,
});
return GroupComponentMessage.encode(message).finish();
}
load(saveData: collabs.Optional<Uint8Array>) {
if (!saveData.isPresent) return;
this.state.rotate1 = GroupComponentMessage.decode(saveData.get()).rotate1;
this.state.rotate2 = GroupComponentMessage.decode(saveData.get()).rotate2;
}
}
export class ReflectXComponent extends collabs.CPrimitive<GroupEventsRecord> {
readonly state: GroupState;
constructor(initToken: collabs.InitToken, initialState: GroupState) {
super(initToken);
this.state = initialState;
}
reflect(img: number) {
var message;
if (img === 1) {
message = GroupComponentMessage.create({ reflectX1: -1, reflectX2: 1 });
} else if (img === 2) {
message = GroupComponentMessage.create({ reflectX1: 1, reflectX2: -1 });
} else {
message = GroupComponentMessage.create({ reflectX1: -1, reflectX2: -1 });
}
let buffer = GroupComponentMessage.encode(message).finish();
super.sendPrimitive(buffer);
}
protected receivePrimitive(message: Uint8Array, meta: collabs.MessageMeta) {
let decoded = GroupComponentMessage.decode(message);
this.state.reflectX1 *= decoded.reflectX1;
this.state.reflectX2 *= decoded.reflectX2;
// Check for group reflection
if (decoded.reflectX1 === -1 && decoded.reflectX2 === -1) {
this.state.rotate1 *= -1;
this.state.rotate2 *= -1;
this.state.Y1 *= -1;
this.state.Y2 *= -1;
}
this.emit("ReflectX", {
meta,
reflect1: decoded.reflectX1,
reflect2: decoded.reflectX2,
});
}
canGC() {
return this.state.reflectX1 === 1;
}
save(): Uint8Array {
let message = GroupComponentMessage.create({
reflectX1: this.state.reflectX1,
});
return GroupComponentMessage.encode(message).finish();
}
load(saveData: collabs.Optional<Uint8Array>) {
if (!saveData.isPresent) return;
this.state.reflectX1 = GroupComponentMessage.decode(
saveData.get()
).reflectX1;
}
}
export class ReflectYComponent extends collabs.CPrimitive<GroupEventsRecord> {
readonly state: GroupState;
constructor(initToken: collabs.InitToken, initialState: GroupState) {
super(initToken);
this.state = initialState;
}
reflect(img: number) {
var message;
if (img === 1) {
message = GroupComponentMessage.create({ reflectY1: -1, reflectY2: 1 });
} else if (img === 2) {
message = GroupComponentMessage.create({ reflectY1: 1, reflectY2: -1 });
} else {
message = GroupComponentMessage.create({ reflectY1: -1, reflectY2: -1 });
}
let buffer = GroupComponentMessage.encode(message).finish();
super.sendPrimitive(buffer);
}
protected receivePrimitive(message: Uint8Array, meta: collabs.MessageMeta) {
let decoded = GroupComponentMessage.decode(message);
this.state.reflectY1 *= decoded.reflectY1;
this.state.reflectY2 *= decoded.reflectY2;
// Check for group reflection
if (decoded.reflectY1 === -1 && decoded.reflectY2 === -1) {
this.state.rotate1 *= -1;
this.state.rotate2 *= -1;
this.state.X1 *= -1;
this.state.X2 *= -1;
}
this.emit("ReflectY", {
meta,
reflect1: decoded.reflectY1,
reflect2: decoded.reflectY2,
});
}
canGC() {
return this.state.reflectY1 === 1 && this.state.reflectY2 === 1;
}
save(): Uint8Array {
let message = GroupComponentMessage.create({
reflectY1: this.state.reflectY1,
reflectY2: this.state.reflectY2,
});
return GroupComponentMessage.encode(message).finish();
}
load(saveData: collabs.Optional<Uint8Array>) {
if (!saveData.isPresent) return;
this.state.reflectY1 = GroupComponentMessage.decode(
saveData.get()
).reflectY1;
this.state.reflectY2 = GroupComponentMessage.decode(
saveData.get()
).reflectY2;
}
}
export class GroupCRDT extends collabs.MultipleSemidirectProduct<
GroupState,
GroupEventsRecord
> {
private translateCrdt: TranslateComponent;
private rotateCrdt: RotateComponent;
private reflectXCrdt: ReflectXComponent;
private reflectYCrdt: ReflectYComponent;
constructor(initToken: collabs.InitToken) {
super(initToken, false);
const state = new GroupState();
super.setupState(state);
this.translateCrdt = super.setupOneCRDT(
collabs.Pre(TranslateComponent)(state)
);
this.rotateCrdt = super.setupOneCRDT(collabs.Pre(RotateComponent)(state));
this.reflectXCrdt = super.setupOneCRDT(
collabs.Pre(ReflectXComponent)(state)
);
this.reflectYCrdt = super.setupOneCRDT(
collabs.Pre(ReflectYComponent)(state)
);
this.translateCrdt.on("Translate", (event) =>
super.emit("Translate", event)
);
this.rotateCrdt.on("Rotate", (event) => super.emit("Rotate", event));
this.reflectXCrdt.on("ReflectX", (event) => super.emit("ReflectX", event));
this.reflectYCrdt.on("ReflectY", (event) => super.emit("ReflectY", event));
}
// Want to "add on" m2's actions to m1. Start with m1 values and
// add reflection or rotation as needed.
protected action(
m2MessagePath: Message[],
_m2Meta: collabs.MessageMeta | null,
m2Index: number,
m1MessagePath: Message[],
_m1Meta: collabs.MessageMeta | null
): { m1MessagePath: Message[] } | null {
let m2Decoded = GroupComponentMessage.decode(<Uint8Array>m2MessagePath[0]);
let m1Decoded = GroupComponentMessage.decode(<Uint8Array>m1MessagePath[0]);
var XArg1: number = m1Decoded!.X1 || 0;
var YArg1: number = m1Decoded!.Y1 || 0;
var rotateArg1: number = m1Decoded!.rotate1 || 0;
var reflectXArg1: number = m1Decoded!.reflectX1 || 1;
var reflectYArg1: number = m1Decoded!.reflectY1 || 1;
var XArg2: number = m1Decoded!.X2 || 0;
var YArg2: number = m1Decoded!.Y2 || 0;
var rotateArg2: number = m1Decoded!.rotate2 || 0;
var reflectXArg2: number = m1Decoded!.reflectX2 || 1;
var reflectYArg2: number = m1Decoded!.reflectY2 || 1;
switch (m2Index) {
case 3:
reflectYArg1 *= m2Decoded.reflectY1;
reflectYArg2 *= m2Decoded.reflectY2;
// Check for group reflection
if (m2Decoded.reflectY1 === -1 && m2Decoded.reflectY2 === -1) {
rotateArg1 *= -1;
rotateArg2 *= -1;
XArg1 *= -1;
XArg2 *= -1;
}
break;
case 2:
reflectXArg1 *= m2Decoded.reflectX1;
reflectXArg2 *= m2Decoded.reflectX2;
// Check for group reflection
if (m2Decoded.reflectX1 === -1 && m2Decoded.reflectX2 === -1) {
rotateArg1 *= -1;
rotateArg2 *= -1;
YArg1 *= -1;
YArg2 *= -1;
}
break;
case 1:
rotateArg1 += m2Decoded.rotate1;
rotateArg2 += m2Decoded.rotate2;
// Check for group rotation
if (m2Decoded.rotate1 === m2Decoded.rotate2) {
if (m2Decoded.rotate1 < 0) {
[XArg1, XArg2, YArg1, YArg2] = this.rotateCrdt.semidirectDiffs(
m2Decoded.rotate1,
XArg1,
YArg1,
XArg2,
YArg2
);
} else {
[XArg1, XArg2, YArg1, YArg2] = this.rotateCrdt.semidirectDiffs(
m2Decoded.rotate1 - 360,
XArg1,
YArg1,
XArg2,
YArg2
);
}
}
break;
default:
XArg1 += m1Decoded.X1;
YArg1 += m1Decoded.Y1;
XArg2 += m1Decoded.X2;
YArg2 += m1Decoded.Y2;
}
let acted = GroupComponentMessage.create({
X1: XArg1,
Y1: YArg1,
rotate1: rotateArg1,
reflectX1: reflectXArg1,
reflectY1: reflectYArg1,
X2: XArg2,
Y2: YArg2,
rotate2: rotateArg2,
reflectX2: reflectXArg2,
reflectY2: reflectYArg2,
});
return {
m1MessagePath: [GroupComponentMessage.encode(acted).finish()],
};
}
translate(X: number, Y: number, img: number) {
this.translateCrdt.translate(X, Y, img);
}
rotate(degrees: number, img: number) {
this.rotateCrdt.rotate(degrees, img);
}
reflectX(img: number) {
this.reflectXCrdt.reflect(img);
}
reflectY(img: number) {
this.reflectYCrdt.reflect(img);
}
getState() {
return this.state.internalState;
}
} | the_stack |
const mix = (a: number, b: number, m: number) => (1 - m) * a + m * b;
const mixCol = (a: Color, b: Color, m: number): Color => ({
r: mix(a.r, b.r, m),
g: mix(a.g, b.g, m),
b: mix(a.b, b.b, m),
a: mix(a.a, b.a, m),
});
const halfV = {x: 0.5, y: 0.5};
const v10 = {x: 1, y: 0};
const v01 = {x: 0, y: 1};
const v11 = {x: 1, y: 1};
const n21 = (v: Vec2): number => ((Math.sin(v.x * 100 + v.y * 6574) + 1) * 564) % 1;
const noise = (v: Vec2): number => {
const lv = fractV(v);
const id = floorV(v);
const bl = n21(id);
const br = n21(addV(id, v10));
const b = mix(bl, br, lv.x);
const tl = n21(addV(id, v01));
const tr = n21(addV(id, v11));
const t = mix(tl, tr, lv.x);
return mix(b, t, lv.y);
};
const smoothstep = (min: number, max: number, value: number) => {
const x = clamp((value - min) / (max - min), 0, 1);
return x * x * (3 - 2 * x);
};
const newCol = (r: number = 1, g: number = 1, b: number = 1, a: number = 1): Color => ({r, g, b, a});
const mulCol = (color: Color, v: number) => ({
r: color.r * v,
g: color.g * v,
b: color.b * v,
a: color.a
});
const addCol = (a: Color, b: Color) => {
return {
r: a.r + b.r * b.a,
g: a.g + b.g * b.a,
b: a.b + b.b * b.a,
a: a.a + b.a
};
};
const generateImage = (width: number, height: number, cb: (v: Vec2) => Color) => {
const [canvas, context] = createCanvas(width, height);
const imageData = context.getImageData(0, 0, width, height);
const buf = new ArrayBuffer(imageData.data.length);
const buf8 = new Uint8ClampedArray(buf);
const data32 = new Uint32Array(buf);
const v: Partial<Vec2> = {};
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
v.x = x / (width - 1);
v.y = y / (height - 1);
const c = cb(v as Vec2);
data32[y * width + x] =
(clamp(c.a! * 255, 0, 255) << 24) | // alpha
(clamp(c.b! * 255, 0, 255) << 16) | // blue
(clamp(c.g! * 255, 0, 255) << 8) | // green
clamp(c.r! * 255, 0, 255);
}
}
imageData.data.set(buf8);
context.putImageData(imageData, 0, 0);
return canvas;
};
// https://gist.github.com/sakrist/8706749
const createHexField = (v: Vec2, scale: number): number => {
let {x, y} = mulVS(v, scale);
x *= 0.57735 * 2.0;
y += (Math.floor(x) % 2) * 0.5;
x = Math.abs(x % 1 - 0.5);
y = Math.abs(y % 1 - 0.5);
return Math.abs(Math.max(x * 1.5 + y, y * 2.0) - 1.0);
};
const createMetalPlate = (a: number, d: number): number => {
const shading = smoothstep(0.91, 0.94, d) - smoothstep(0.41, 0.42, d);
a += shading;
return 0.9 + 0.1 * Math.sin(a * 6) * 0.9 + 0.1 * Math.sin(a * 4)
- (noise({x: (a + 4 + d * 5) * 2, y: d * 80}) * 0.1) + shading * 0.2;
};
const createCoilSprite = (size: number): Canvas => {
const sw = 4 / size;
const hexFieldScale = size / 4;
const hexFieldBrightness = 0.7;
const ringBrightness = 0.4;
const gridShadowBlur = 0.1;
const gridShadowStrength = 1;
const ringWidth = 0.2;
const buttonSize = 0.5;
const gridColor = newCol(0.615, 0.705, 1, 1);
const metalColor = newCol(1, 1, 1, 1);
const shadowBlur = 0.2;
const shadowDistance = 0.04;
const shadowScale = 1.1;
const shadowStrength = 0.5;
const image = generateImage(Math.round(size * 1.1), Math.round(size * 1.1), v => {
v = mulVS(v, 1.1); // scale to make room for shadow
const centerV = subV(v, halfV);
const a = Math.atan2(centerV.y, centerV.x);
const d = lenV(centerV) * 2;
let grid = hexFieldBrightness * smoothstep(0.3, 1, 1 - createHexField(v, hexFieldScale)); // TODO: FOR SPOOL
const gridShadow = 1 - (smoothstep(1 - ringWidth * 0.65, 1 - ringWidth - gridShadowBlur, d) -
smoothstep(buttonSize + gridShadowBlur, buttonSize * 0.85, d));
grid -= (gridShadow * gridShadowStrength);
const metalPlate = createMetalPlate(a, d) * ringBrightness;
const ringMask = smoothstep(1 - ringWidth, 1 - ringWidth + sw, d) + smoothstep(buttonSize, buttonSize - sw, d);
const spriteCol = mixCol(mulCol(gridColor, grid), mulCol(metalColor, metalPlate), ringMask);
const shadow = smoothstep(1, 1 - shadowBlur, lenV(subV(centerV, {
x: shadowDistance,
y: shadowDistance
})) * 2 / shadowScale) * shadowStrength;
const shadowCol = newCol(0, 0, 0, shadow);
return mixCol(spriteCol, shadowCol, smoothstep(1 - sw, 1, d));
});
return image;
};
const createIsolatorSprite = (size: number): Canvas => {
const sw = 4 / size;
const hexFieldScale = size / 8;
const hexFieldBrightness = 0.7;
const ringBrightness = 0.4;
const gridShadowBlur = 0.2;
const gridShadowStrength = 0.6;
const ringWidth = 0.15;
const buttonSize = 0.3;
const gridColor = newCol(0.815, 0.2705, .2, 1); // isolate red
const metalColor = newCol(1, 1, 1, 1);
const shadowBlur = 0.2;
const shadowDistance = 0.04;
const shadowScale = 1.1;
const shadowStrength = 0.5;
const image = generateImage(Math.round(size * 1.1), Math.round(size * 1.1), v => {
v = mulVS(v, 1.1); // scale to make room for shadow
const centerV = subV(v, halfV);
const a = Math.atan2(centerV.y, centerV.x); // polar x
const d = lenV(centerV) * 2; // polar y
let grid = hexFieldBrightness * smoothstep(0.02, 0.41, 1 - createHexField(v, hexFieldScale)); // TODO FOR ISOLATOR
const gridShadow = 1 - (smoothstep(1 - ringWidth * 0.65, 1 - ringWidth - gridShadowBlur, d) -
smoothstep(buttonSize + gridShadowBlur, buttonSize * 0.85, d));
grid -= (gridShadow * gridShadowStrength);
const metalPlate = createMetalPlate(a, d) * ringBrightness;
const ringMask = smoothstep(1 - ringWidth, 1 - ringWidth + sw, d) + smoothstep(buttonSize, buttonSize - sw, d);
const spriteCol = mixCol(mulCol(gridColor, grid), mulCol(metalColor, metalPlate), ringMask);
const shadow = smoothstep(1, 1 - shadowBlur, lenV(subV(centerV, {
x: shadowDistance,
y: shadowDistance
})) * 2 / shadowScale) * shadowStrength;
const shadowCol = newCol(0, 0, 0, shadow);
return mixCol(spriteCol, shadowCol, smoothstep(1 - sw, 1, d));
});
return image;
};
const createGear = (px:number, py:number, outerSize: number, innerSize:number, step: number): number => {
const s = Math.min(fract(px), fract(1 - px)) * 2;
const spikes = smoothstep(0, step*8, s - py);
const center = smoothstep(innerSize, innerSize+step, 1 - py);
const cut = smoothstep(outerSize+step,outerSize , 1 - py);
return clamp(spikes +center - cut, 0,1);
};
const createBlockSprite = (size: number): Canvas => {
const image = generateImage(size, size, v => {
const cv = subV(v, halfV);
const d = lenV(cv) * 2;
const atan = Math.atan2(cv.y, cv.x);
const px = atan / (Math.PI * 2) + 0.5; // polar twistedMx
const twistedPx = atan / (Math.PI * 2) + 0.5 + d * 0.3; // polar twistedMx
const twistedMx = twistedPx * Math.round(8+size/50);
const mx = px * Math.round(5+size/200);
const m = Math.min(fract(twistedMx), fract(1 - twistedMx));
let bladeAlpha = smoothstep(0.0, 0.08, m * 0.5 - d + 0.7);
let shadow = 1-smoothstep(0.9, 0.2, d);
let blade = 1.4 * d - bladeAlpha * 0.5;
let gear = createGear(mx, d, 0.45, 0.52, 0.02);
let gearCol = 0.5+0.5*createMetalPlate(atan*1, d);
blade = mix(mix(shadow, blade, bladeAlpha), gear*0.3*gearCol, gear);
return newCol(blade, blade, blade, bladeAlpha+(1-shadow));
});
return image;
};
const createInnerShadow = (v: Vec2): Color => {
const d = lenV(v) * 2;
const dm = lenV(subV(v, mulVS(v11, 0.05))) * 2;
const val = smoothstep(1, 0.5, dm * 0.8) * 0.2;
const a = smoothstep(1, 0.85, d);
return newCol(val, val, val, a);
};
const createLedGlass = (v: Vec2): Color => {
const d = (lenV(v) * 2) * 1.2;
const val = smoothstep(1, 0.0, d) * 0.25;
const a = smoothstep(0.99, 0.9, d);
return newCol(val, val, val, a);
};
const createLedGlassReflection = (v: Vec2): Color => {
const d = (lenV(v) * 2) * 1.5;
const dm = lenV(subV(v, mulVS(v11, 0.14))) * 1.01;
const val = smoothstep(1, 0.6, d) *
smoothstep(0.2, 0.5, dm);
return newCol(val, val, val, val);
};
const createLedSprite = (): Canvas => generateImage(21, 21, v => {
const cv = subV(v, halfV);
const innerShadow = createInnerShadow(cv);
const ledGlass = createLedGlass(cv);
const ledGlassReflection = createLedGlassReflection(cv);
return addCol(addCol(innerShadow, ledGlass), ledGlassReflection);
});
const white = newCol(1, 1, 1, 1);
const createGlow = (color:Color): Canvas => generateImage(80, 80, v => {
const cv = subV(v, halfV);
const d = 1 - lenV(cv) * 2;
const result = mixCol(color, white, smoothstep(0.6, 0.89, d));
const a = smoothstep(0.0, 1, d);
return newCol(result.r, result.g, result.b, a*a*a);
});
const createMetal = (a: number, d: number): number => {
return 0.9 + 0.1 * Math.sin(a * 6) * 0.9 + 0.1 * Math.sin(a * 4)
- (noise({x: (a + 4 + d * 5) * 2, y: d * 80}) * 0.1);
};
const createRingGlow = (color:Color): Canvas => generateImage(62, 62, v => {
const cv = subV(v, halfV);
const d = 1 - lenV(cv) * 2;
const result = mixCol(color, white, smoothstep(0.45, 0.5, d)*smoothstep(0.55, 0.5, d));
const a = smoothstep(0.0, 0.5, d)*smoothstep(1, 0.5, d);
return newCol(result.r, result.g, result.b, a*a*a);
});
const createConnectorButtons = (lightColor:Color, size:number): Canvas => {
const shadowBlur = 0.2;
const shadowDistance = 0.04;
const shadowScale = 1.1;
const shadowStrength = 0.2;
const image = generateImage(size, size, v => {
v = mulVS(v, 1.1); // scale to make room for shadow
const cv = subV(v, halfV);
const atan = Math.atan2(cv.y, cv.x);
const py = lenV(cv) * 2;
// back
const backAlpha = smoothstep(1, .96, py);
let shading = smoothstep(0.9, 0.80, py)*0.3+0.3;
shading -= smoothstep(0.7, 0.60, py) * smoothstep(0.2, 0.30, py) * 0.4;
const backVal = createMetal(atan+(shading*3), py) * shading;
const backCol = newCol(backVal, backVal, backVal, backAlpha);
// light
const lightAlpha = smoothstep(0.35, 0.45, py)*smoothstep(0.55, 0.45, py);
const col = mixCol(backCol, lightColor, lightAlpha);
const shadow = smoothstep(1, 1 - shadowBlur, lenV(subV(cv, {
x: shadowDistance,
y: shadowDistance
})) * 2 / shadowScale) * shadowStrength;
const shadowCol = newCol(0, 0, 0, shadow);
return mixCol(col, shadowCol, smoothstep(0.8, 1, py));
});
return image;
};
const createGameBackground = (): Canvas => {
const [canvas, context] = createCanvas(1920, 1280);
const image = generateImage(64, 64, v => {
const m = mulVS(v, 4);
const col = 1-smoothstep(0.7, 1, createHexField(m, 1))*0.7;
return newCol(col * 0.117, col * 0.149, col * 0.188, 1);
});
const highlight = generateImage(128*2, 72*2, v => {
const w = 0.01;
const c = smoothstep(0, w*0.6, v.x)*smoothstep(1, 1-w*0.6, v.x)*
smoothstep(0, w, v.y)*smoothstep(1, 1-w, v.y);
return newCol(1, 1, 1, (1-c)*0.04);
});
for (let y = 0; y < 12; y++) {
for (let x = 0; x < 24; x++) {
context.drawImage(image, x * 54, y * 63);
}
}
context.drawImage(highlight, 0, 0, 1280, 720);
return canvas;
}; | the_stack |
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useIdAllocator } from '@leafygreen-ui/hooks';
import { cx, css } from '@leafygreen-ui/emotion';
import { createDataProp, isComponentType } from '@leafygreen-ui/lib';
import { uiColors } from '@leafygreen-ui/palette';
import { Overline } from '@leafygreen-ui/typography';
import { useUsingKeyboardContext } from '@leafygreen-ui/leafygreen-provider';
import useDynamicRefs from './useDynamicRefs';
import { Size, Mode } from './types';
import { once } from 'lodash';
import { useEffectOnceOnMount } from './useEffectOnceOnMount';
const selectionIndicatorDataAttr = createDataProp('selection-indicator');
const hoverIndicatorDataAttr = createDataProp('hover-indicator');
/**
* Styles
*/
const wrapperStyle = css`
display: flex;
gap: 8px;
align-items: center;
z-index: 0;
`;
const labelStyle: {
[key in Mode]: string;
} = {
light: css`
color: ${uiColors.gray.dark1};
`,
dark: css`
color: ${uiColors.gray.light1};
`,
};
// The border color is slightly different from the base gray for accessibility reasons
const selectionBorderColor = '#869499';
const frameStyleSize: {
[key in Size]: string;
} = {
small: css`
--segment-gap: 1px;
--frame-padding: 0px;
--frame-border-radius: 4px;
--indicator-height: 100%;
`,
default: css`
--segment-gap: 5px;
--frame-padding: 3px;
--frame-border-radius: 6px;
--indicator-height: calc(100% - 2 * var(--frame-padding));
`,
large: css`
--segment-gap: 5px;
--frame-padding: 3px;
--frame-border-radius: 6px;
--indicator-height: calc(100% - 2 * var(--frame-padding));
`,
};
const frameStyleMode: {
[key in Mode]: string;
} = {
light: css`
--background-color: ${uiColors.gray.light3};
--border-color: transparent;
--border-width: 0px;
--inner-shadow: 0px 1px 2px rgba(0, 0, 0, 0.3) inset;
--outer-shadow: 0px 1px 1px #e7eeec;
--hover-background-color: ${uiColors.white};
--indicator-background-color: ${uiColors.gray.light2};
--indicator-border-color: ${selectionBorderColor};
`,
dark: css`
--background-color: ${uiColors.gray.dark3};
--border-color: ${uiColors.gray.dark1};
--border-width: 1px;
--inner-shadow: unset;
--outer-shadow: unset;
--hover-background-color: ${uiColors.gray.dark2};
--indicator-background-color: ${uiColors.gray.dark1};
--indicator-border-color: ${uiColors.gray.base};
`,
};
const frameStyle = ({
mode = 'light',
size = 'default',
}: {
mode: Mode;
size: Size;
}) =>
cx(
frameStyleSize[size],
frameStyleMode[mode],
css`
position: relative;
display: grid;
grid-auto-flow: column;
grid-auto-columns: 1fr;
gap: var(--segment-gap);
align-items: center;
padding: var(--frame-padding);
border: var(--border-width) solid var(--border-color);
border-radius: var(--frame-border-radius);
background-color: var(--background-color);
&:focus {
outline: none;
}
// Frame shadow
&:after {
content: '';
position: absolute;
width: 100%;
height: 100%;
border-radius: inherit;
box-shadow: var(--inner-shadow), var(--outer-shadow);
z-index: 1;
pointer-events: none;
}
`,
);
const selectionIndicatorStyle = css`
position: absolute;
grid-column: 1/2; // position the selector in the grid until it gets positioned
width: 100%;
height: var(--indicator-height);
z-index: 2;
box-shadow: 0px 1px 2px rgba(6, 22, 33, 0.3);
border-radius: 4px;
border-width: 1px;
border-style: solid;
background-color: var(--indicator-background-color);
border-color: var(--indicator-border-color);
transition: transform 150ms ease-in-out;
`;
const getDynamicSelectionStyle = (width: number, left: number) => {
return css`
grid-column: unset;
width: ${width}px;
transform: translateX(${left}px);
`;
};
const hoverIndicatorStyle = css`
position: absolute;
height: var(--indicator-height);
width: 100%;
grid-column: unset;
border-radius: 4px;
background-color: var(--hover-background-color);
z-index: 0;
opacity: 0;
`;
const getDynamicHoverStyle = (index: number | null) => {
if (index != null) {
return css`
opacity: 1;
grid-column: ${index + 1} / ${index + 2};
`;
}
};
/**
* Types
*/
interface SCContext {
size: Size;
mode: Mode;
name: string;
followFocus: boolean;
}
export const SegmentedControlContext = React.createContext<SCContext>({
size: 'default',
mode: 'light',
name: '',
followFocus: true,
});
export interface SegmentedControlProps
extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> {
/**
* Children must be SegmentedControlOptions
*/
children: React.ReactNode;
/**
* Defines the size of the segmented control. Can be either `small`, `default`, or `large`
*/
size?: Size;
/**
* Toggles dark mode
*/
darkMode?: boolean;
/**
* Defines the default, or initial value of the component. Ignored if `value` is also provided.
*/
defaultValue?: string;
/**
* Controls the value of the component.
* If provided, you must update the value in the `onChange` method,
* or other user actions (such as routing)
*/
value?: string;
/**
* A text label to the left of the segmented control. Sets the `name` prop if none is provided.
*/
label?: string;
/**
* Identifies the segmented control group to screen readers. Auto-generated if no `name` or `label` is provided.
*
* It's recommended for accessability to set this to a meaningful value.
*/
name?: string;
/**
* Defines whether the selection should automatically follow focus.
* If set to true, the arrow keys can be used to switch selection,
* otherwise a keyboard user will need to press enter to make a selection.
*
* Default: `true`
*/
followFocus?: boolean;
/**
* Identifies the element(s) whose contents/presence is controlled by the segmented control.
*
* Required as a prop on the control, or on each individual option.
*/
'aria-controls'?: string;
/**
* Callback that gets called when a user makes a new selection.
*/
onChange?: (value: string) => void;
/**
* Styling prop
*/
className?: string;
}
/**
* Component
*/
const SegmentedControl = React.forwardRef<
HTMLDivElement,
SegmentedControlProps
>(function SegmentedControl(
{
children,
name: nameProp,
size = 'default',
darkMode = false,
defaultValue,
value: controlledValue,
onChange,
className,
label,
followFocus = true,
'aria-controls': ariaControls,
...rest
}: SegmentedControlProps,
forwardedRef,
) {
// TODO log warning if defaultValue is set but does not match any child value
const { usingKeyboard } = useUsingKeyboardContext();
const [getRef, setRef] = useDynamicRefs<HTMLDivElement>();
const mode = darkMode ? 'dark' : 'light';
const name = useIdAllocator({
prefix: 'segmented-control',
id: nameProp ?? label,
});
// If a value is given, then it's controlled
const isControlled = useMemo(() => controlledValue != null, [
controlledValue,
]);
// Keep track of the value internally
const [internalValue, setInternalValue] = useState<string | undefined>(
defaultValue ?? controlledValue,
);
const [focusedOptionValue, setFocusedOptionValue] = useState<
string | undefined
>(defaultValue ?? controlledValue);
// If no default or controlled value is given, set it to the first option
useEffectOnceOnMount(() => {
const firstChild = React.Children.toArray(children)[0];
if (
!internalValue &&
isComponentType(firstChild, 'SegmentedControlOption')
) {
setInternalValue(firstChild.props.value);
setFocusedOptionValue(firstChild.props.value);
}
});
// Handle value updates
const updateValue = useCallback(
(value: string) => {
if (internalValue !== value) {
setInternalValue(value);
onChange?.(value);
}
},
[internalValue, onChange],
);
/**
* Main render function.
* Add internal props to children passed in
*/
const renderedChildren: React.ReactNode = useMemo(
() =>
React.Children.map(children, (child, index) => {
if (!isComponentType(child, 'SegmentedControlOption')) {
errorOnce(
`Error in Segmented Control: ${child} is not a SegmentedControlOption`,
);
return child;
}
// Ensure `aria-controls` is set
if (!ariaControls && !child.props['aria-controls']) {
warnOnce(
`The property \`aria-controls\` is required on each Segmented Control option, or on the Segmented Control parent.`,
);
}
const _id = child.props.id ?? `${name}-${index}`;
const _checked: boolean = isControlled
? child.props.value === controlledValue || !!child.props.checked
: child.props.value === internalValue;
const _focused: boolean = child.props.value === focusedOptionValue;
const _onHover = (hovered: boolean) => {
if (hovered) setHoveredIndex(index);
else setHoveredIndex(null);
};
return React.cloneElement(child, {
_id,
_checked,
_focused,
_index: index,
'aria-controls': child.props['aria-controls'] ?? ariaControls,
_onClick: updateValue,
_onHover,
ref: setRef(`${name}-${index}`),
});
}),
[
children,
isControlled,
controlledValue,
internalValue,
focusedOptionValue,
name,
ariaControls,
updateValue,
setRef,
],
);
// Maintain a list of child `id`s to link the `tablist` to individual `tab` elements
// See https://www.w3.org/TR/wai-aria-1.1/#tab
const childrenIdList: string = useMemo(() => {
if (renderedChildren) {
return React.Children.map(
renderedChildren as React.ReactElement,
child => child?.props?._id,
).join(' ');
}
return '';
}, [renderedChildren]);
// Keep track of which element is hovered
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
// Keep track of the index of the selected value
const selectedIndex = useMemo(
() =>
(React.Children.toArray(
renderedChildren,
) as Array<React.ReactElement>).findIndex(child =>
isControlled
? child.props.value === controlledValue
: child.props.value === internalValue,
),
[controlledValue, isControlled, renderedChildren, internalValue],
);
/**
* Focus Management
*/
// Keep track of the index of the focused value
const focusedIndex = useMemo(
() =>
(React.Children.toArray(
renderedChildren,
) as Array<React.ReactElement>).findIndex(
child => child.props.value === focusedOptionValue,
),
[renderedChildren, focusedOptionValue],
);
const updateFocusedIndex = (newIndex: number): void => {
const children = (React.Children.toArray(
renderedChildren,
) as Array<React.ReactElement>).filter(child => !child.props.disabled);
const length = children.length;
newIndex =
newIndex >= length
? newIndex % length
: newIndex < 0
? length + newIndex
: newIndex;
const { value } = children[newIndex].props;
setFocusedOptionValue(value);
};
// When the value changes via click, we update the internal focus tracker so the correct element gets focused on tab press
useEffect(() => {
if (!usingKeyboard) {
setFocusedOptionValue(internalValue);
}
}, [internalValue, usingKeyboard]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
// Note: Arrow keys don't fire a keyPress event — need to use keyDown
e.stopPropagation();
// We only handle right and left arrow keys
// Up & down should be left to control scroll
switch (e.key) {
case 'ArrowRight':
updateFocusedIndex(focusedIndex + 1);
break;
case 'ArrowLeft':
updateFocusedIndex(focusedIndex - 1);
break;
default:
break;
}
};
/**
* Dynamic Styles
*/
// Dynamically set the size & position of the selection indicator
const [selectionStyleDynamic, setSelectionStyle] = useState<string>('');
useEffect(() => {
const selectedRef = getRef(`${name}-${selectedIndex}`);
if (selectedRef && selectedRef.current) {
// The ref refers to the button element
const selectedElement = selectedRef.current;
if (selectedElement) {
const { offsetWidth: width, offsetLeft: left } = selectedElement;
setSelectionStyle(getDynamicSelectionStyle(width, left));
}
}
}, [getRef, name, selectedIndex, renderedChildren]);
// Dynamic hover styles
const hoverStyleDynamic = useMemo(() => {
return getDynamicHoverStyle(hoveredIndex);
}, [hoveredIndex]);
/**
* Return
*/
return (
<SegmentedControlContext.Provider value={{ size, mode, name, followFocus }}>
<div className={cx(wrapperStyle, className)} {...rest}>
{label && <Overline className={labelStyle[mode]}>{label}</Overline>}
<div
role="tablist"
aria-label={name}
aria-owns={childrenIdList}
className={cx(frameStyle({ mode, size }))}
ref={forwardedRef}
onKeyDownCapture={handleKeyDown}
>
{renderedChildren}
<div
{...selectionIndicatorDataAttr.prop}
className={cx(selectionIndicatorStyle, selectionStyleDynamic)}
/>
<div
{...hoverIndicatorDataAttr.prop}
className={cx(hoverIndicatorStyle, hoverStyleDynamic)}
/>
</div>
</div>
</SegmentedControlContext.Provider>
);
});
SegmentedControl.displayName = 'SegmentedControl';
export default SegmentedControl;
const errorOnce = once(console.error);
const warnOnce = once(console.warn); | the_stack |
/* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable no-irregular-whitespace */
import {
OAuth2Client,
JWT,
Compute,
UserRefreshClient,
BaseExternalAccountClient,
GaxiosPromise,
GoogleConfigurable,
createAPIRequest,
MethodOptions,
StreamMethodOptions,
GlobalOptions,
GoogleAuth,
BodyResponseCallback,
APIRequestContext,
} from 'googleapis-common';
import {Readable} from 'stream';
export namespace versionhistory_v1 {
export interface Options extends GlobalOptions {
version: 'v1';
}
interface StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?:
| string
| OAuth2Client
| JWT
| Compute
| UserRefreshClient
| BaseExternalAccountClient
| GoogleAuth;
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: string;
/**
* JSONP
*/
callback?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
*/
quotaUser?: string;
/**
* Legacy upload protocol for media (e.g. "media", "multipart").
*/
uploadType?: string;
/**
* Upload protocol for media (e.g. "raw", "multipart").
*/
upload_protocol?: string;
}
/**
* Version History API
*
* Version History API - Prod
*
* @example
* ```js
* const {google} = require('googleapis');
* const versionhistory = google.versionhistory('v1');
* ```
*/
export class Versionhistory {
context: APIRequestContext;
platforms: Resource$Platforms;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.platforms = new Resource$Platforms(this.context);
}
}
/**
* Each Channel is owned by a Platform and owns a collection of versions. Possible Channels are listed in the Channel enum below. Not all Channels are available for every Platform (e.g. CANARY does not exist for LINUX).
*/
export interface Schema$Channel {
/**
* Type of channel.
*/
channelType?: string | null;
/**
* Channel name. Format is "{product\}/platforms/{platform\}/channels/{channel\}"
*/
name?: string | null;
}
/**
* Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp end (exclusive). The start must be less than or equal to the end. When the start equals the end, the interval is empty (matches no time). When both start and end are unspecified, the interval matches any time.
*/
export interface Schema$Interval {
/**
* Optional. Exclusive end of the interval. If specified, a Timestamp matching this interval will have to be before the end.
*/
endTime?: string | null;
/**
* Optional. Inclusive start of the interval. If specified, a Timestamp matching this interval will have to be the same or after the start.
*/
startTime?: string | null;
}
/**
* Response message for ListChannels.
*/
export interface Schema$ListChannelsResponse {
/**
* The list of channels.
*/
channels?: Schema$Channel[];
/**
* A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages.
*/
nextPageToken?: string | null;
}
/**
* Response message for ListPlatforms.
*/
export interface Schema$ListPlatformsResponse {
/**
* A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages.
*/
nextPageToken?: string | null;
/**
* The list of platforms.
*/
platforms?: Schema$Platform[];
}
/**
* Response message for ListReleases.
*/
export interface Schema$ListReleasesResponse {
/**
* A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages.
*/
nextPageToken?: string | null;
/**
* The list of releases.
*/
releases?: Schema$Release[];
}
/**
* Response message for ListVersions.
*/
export interface Schema$ListVersionsResponse {
/**
* A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages.
*/
nextPageToken?: string | null;
/**
* The list of versions.
*/
versions?: Schema$Version[];
}
/**
* Each Platform is owned by a Product and owns a collection of channels. Available platforms are listed in Platform enum below. Not all Channels are available for every Platform (e.g. CANARY does not exist for LINUX).
*/
export interface Schema$Platform {
/**
* Platform name. Format is "{product\}/platforms/{platform\}"
*/
name?: string | null;
/**
* Type of platform.
*/
platformType?: string | null;
}
/**
* A Release is owned by a Version. A Release contains information about the release(s) of its parent version. This includes when the release began and ended, as well as what percentage it was released at. If the version is released again, or if the serving percentage changes, it will create another release under the version.
*/
export interface Schema$Release {
/**
* Rollout fraction. This fraction indicates the fraction of people that should receive this version in this release. If the fraction is not specified in ReleaseManager, the API will assume fraction is 1.
*/
fraction?: number | null;
/**
* Release name. Format is "{product\}/platforms/{platform\}/channels/{channel\}/versions/{version\}/releases/{release\}"
*/
name?: string | null;
/**
* Timestamp interval of when the release was live. If end_time is unspecified, the release is currently live.
*/
serving?: Schema$Interval;
/**
* String containing just the version number. e.g. "84.0.4147.38"
*/
version?: string | null;
}
/**
* Each Version is owned by a Channel. A Version only displays the Version number (e.g. 84.0.4147.38). A Version owns a collection of releases.
*/
export interface Schema$Version {
/**
* Version name. Format is "{product\}/platforms/{platform\}/channels/{channel\}/versions/{version\}" e.g. "chrome/platforms/win/channels/beta/versions/84.0.4147.38"
*/
name?: string | null;
/**
* String containing just the version number. e.g. "84.0.4147.38"
*/
version?: string | null;
}
export class Resource$Platforms {
context: APIRequestContext;
channels: Resource$Platforms$Channels;
constructor(context: APIRequestContext) {
this.context = context;
this.channels = new Resource$Platforms$Channels(this.context);
}
/**
* Returns list of platforms that are available for a given product. The resource "product" has no resource name in its name.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/versionhistory.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const versionhistory = google.versionhistory('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await versionhistory.platforms.list({
* // Optional. Optional limit on the number of channels to include in the response. If unspecified, the server will pick an appropriate default.
* pageSize: 'placeholder-value',
* // Optional. A page token, received from a previous `ListChannels` call. Provide this to retrieve the subsequent page.
* pageToken: 'placeholder-value',
* // Required. The product, which owns this collection of platforms. Format: {product\}
* parent: '[^/]+',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "nextPageToken": "my_nextPageToken",
* // "platforms": []
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Platforms$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Platforms$List,
options?: MethodOptions
): GaxiosPromise<Schema$ListPlatformsResponse>;
list(
params: Params$Resource$Platforms$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Platforms$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$ListPlatformsResponse>,
callback: BodyResponseCallback<Schema$ListPlatformsResponse>
): void;
list(
params: Params$Resource$Platforms$List,
callback: BodyResponseCallback<Schema$ListPlatformsResponse>
): void;
list(callback: BodyResponseCallback<Schema$ListPlatformsResponse>): void;
list(
paramsOrCallback?:
| Params$Resource$Platforms$List
| BodyResponseCallback<Schema$ListPlatformsResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ListPlatformsResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ListPlatformsResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ListPlatformsResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback || {}) as Params$Resource$Platforms$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Platforms$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://versionhistory.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+parent}/platforms').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ListPlatformsResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ListPlatformsResponse>(parameters);
}
}
}
export interface Params$Resource$Platforms$List extends StandardParameters {
/**
* Optional. Optional limit on the number of channels to include in the response. If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* Optional. A page token, received from a previous `ListChannels` call. Provide this to retrieve the subsequent page.
*/
pageToken?: string;
/**
* Required. The product, which owns this collection of platforms. Format: {product\}
*/
parent?: string;
}
export class Resource$Platforms$Channels {
context: APIRequestContext;
versions: Resource$Platforms$Channels$Versions;
constructor(context: APIRequestContext) {
this.context = context;
this.versions = new Resource$Platforms$Channels$Versions(this.context);
}
/**
* Returns list of channels that are available for a given platform.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/versionhistory.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const versionhistory = google.versionhistory('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await versionhistory.platforms.channels.list({
* // Optional. Optional limit on the number of channels to include in the response. If unspecified, the server will pick an appropriate default.
* pageSize: 'placeholder-value',
* // Optional. A page token, received from a previous `ListChannels` call. Provide this to retrieve the subsequent page.
* pageToken: 'placeholder-value',
* // Required. The platform, which owns this collection of channels. Format: {product\}/platforms/{platform\}
* parent: '[^/]+/platforms/my-platform',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "channels": [],
* // "nextPageToken": "my_nextPageToken"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Platforms$Channels$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Platforms$Channels$List,
options?: MethodOptions
): GaxiosPromise<Schema$ListChannelsResponse>;
list(
params: Params$Resource$Platforms$Channels$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Platforms$Channels$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$ListChannelsResponse>,
callback: BodyResponseCallback<Schema$ListChannelsResponse>
): void;
list(
params: Params$Resource$Platforms$Channels$List,
callback: BodyResponseCallback<Schema$ListChannelsResponse>
): void;
list(callback: BodyResponseCallback<Schema$ListChannelsResponse>): void;
list(
paramsOrCallback?:
| Params$Resource$Platforms$Channels$List
| BodyResponseCallback<Schema$ListChannelsResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ListChannelsResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ListChannelsResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ListChannelsResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Platforms$Channels$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Platforms$Channels$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://versionhistory.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+parent}/channels').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ListChannelsResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ListChannelsResponse>(parameters);
}
}
}
export interface Params$Resource$Platforms$Channels$List
extends StandardParameters {
/**
* Optional. Optional limit on the number of channels to include in the response. If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* Optional. A page token, received from a previous `ListChannels` call. Provide this to retrieve the subsequent page.
*/
pageToken?: string;
/**
* Required. The platform, which owns this collection of channels. Format: {product\}/platforms/{platform\}
*/
parent?: string;
}
export class Resource$Platforms$Channels$Versions {
context: APIRequestContext;
releases: Resource$Platforms$Channels$Versions$Releases;
constructor(context: APIRequestContext) {
this.context = context;
this.releases = new Resource$Platforms$Channels$Versions$Releases(
this.context
);
}
/**
* Returns list of version for the given platform/channel.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/versionhistory.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const versionhistory = google.versionhistory('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await versionhistory.platforms.channels.versions.list({
* // Optional. Filter string. Format is a comma separated list of All comma separated filter clauses are conjoined with a logical "and". Valid field_names are "version", "name", "platform", and "channel". Valid operators are "<", "<=", "=", "\>=", and "\>". Channel comparison is done by distance from stable. Ex) stable < beta, beta < dev, canary < canary_asan. Version comparison is done numerically. If version is not entirely written, the version will be appended with 0 in missing fields. Ex) version \> 80 becoms version \> 80.0.0.0 Name and platform are filtered by string comparison. Ex) "...?filter=channel<=beta, version \>= 80 Ex) "...?filter=version \> 80, version < 81
* filter: 'placeholder-value',
* // Optional. Ordering string. Valid order_by strings are "version", "name", "platform", and "channel". Optionally, you can append " desc" or " asc" to specify the sorting order. Multiple order_by strings can be used in a comma separated list. Ordering by channel will sort by distance from the stable channel (not alphabetically). A list of channels sorted in this order is: stable, beta, dev, canary, and canary_asan. Sorting by name may cause unexpected behaviour as it is a naive string sort. For example, 1.0.0.8 will be before 1.0.0.10 in descending order. If order_by is not specified the response will be sorted by version in descending order. Ex) "...?order_by=version asc" Ex) "...?order_by=platform desc, channel, version"
* orderBy: 'placeholder-value',
* // Optional. Optional limit on the number of versions to include in the response. If unspecified, the server will pick an appropriate default.
* pageSize: 'placeholder-value',
* // Optional. A page token, received from a previous `ListVersions` call. Provide this to retrieve the subsequent page.
* pageToken: 'placeholder-value',
* // Required. The channel, which owns this collection of versions. Format: {product\}/platforms/{platform\}/channels/{channel\}
* parent: '[^/]+/platforms/my-platform/channels/my-channel',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "nextPageToken": "my_nextPageToken",
* // "versions": []
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Platforms$Channels$Versions$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Platforms$Channels$Versions$List,
options?: MethodOptions
): GaxiosPromise<Schema$ListVersionsResponse>;
list(
params: Params$Resource$Platforms$Channels$Versions$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Platforms$Channels$Versions$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$ListVersionsResponse>,
callback: BodyResponseCallback<Schema$ListVersionsResponse>
): void;
list(
params: Params$Resource$Platforms$Channels$Versions$List,
callback: BodyResponseCallback<Schema$ListVersionsResponse>
): void;
list(callback: BodyResponseCallback<Schema$ListVersionsResponse>): void;
list(
paramsOrCallback?:
| Params$Resource$Platforms$Channels$Versions$List
| BodyResponseCallback<Schema$ListVersionsResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ListVersionsResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ListVersionsResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ListVersionsResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Platforms$Channels$Versions$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Platforms$Channels$Versions$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://versionhistory.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+parent}/versions').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ListVersionsResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ListVersionsResponse>(parameters);
}
}
}
export interface Params$Resource$Platforms$Channels$Versions$List
extends StandardParameters {
/**
* Optional. Filter string. Format is a comma separated list of All comma separated filter clauses are conjoined with a logical "and". Valid field_names are "version", "name", "platform", and "channel". Valid operators are "<", "<=", "=", "\>=", and "\>". Channel comparison is done by distance from stable. Ex) stable < beta, beta < dev, canary < canary_asan. Version comparison is done numerically. If version is not entirely written, the version will be appended with 0 in missing fields. Ex) version \> 80 becoms version \> 80.0.0.0 Name and platform are filtered by string comparison. Ex) "...?filter=channel<=beta, version \>= 80 Ex) "...?filter=version \> 80, version < 81
*/
filter?: string;
/**
* Optional. Ordering string. Valid order_by strings are "version", "name", "platform", and "channel". Optionally, you can append " desc" or " asc" to specify the sorting order. Multiple order_by strings can be used in a comma separated list. Ordering by channel will sort by distance from the stable channel (not alphabetically). A list of channels sorted in this order is: stable, beta, dev, canary, and canary_asan. Sorting by name may cause unexpected behaviour as it is a naive string sort. For example, 1.0.0.8 will be before 1.0.0.10 in descending order. If order_by is not specified the response will be sorted by version in descending order. Ex) "...?order_by=version asc" Ex) "...?order_by=platform desc, channel, version"
*/
orderBy?: string;
/**
* Optional. Optional limit on the number of versions to include in the response. If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* Optional. A page token, received from a previous `ListVersions` call. Provide this to retrieve the subsequent page.
*/
pageToken?: string;
/**
* Required. The channel, which owns this collection of versions. Format: {product\}/platforms/{platform\}/channels/{channel\}
*/
parent?: string;
}
export class Resource$Platforms$Channels$Versions$Releases {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Returns list of releases of the given version.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/versionhistory.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const versionhistory = google.versionhistory('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: [],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await versionhistory.platforms.channels.versions.releases.list({
* // Optional. Filter string. Format is a comma separated list of All comma separated filter clauses are conjoined with a logical "and". Valid field_names are "version", "name", "platform", "channel", "fraction" "starttime", and "endtime". Valid operators are "<", "<=", "=", "\>=", and "\>". Channel comparison is done by distance from stable. must be a valid channel when filtering by channel. Ex) stable < beta, beta < dev, canary < canary_asan. Version comparison is done numerically. Ex) 1.0.0.8 < 1.0.0.10. If version is not entirely written, the version will be appended with 0 for the missing fields. Ex) version \> 80 becoms version \> 80.0.0.0 When filtering by starttime or endtime, string must be in RFC 3339 date string format. Name and platform are filtered by string comparison. Ex) "...?filter=channel<=beta, version \>= 80 Ex) "...?filter=version \> 80, version < 81 Ex) "...?filter=starttime\>2020-01-01T00:00:00Z
* filter: 'placeholder-value',
* // Optional. Ordering string. Valid order_by strings are "version", "name", "starttime", "endtime", "platform", "channel", and "fraction". Optionally, you can append "desc" or "asc" to specify the sorting order. Multiple order_by strings can be used in a comma separated list. Ordering by channel will sort by distance from the stable channel (not alphabetically). A list of channels sorted in this order is: stable, beta, dev, canary, and canary_asan. Sorting by name may cause unexpected behaviour as it is a naive string sort. For example, 1.0.0.8 will be before 1.0.0.10 in descending order. If order_by is not specified the response will be sorted by starttime in descending order. Ex) "...?order_by=starttime asc" Ex) "...?order_by=platform desc, channel, startime desc"
* orderBy: 'placeholder-value',
* // Optional. Optional limit on the number of releases to include in the response. If unspecified, the server will pick an appropriate default.
* pageSize: 'placeholder-value',
* // Optional. A page token, received from a previous `ListReleases` call. Provide this to retrieve the subsequent page.
* pageToken: 'placeholder-value',
* // Required. The version, which owns this collection of releases. Format: {product\}/platforms/{platform\}/channels/{channel\}/versions/{version\}
* parent:
* '[^/]+/platforms/my-platform/channels/my-channel/versions/my-version',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "nextPageToken": "my_nextPageToken",
* // "releases": []
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Platforms$Channels$Versions$Releases$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Platforms$Channels$Versions$Releases$List,
options?: MethodOptions
): GaxiosPromise<Schema$ListReleasesResponse>;
list(
params: Params$Resource$Platforms$Channels$Versions$Releases$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Platforms$Channels$Versions$Releases$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$ListReleasesResponse>,
callback: BodyResponseCallback<Schema$ListReleasesResponse>
): void;
list(
params: Params$Resource$Platforms$Channels$Versions$Releases$List,
callback: BodyResponseCallback<Schema$ListReleasesResponse>
): void;
list(callback: BodyResponseCallback<Schema$ListReleasesResponse>): void;
list(
paramsOrCallback?:
| Params$Resource$Platforms$Channels$Versions$Releases$List
| BodyResponseCallback<Schema$ListReleasesResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ListReleasesResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ListReleasesResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ListReleasesResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Platforms$Channels$Versions$Releases$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params =
{} as Params$Resource$Platforms$Channels$Versions$Releases$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://versionhistory.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+parent}/releases').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ListReleasesResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ListReleasesResponse>(parameters);
}
}
}
export interface Params$Resource$Platforms$Channels$Versions$Releases$List
extends StandardParameters {
/**
* Optional. Filter string. Format is a comma separated list of All comma separated filter clauses are conjoined with a logical "and". Valid field_names are "version", "name", "platform", "channel", "fraction" "starttime", and "endtime". Valid operators are "<", "<=", "=", "\>=", and "\>". Channel comparison is done by distance from stable. must be a valid channel when filtering by channel. Ex) stable < beta, beta < dev, canary < canary_asan. Version comparison is done numerically. Ex) 1.0.0.8 < 1.0.0.10. If version is not entirely written, the version will be appended with 0 for the missing fields. Ex) version \> 80 becoms version \> 80.0.0.0 When filtering by starttime or endtime, string must be in RFC 3339 date string format. Name and platform are filtered by string comparison. Ex) "...?filter=channel<=beta, version \>= 80 Ex) "...?filter=version \> 80, version < 81 Ex) "...?filter=starttime\>2020-01-01T00:00:00Z
*/
filter?: string;
/**
* Optional. Ordering string. Valid order_by strings are "version", "name", "starttime", "endtime", "platform", "channel", and "fraction". Optionally, you can append "desc" or "asc" to specify the sorting order. Multiple order_by strings can be used in a comma separated list. Ordering by channel will sort by distance from the stable channel (not alphabetically). A list of channels sorted in this order is: stable, beta, dev, canary, and canary_asan. Sorting by name may cause unexpected behaviour as it is a naive string sort. For example, 1.0.0.8 will be before 1.0.0.10 in descending order. If order_by is not specified the response will be sorted by starttime in descending order. Ex) "...?order_by=starttime asc" Ex) "...?order_by=platform desc, channel, startime desc"
*/
orderBy?: string;
/**
* Optional. Optional limit on the number of releases to include in the response. If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* Optional. A page token, received from a previous `ListReleases` call. Provide this to retrieve the subsequent page.
*/
pageToken?: string;
/**
* Required. The version, which owns this collection of releases. Format: {product\}/platforms/{platform\}/channels/{channel\}/versions/{version\}
*/
parent?: string;
}
} | the_stack |
import * as React from "react"
import {
StandardLonghandProperties,
StandardShorthandProperties,
Property,
} from "csstype"
export type Assign<T, U> = {
[P in keyof (T & U)]: P extends keyof T
? T[P]
: P extends keyof U
? U[P]
: never
}
export type ForwardRef<T, P> = React.ForwardRefExoticComponent<
React.PropsWithoutRef<P> & React.RefAttributes<T>
>
export interface CssProps
extends StandardLonghandProperties,
StandardShorthandProperties {}
export type ComponentProps<T extends keyof JSX.IntrinsicElements> = Assign<
React.ComponentProps<T>,
BoxProps
>
export type ComponentWithRef<
T,
P extends keyof JSX.IntrinsicElements
> = ForwardRef<T, ComponentProps<P>>
export interface AliasProps {
/**
* Th/**e **d``** is a shorthand property for the **`display`** CSS property.
*/
d?: Property.Display
/**
* The **`bg`** is a shorthand property for the **`backgroundColor`** CSS property.
*/
bg?: Property.BackgroundColor
/**
* The **m``** is a shorthand property for the **`margin`** CSS property.
*/
m?: Property.Margin
/**
* The **`mt`** is a shorthand property for the **`marginTop`** CSS property.
*/
mt?: Property.MarginTop
/**
* The **`mr`** is a shorthand property for the **`marginRight`** CSS property.
*/
mr?: Property.MarginRight
/**
* The **`mb`** is a shorthand property for the **`marginBottom`** CSS property.
*/
mb?: Property.MarginBottom
/**
* The **`ml`** is a shorthand property for the **`marginLeft`** CSS property.
*/
ml?: Property.MarginLeft
/**
* The **`mx`** is a shorthand property for the **`marginX`** CSS property.
*/
mx?: Property.MarginLeft
/**
* The **`my`** is a shorthand property for the **`marginY`** CSS property.
*/
my?: Property.MarginTop
/**
* The **p``** is a shorthand property for the **`padding`** CSS property.
*/
p?: Property.Padding
/**
* The **`pt`** is a shorthand property for the **`paddingTop`** CSS property.
*/
pt?: Property.PaddingTop
/**
* The **`pr`** is a shorthand property for the **`paddingRight`** CSS property.
*/
pr?: Property.PaddingRight
/**
* The **`pb`** is a shorthand property for the **`paddingBottom`** CSS property.
*/
pb?: Property.PaddingBottom
/**
* The **`pl`** is a shorthand property for the **`paddingLeft`** CSS property.
*/
pl?: Property.PaddingLeft
/**
* The **`px`** is a shorthand property for the **`paddingX`** CSS property.
*/
px?: Property.PaddingLeft
/**
* The **`py`** is a shorthand property for the **`paddingY`** CSS property.
*/
py?: Property.PaddingTop
/**
* The **`maxW`** is a shorthand property for the **`maxWidth`** CSS property.
*/
maxW?: Property.MaxWidth
/**
* The **`minW`** is a shorthand property for the **`minWidth`** CSS property.
*/
minW?: Property.MinWidth
/**
* The **w``** is a shorthand property for the **`width`** CSS property.
*/
w?: Property.Width
/**
* The **h``** is a shorthand property for the **`height`** CSS property.
*/
h?: Property.Height
/**
* The **`maxH`** is a shorthand property for the **`maxHeight`** CSS property.
*/
maxH?: Property.MaxHeight
/**
* The **`minH`** is a shorthand property for the **`minHeight`** CSS property.
*/
minH?: Property.MinHeight
/**
* The **`col`** is a shorthand property for the **`gridTemplateColumns`** CSS property.
*/
col?: Property.GridTemplateColumns
/**
* The **`colStart`** is a shorthand property for the **`gridColumnStart`** CSS property.
*/
colStart?: Property.GridColumnStart
/**
* The **`colEnd`** is a shorthand property for the **`gridColumnEnd`** CSS property.
*/
colEnd?: Property.GridColumnEnd
/**
* The **`colGap`** is a shorthand property for the **`gridColumnGap`** CSS property.
*/
colGap?: Property.GridColumnGap
/**
* The **`row`** is a shorthand property for the **`gridTemplateRows`** CSS property.
*/
row?: Property.GridTemplateRows
/**
* The **`rowStart`** is a shorthand property for the **`gridRowStart`** CSS property.
*/
rowStart?: Property.GridRowStart
/**
* The **`rowEnd`** is a shorthand property for the **`gridRowEnd`** CSS property.
*/
rowEnd?: Property.GridRowEnd
/**
* The **``** is a shorthand property for the **`gridRowGap`** CSS property.
*/
rowGap?: Property.GridRowGap
/**
* The **`rounded`** is a shorthand property for the **`borderRadius`** CSS property.
*/
rounded?: Property.BorderRadius
/**
* The **`rounded`** is a shorthand property for the **`borderTopLeftRadius`** and **`borderTopRightRadius`** CSS properties.
*/
roundedTop?: Property.BorderTopLeftRadius
/**
* The **`roundedRight`** is a shorthand property for the **`borderTopRightRadius`** and **`borderBottomRightRadius`** CSS properties.
*/
roundedRight?: Property.BorderTopRightRadius
/**
* The **`roundedBottom`** is a shorthand property for the **`borderBottomLeftRadius`** and **`borderBottomRightRadius`** CSS properties.
*/
roundedBottom?: Property.BorderBottomLeftRadius
/**
* The **`roundedLeft`** is a shorthand property for the **`borderTopLeftRadius`** and **`borderBottomLeftRadius`** CSS properties.
*/
roundedLeft?: Property.BorderTopLeftRadius
/**
* The **`size`** is a shorthand property for the **`width`** and **`height`** CSS properties.
*/
size?: Property.Width
}
export interface BoxProps extends CssProps, AliasProps {
as?: string
variant?: string
}
export const A: ComponentWithRef<HTMLAnchorElement, "a">
export const Abbr: ComponentWithRef<HTMLElement, "abbr">
export const Address: ComponentWithRef<HTMLElement, "address">
export const Area: ComponentWithRef<HTMLAreaElement, "area">
export const Article: ComponentWithRef<HTMLElement, "article">
export const Aside: ComponentWithRef<HTMLElement, "aside">
export const Audio: ComponentWithRef<HTMLAudioElement, "audio">
export const B: ComponentWithRef<HTMLElement, "b">
export const Base: ComponentWithRef<HTMLBaseElement, "base">
export const Bdi: ComponentWithRef<HTMLElement, "bdi">
export const Bdo: ComponentWithRef<HTMLElement, "bdo">
export const Blockquote: ComponentWithRef<HTMLElement, "blockquote">
export const Body: ComponentWithRef<HTMLBodyElement, "body">
export const Br: ComponentWithRef<HTMLBRElement, "br">
export const Button: ComponentWithRef<HTMLButtonElement, "button">
export const Canvas: ComponentWithRef<HTMLCanvasElement, "canvas">
export const Caption: ComponentWithRef<HTMLTableCaptionElement, "caption">
export const Cite: ComponentWithRef<HTMLElement, "cite">
export const Code: ComponentWithRef<HTMLElement, "code">
export const Col: ComponentWithRef<HTMLTableColElement, "col">
export const Colgroup: ComponentWithRef<HTMLElement, "colgroup">
export const Data: ComponentWithRef<HTMLDataElement, "data">
export const Datalist: ComponentWithRef<HTMLDataListElement, "datalist">
export const Dd: ComponentWithRef<HTMLElement, "dd">
export const Del: ComponentWithRef<HTMLElement, "del">
export const Details: ComponentWithRef<HTMLDetailsElement, "details">
export const Dfn: ComponentWithRef<HTMLElement, "dfn">
export const Dialog: ComponentWithRef<HTMLDialogElement, "dialog">
export const Div: ComponentWithRef<HTMLDivElement, "div">
export const Dl: ComponentWithRef<HTMLElement, "dl">
export const Dt: ComponentWithRef<HTMLElement, "dt">
export const Em: ComponentWithRef<HTMLElement, "em">
export const Embed: ComponentWithRef<HTMLEmbedElement, "embed">
export const Fieldset: ComponentWithRef<HTMLFieldSetElement, "fieldset">
export const Figcaption: ComponentWithRef<HTMLElement, "figcaption">
export const Figure: ComponentWithRef<HTMLElement, "figure">
export const Footer: ComponentWithRef<HTMLElement, "footer">
export const Form: ComponentWithRef<HTMLFormElement, "form">
export const H1: ComponentWithRef<HTMLHeadingElement, "h1">
export const H2: ComponentWithRef<HTMLHeadingElement, "h2">
export const H3: ComponentWithRef<HTMLHeadingElement, "h3">
export const H4: ComponentWithRef<HTMLHeadingElement, "h4">
export const H5: ComponentWithRef<HTMLHeadingElement, "h5">
export const H6: ComponentWithRef<HTMLHeadingElement, "h6">
export const Head: ComponentWithRef<HTMLHeadElement, "head">
export const Header: ComponentWithRef<HTMLElement, "header">
export const Hr: ComponentWithRef<HTMLHRElement, "hr">
export const Html: ComponentWithRef<HTMLHtmlElement, "html">
export const I: ComponentWithRef<HTMLElement, "i">
export const Iframe: ComponentWithRef<HTMLIFrameElement, "iframe">
export const Img: ComponentWithRef<HTMLImageElement, "img">
export const Input: ComponentWithRef<HTMLInputElement, "input">
export const Ins: ComponentWithRef<HTMLElement, "ins">
export const Kbd: ComponentWithRef<HTMLElement, "kbd">
export const Label: ComponentWithRef<HTMLLabelElement, "label">
export const Legend: ComponentWithRef<HTMLLegendElement, "legend">
export const Li: ComponentWithRef<HTMLLIElement, "li">
export const Main: ComponentWithRef<HTMLElement, "main">
export const Map: ComponentWithRef<HTMLMapElement, "map">
export const Mark: ComponentWithRef<HTMLElement, "mark">
export const Meta: ComponentWithRef<HTMLMetaElement, "meta">
export const Meter: ComponentWithRef<HTMLMeterElement, "meter">
export const Nav: ComponentWithRef<HTMLElement, "nav">
export const Ol: ComponentWithRef<HTMLOListElement, "ol">
export const Optgroup: ComponentWithRef<HTMLOptGroupElement, "optgroup">
export const Option: ComponentWithRef<HTMLOptionElement, "option">
export const Output: ComponentWithRef<HTMLOutputElement, "output">
export const P: ComponentWithRef<HTMLParagraphElement, "p">
export const Param: ComponentWithRef<HTMLParamElement, "param">
export const Path: ComponentWithRef<HTMLElement, "path">
export const Picture: ComponentWithRef<HTMLPictureElement, "picture">
export const Pre: ComponentWithRef<HTMLPreElement, "pre">
export const Progress: ComponentWithRef<HTMLProgressElement, "progress">
export const Q: ComponentWithRef<HTMLElement, "q">
export const Rp: ComponentWithRef<HTMLElement, "rp">
export const Rt: ComponentWithRef<HTMLElement, "rt">
export const Ruby: ComponentWithRef<HTMLElement, "ruby">
export const S: ComponentWithRef<HTMLElement, "s">
export const Samp: ComponentWithRef<HTMLElement, "samp">
export const Section: ComponentWithRef<HTMLElement, "section">
export const Select: ComponentWithRef<HTMLSelectElement, "select">
export const Small: ComponentWithRef<HTMLElement, "small">
export const Source: ComponentWithRef<HTMLSourceElement, "source">
export const Span: ComponentWithRef<HTMLSpanElement, "span">
export const Strong: ComponentWithRef<HTMLElement, "strong">
export const Style: ComponentWithRef<HTMLStyleElement, "style">
export const Sub: ComponentWithRef<HTMLElement, "sub">
export const Summary: ComponentWithRef<HTMLElement, "summary">
export const Sup: ComponentWithRef<HTMLElement, "sup">
export const Svg: ComponentWithRef<HTMLOrSVGElement, "svg">
export const Table: ComponentWithRef<HTMLTableElement, "table">
export const Tbody: ComponentWithRef<HTMLElement, "tbody">
export const Td: ComponentWithRef<HTMLTableDataCellElement, "td">
export const Template: ComponentWithRef<HTMLTemplateElement, "template">
export const Textarea: ComponentWithRef<HTMLTextAreaElement, "textarea">
export const Tfoot: ComponentWithRef<HTMLTableSectionElement, "tfoot">
export const Th: ComponentWithRef<HTMLTableHeaderCellElement, "th">
export const Thead: ComponentWithRef<HTMLTableSectionElement, "thead">
export const Time: ComponentWithRef<HTMLTimeElement, "time">
export const Title: ComponentWithRef<HTMLTitleElement, "title">
export const Tr: ComponentWithRef<HTMLTableRowElement, "tr">
export const Track: ComponentWithRef<HTMLTrackElement, "track">
export const U: ComponentWithRef<HTMLElement, "u">
export const Ul: ComponentWithRef<HTMLUListElement, "ul">
export const Video: ComponentWithRef<HTMLVideoElement, "video">
export const Wbr: ComponentWithRef<HTMLElement, "wbr">
export const Container: ComponentWithRef<HTMLDivElement, "div">
export const Flexbox: ComponentWithRef<HTMLDivElement, "div">
export const Grid: ComponentWithRef<HTMLDivElement, "div">
export const VisuallyHidden: ComponentWithRef<HTMLSpanElement, "span">
export const Icon: ComponentWithRef<HTMLOrSVGElement, "svg"> | the_stack |
import {
ActionBaseJSON,
AnyContractParameterJSON,
ArrayContractParameterJSON,
AttributeJSON,
Block,
BlockJSON,
BooleanContractParameter,
BooleanContractParameterJSON,
ByteArrayContractParameterJSON,
CallReceiptJSON,
common,
ConfirmedTransaction,
Contract,
ContractABI,
ContractABIJSON,
ContractJSON,
ContractManifestJSON,
ForwardValue,
Hash160ABIParameter,
Hash160ContractParameter,
Hash160ContractParameterJSON,
Hash256ContractParameterJSON,
Header,
HeaderJSON,
IntegerABIParameter,
IntegerABIReturn,
IntegerContractParameter,
IntegerContractParameterJSON,
InteropInterfaceContractParameterJSON,
InvocationDataJSON,
LogActionJSON,
MapContractParameterJSON,
NetworkSettings,
NetworkSettingsJSON,
NotificationActionJSON,
Peer,
PublicKeyContractParameterJSON,
RawActionBase,
RawCallReceipt,
RawInvocationData,
RawInvocationResultErrorJSON,
RawInvocationResultSuccessJSON,
RawInvokeReceipt,
RawLog,
RawNotification,
RawTransactionResultError,
RawTransactionResultSuccess,
SignatureContractParameterJSON,
SmartContractDefinition,
StorageItemJSON,
StringABIParameter,
StringABIReturn,
StringContractParameter,
StringContractParameterJSON,
Transaction,
TransactionJSON,
TransactionModel,
TransactionModelAdd,
TransactionReceipt,
TransactionResult,
TransactionResultError,
TransactionResultErrorJSON,
TransactionResultSuccess,
TransactionResultSuccessJSON,
TransactionWithInvocationDataJSON,
Transfer,
UserAccount,
UserAccountID,
VerifyScriptResultJSON,
VerifyTransactionResultJSON,
VoidContractParameterJSON,
Witness,
WitnessJSON,
} from '@neo-one/client-common';
import BigNumber from 'bignumber.js';
import { BN } from 'bn.js';
import { ContractEventDescriptor, ContractMethodDescriptor } from '../../../neo-one-node-core/src/manifest';
import { Hash160 } from '../Hash160';
import * as nep17 from '../nep17';
import { LockedWallet, UnlockedWallet } from '../user';
import { data } from './data';
import { keys } from './keys';
const createContractABIJSON = (options: Partial<ContractABIJSON> = {}): ContractABIJSON => ({
hash: keys[0].scriptHashString,
methods: [], // TODO
events: [], // TODO
...options,
// parameters: ['Hash160', 'ByteArray'],
// returntype: 'ByteArray',
});
const createManifestJSON = (options: Partial<ContractManifestJSON> = {}): ContractManifestJSON => {
const { abi, ...optionsIn } = options;
return {
hash: keys[0].scriptHashString,
hashHex: keys[0].scriptHashString,
abi: createContractABIJSON(abi),
groups: [], // TODO
permissions: [], // TODO
trusts: '*',
supportedStandards: [], // TODO
...optionsIn,
};
};
const createContractJSON = (options: Partial<ContractJSON> = {}): ContractJSON => {
const { manifest, ...optionsIn } = options;
return {
id: 0,
script: data.buffers.b,
manifest: createManifestJSON(manifest),
...optionsIn,
};
};
const createActionBaseJSON = (options: Partial<ActionBaseJSON> = {}): ActionBaseJSON => ({
version: 0,
index: '10',
scriptHash: keys[0].scriptHashString,
...options,
});
const createNotificationActionJSON = (options: Partial<NotificationActionJSON> = {}): NotificationActionJSON => ({
...createActionBaseJSON(),
type: 'Notification',
args: [createIntegerContractParameterJSON()],
...options,
});
const createLogActionJSON = (options: Partial<LogActionJSON> = {}): LogActionJSON => ({
...createActionBaseJSON(),
type: 'Log',
message: 'Hello World',
...options,
});
const createHighPriorityAttributeJSON = (options: Partial<AttributeJSON> = {}): AttributeJSON => ({
type: 'HighPriority',
...options,
});
const createWitnessJSON = (options: Partial<WitnessJSON> = {}): WitnessJSON => ({
invocation: data.buffers.a,
verification: data.buffers.b,
...options,
});
const createTransactionJSON = (options: Partial<TransactionJSON> = {}): TransactionJSON => ({
hash: data.hash256s.a,
size: 256,
version: 0,
attributes: [createHighPriorityAttributeJSON()],
script: data.buffers.a,
sysfee: '10',
netfee: '5',
nonce: 10, // TODO
sender: '', // TODO
validuntilblock: 1000, // TODO
signers: [], // TODO
witnesses: [], // TODO
data: {
blockHash: data.hash256s.b,
blockIndex: 5,
blockTime: 0, // TODO
confirmations: 0, // TODO
transactionHash: '', // TODO
transactionIndex: 10,
globalIndex: '25',
},
...options,
});
const createTransactionWithInvocationDataJSON = (
options: Partial<TransactionWithInvocationDataJSON> = {},
): TransactionWithInvocationDataJSON => ({
// TODO: get options into invocationData and createTransactionJSON()
...createTransactionJSON(),
script: Buffer.from(data.buffers.a, 'hex').toString('hex'),
gas: '0', // TODO
invocationData: createInvocationDataJSON(),
...options,
});
const createIntegerContractParameterJSON = (
options: Partial<IntegerContractParameterJSON> = {},
): IntegerContractParameterJSON => ({
name: 'param',
type: 'Integer',
value: '20',
...options,
});
const createTransactionResultSuccessJSON = (
options: Partial<TransactionResultSuccessJSON> = {},
): TransactionResultSuccessJSON => ({
script: '', // TODO
state: 'HALT',
gas_consumed: '20',
gas_cost: '20',
stack: [createIntegerContractParameterJSON()],
...options,
});
const createTransactionResultErrorJSON = (
options: Partial<TransactionResultErrorJSON> = {},
): TransactionResultErrorJSON => ({
script: '', // TODO
state: 'FAULT',
gas_consumed: '20',
gas_cost: '20',
stack: [createIntegerContractParameterJSON()],
message: 'failure',
...options,
});
const createRawInvocationResultSuccessJSON = (
options: Partial<RawInvocationResultSuccessJSON> = {},
): RawInvocationResultSuccessJSON => ({
state: 'HALT',
gas_consumed: '20',
stack: [createIntegerContractParameterJSON()],
...options,
});
const createRawInvocationResultErrorJSON = (
options: Partial<RawInvocationResultErrorJSON> = {},
): RawInvocationResultErrorJSON => ({
state: 'FAULT',
gas_consumed: '20',
stack: [createIntegerContractParameterJSON()],
...options,
});
const createInvocationDataJSON = (options: Partial<InvocationDataJSON> = {}): InvocationDataJSON => ({
result: createTransactionResultSuccessJSON(),
contracts: [createContractJSON()],
deletedContractHashes: [keys[2].scriptHashString],
migratedContractHashes: [[keys[0].scriptHashString, keys[1].scriptHashString]],
voteUpdates: [],
actions: [createNotificationActionJSON(), createLogActionJSON()],
storageChanges: [],
...options,
});
const createTransactionModel = (options: Partial<TransactionModelAdd> = {}): TransactionModel => {
const invocation = createTransactionWithInvocationDataJSON();
return new TransactionModel({
script: Buffer.from(invocation.script, 'hex'),
version: invocation.version,
attributes: [],
systemFee: new BN(0), // TODO
hash: common.hexToUInt256(invocation.hash),
...options,
});
};
const createTransactionReceipt = (options: Partial<TransactionReceipt> = {}): TransactionReceipt => ({
blockHash: data.hash256s.a,
blockIndex: 0,
transactionIndex: 3,
transactionHash: '', // TODO
blockTime: 0, // TODO
confirmations: 10, // TODO
globalIndex: new BigNumber(4),
...options,
});
const createCallReceiptJSON = (options: Partial<CallReceiptJSON> = {}): CallReceiptJSON => ({
result: createTransactionResultSuccessJSON(),
actions: [createNotificationActionJSON(), createLogActionJSON()],
...options,
});
const createVerifyScriptResultJSON = (options: Partial<VerifyScriptResultJSON> = {}): VerifyScriptResultJSON => ({
hash: keys[0].scriptHashString,
witness: factory.createWitness(),
actions: [createLogActionJSON()],
...options,
});
const createVerifyTransactionResultJSON = (
options: Partial<VerifyTransactionResultJSON> = {},
): VerifyTransactionResultJSON => ({
verifications: [createVerifyScriptResultJSON()],
...options,
});
const createHeaderJSON = (options: Partial<HeaderJSON> = {}): HeaderJSON => ({
version: 0,
hash: data.hash256s.a,
previousblockhash: data.hash256s.b,
merkleroot: data.hash256s.c,
time: data.timestamps.past.toString(),
index: 10,
nextconsensus: keys[0].address,
witnesses: [createWitnessJSON()],
size: 256,
...options,
});
const createBlockJSON = (options: Partial<BlockJSON> = {}): BlockJSON => ({
...createHeaderJSON(),
tx: [createTransactionWithInvocationDataJSON()],
...options,
});
const createPeerJSON = (options: Partial<Peer> = {}): Peer => ({
address: 'localhost',
port: 1340,
...options,
});
const createNetworkSettingsJSON = (options: Partial<NetworkSettingsJSON> = {}): NetworkSettingsJSON => ({
issueGASFee: data.bigNumbers.a.toString(10),
...options,
});
const createStorageItemJSON = (options: Partial<StorageItemJSON> = {}): StorageItemJSON => ({
hash: keys[0].scriptHashString,
key: data.buffers.a,
value: data.buffers.b,
flags: 'None',
...options,
});
const createAnyContractParameterJSON = (options: Partial<AnyContractParameterJSON> = {}): AnyContractParameterJSON => ({
name: 'param',
type: 'Any',
value: undefined,
...options,
});
const createArrayContractParameterJSON = (
options: Partial<ArrayContractParameterJSON> = {},
): ArrayContractParameterJSON => ({
name: 'param',
type: 'Array',
value: [createBooleanContractParameterJSON()],
...options,
});
const createBooleanContractParameterJSON = (
options: Partial<BooleanContractParameterJSON> = {},
): BooleanContractParameterJSON => ({
name: 'param',
type: 'Boolean',
value: true,
...options,
});
const createByteArrayContractParameterJSON = (
options: Partial<ByteArrayContractParameterJSON> = {},
): ByteArrayContractParameterJSON => ({
name: 'param',
type: 'ByteArray',
value: Buffer.alloc(1, 0xff).toString(),
...options,
});
const createHash160ContractParameterJSON = (
options: Partial<Hash160ContractParameterJSON> = {},
): Hash160ContractParameterJSON => ({
name: 'param',
type: 'Hash160',
value: keys[0].scriptHashString,
...options,
});
const createHash256ContractParameterJSON = (
options: Partial<Hash256ContractParameterJSON> = {},
): Hash256ContractParameterJSON => ({
name: 'param',
type: 'Hash256',
value: data.hash256s.a,
...options,
});
const createInteropInterfaceContractParameterJSON = (options: Partial<InteropInterfaceContractParameterJSON> = {}) => ({
type: 'InteropInterface' as 'InteropInterface',
name: 'param',
...options,
});
const createMapContractParameterJSON = (options: Partial<MapContractParameterJSON> = {}): MapContractParameterJSON => ({
name: 'param',
type: 'Map',
value: [[createIntegerContractParameterJSON(), createBooleanContractParameterJSON()]],
...options,
});
const createPublicKeyContractParameterJSON = (
options: Partial<PublicKeyContractParameterJSON> = {},
): PublicKeyContractParameterJSON => ({
name: 'param',
type: 'PublicKey',
value: keys[0].publicKeyString,
...options,
});
const createSignatureContractParameterJSON = (
options: Partial<SignatureContractParameterJSON> = {},
): SignatureContractParameterJSON => ({
name: 'param',
type: 'Signature',
value: data.signatures.a,
...options,
});
const createStringContractParameterJSON = (
options: Partial<StringContractParameterJSON> = {},
): StringContractParameterJSON => ({
name: 'param',
type: 'String',
value: 'test',
...options,
});
const createVoidContractParameterJSON = (
options: Partial<VoidContractParameterJSON> = {},
): VoidContractParameterJSON => ({
name: 'param',
type: 'Void',
...options,
});
const createContract = (options: Partial<Contract> = {}): Contract => ({
version: 0,
address: keys[0].address,
script: data.buffers.b,
parameters: ['Address', 'Buffer'],
returnType: 'Buffer',
name: 'MyContract',
codeVersion: '1.0',
author: 'dicarlo2',
email: 'alex.dicarlo@neotracker.io',
description: 'Hello World',
storage: true,
dynamicInvoke: false,
payable: true,
...options,
});
const createRawActionBase = (options: Partial<RawActionBase> = {}): RawActionBase => ({
version: 0,
blockHash: data.hash256s.a,
blockIndex: 0,
transactionHash: data.hash256s.b,
transactionIndex: 1,
index: data.numbers.a,
globalIndex: data.bigNumbers.a,
address: keys[0].address,
...options,
});
const createRawNotification = (options: Partial<RawNotification> = {}): RawNotification => ({
...createRawActionBase(),
type: 'Notification',
args: [createIntegerContractParameter()],
...options,
});
const createRawTransferNotification = (options: Partial<RawNotification> = {}): RawNotification =>
createRawNotification({
args: [
createStringContractParameter({ value: 'transfer' }),
createHash160ContractParameter({ value: keys[0].address }),
createHash160ContractParameter({ value: keys[1].address }),
createIntegerContractParameter({ value: data.bns.b }),
],
...options,
});
const createRawLog = (options: Partial<RawLog> = {}): RawLog => ({
...createRawActionBase(),
type: 'Log',
message: 'Hello World',
...options,
});
const createWitness = (options: Partial<Witness> = {}): Witness => ({
invocation: data.buffers.a,
verification: data.buffers.b,
...options,
});
const createTransaction = (options: Partial<Transaction> = {}): Transaction => ({
hash: data.hash256s.a,
size: 256,
version: 0,
nonce: 0,
validUntilBlock: 0,
signers: [],
attributes: [],
witnesses: [createWitness()],
systemFee: new BigNumber('10'),
networkFee: new BigNumber('5'),
script: data.buffers.a,
...options,
});
const createHash160ContractParameter = (options: Partial<Hash160ContractParameter> = {}): Hash160ContractParameter => ({
name: 'param',
type: 'Hash160',
value: keys[0].address,
...options,
});
const createStringContractParameter = (options: Partial<StringContractParameter> = {}): StringContractParameter => ({
name: 'param',
type: 'String',
value: 'transfer',
...options,
});
const createIntegerContractParameter = (options: Partial<IntegerContractParameter> = {}): IntegerContractParameter => ({
name: 'param',
type: 'Integer',
value: new BN(20),
...options,
});
const createBooleanContractParameter = (options: Partial<BooleanContractParameter> = {}): BooleanContractParameter => ({
name: 'param',
type: 'Boolean',
value: true,
...options,
});
const createRawInvocationResultError = (
options: Partial<RawTransactionResultError> = {},
): RawTransactionResultError => ({
script: '', // TODO
state: 'FAULT',
gasConsumed: new BigNumber('10'),
gasCost: new BigNumber('20'),
stack: [createIntegerContractParameter()],
message: 'Failure!',
...options,
});
const createRawInvocationResultSuccess = (
options: Partial<RawTransactionResultSuccess> = {},
): RawTransactionResultSuccess => ({
script: '', // TODO
state: 'HALT',
gasConsumed: new BigNumber('10'),
gasCost: new BigNumber('20'),
stack: [createIntegerContractParameter()],
...options,
});
const createInvocationResultError = (options: Partial<TransactionResultError> = {}): TransactionResultError => ({
script: '', // TODO
state: 'FAULT',
gasConsumed: new BigNumber('20'),
gasCost: new BigNumber('10'),
message: 'Failed!',
...options,
});
const createInvocationResultSuccess = (
options: Partial<TransactionResultSuccess<boolean>> = {},
): TransactionResultSuccess<boolean> => ({
script: '', // TODO
state: 'HALT',
gasConsumed: new BigNumber('20'),
gasCost: new BigNumber('10'),
value: true,
...options,
});
const createRawInvocationData = (options: Partial<RawInvocationData> = {}): RawInvocationData => ({
result: createRawInvocationResultSuccess(),
contracts: [createContract()],
deletedContractAddresses: [keys[2].address],
migratedContractAddresses: [[keys[0].address, keys[1].address]],
actions: [createRawNotification(), createRawLog()],
storageChanges: [],
...options,
});
const createConfirmedTransactionBase = (options: Partial<ConfirmedTransaction> = {}): ConfirmedTransaction => ({
receipt: {
blockHash: data.hash256s.a,
blockIndex: 10,
transactionIndex: 1,
globalIndex: new BigNumber('11'),
},
...options,
});
const createConfirmedTransaction = (options: Partial<ConfirmedTransaction> = {}): ConfirmedTransaction => ({
...createTransaction(),
...createConfirmedTransactionBase(),
invocationData: createRawInvocationData(),
...options,
});
const createRawCallReceipt = (options: Partial<RawCallReceipt> = {}): RawCallReceipt => ({
result: createRawInvocationResultSuccess(),
actions: [createRawNotification(), createRawLog()],
...options,
});
const createRawInvokeReceipt = (options: Partial<RawInvokeReceipt> = {}): RawInvokeReceipt => ({
blockIndex: 10,
blockHash: data.hash256s.a,
transactionIndex: 1,
globalIndex: new BigNumber(11),
result: createRawInvocationResultSuccess(),
actions: [createRawNotification(), createRawLog()],
...options,
});
const createNetworkSettings = (options: Partial<NetworkSettings> = {}): NetworkSettings => ({
issueGASFee: data.bigNumbers.a,
...options,
});
const createUserAccountID = (options: Partial<UserAccountID> = {}): UserAccountID => ({
network: 'main',
address: keys[1].address,
...options,
});
const createUserAccount = (options: Partial<UserAccount> = {}): UserAccount => ({
id: createUserAccountID(),
name: 'Mock',
publicKey: keys[1].publicKeyString,
...options,
});
const createLockedWallet = (options: Partial<LockedWallet> = {}): LockedWallet => ({
type: 'locked',
userAccount: createUserAccount(),
nep2: keys[1].encryptedWIF,
...options,
});
const createUnlockedWallet = (options: Partial<UnlockedWallet> = {}): UnlockedWallet => ({
type: 'unlocked',
userAccount: createUserAccount({
id: createUserAccountID({
address: keys[0].address,
}),
publicKey: keys[0].publicKeyString,
}),
privateKey: keys[0].privateKeyString,
nep2: keys[0].encryptedWIF,
...options,
});
const createOtherWallet = (options: Partial<UnlockedWallet> = {}): UnlockedWallet => ({
type: 'unlocked',
userAccount: createUserAccount({
id: createUserAccountID({
address: keys[1].address,
}),
publicKey: keys[1].publicKeyString,
}),
privateKey: keys[1].privateKeyString,
nep2: keys[1].encryptedWIF,
...options,
});
const createTransfer = (options: Partial<Transfer> = {}): Transfer => ({
to: keys[0].address,
amount: data.bigNumbers.a,
asset: Hash160.NEO,
...options,
});
const createHash160ABIParameter = (options: Partial<Hash160ABIParameter> = {}): Hash160ABIParameter => ({
type: 'Hash160',
name: 'from',
...options,
});
const createIntegerABIParameter = (options: Partial<IntegerABIParameter> = {}): IntegerABIParameter => ({
type: 'Integer',
name: 'amount',
decimals: 8,
...options,
});
const createDeployContractMethodDescriptor = (
options: Partial<ContractMethodDescriptor> = {},
): ContractMethodDescriptor => ({
name: 'deploy',
parameters: [],
returnType: { type: 'Boolean' },
...options,
});
const createABIEvent = (options: Partial<ContractEventDescriptor> = {}): ContractEventDescriptor => ({
name: 'transfer',
parameters: [
createHash160ABIParameter({ name: 'from' }),
createHash160ABIParameter({ name: 'to' }),
createIntegerABIParameter({ name: 'amount' }),
],
...options,
});
const createStringABIReturn = (): StringABIReturn => ({
type: 'String',
});
const createIntegerABIReturn = (): IntegerABIReturn => ({
type: 'Integer',
decimals: 0,
});
const createStringABIParameter = (options: Partial<StringABIParameter> = {}): StringABIParameter => ({
type: 'String',
name: 'foo',
...options,
});
const createABI = (options: Partial<ContractABI> = {}): ContractABI => ({
...nep17.abi(8),
...options,
});
const createForwardValue = (options: Partial<ForwardValue> = {}): ForwardValue =>
// tslint:disable-next-line:no-object-literal-type-assertion
({
name: 'foo',
converted: true,
param: true,
...options,
} as ForwardValue);
const createContractMethodDescriptor = (options: Partial<ContractMethodDescriptor> = {}): ContractMethodDescriptor => ({
name: 'foo',
parameters: [],
returnType: { type: 'Boolean' },
send: false,
receive: false,
sendUnsafe: false,
refundAssets: false,
completeSend: false,
claim: false,
...options,
});
const createSmartContractDefinition = (options: Partial<SmartContractDefinition> = {}): SmartContractDefinition => ({
networks: {
main: {
address: keys[0].address,
},
},
manifest: createContractManifest(),
...options,
});
const createTransactionResult = (options: Partial<TransactionResult> = {}): TransactionResult => ({
transaction: createTransaction(),
confirmed: jest.fn(async () => createTransactionReceipt()),
...options,
});
const createHeader = (options: Partial<Header> = {}): Header => ({
version: 0,
hash: data.hash256s.a,
previousBlockHash: data.hash256s.b,
merkleRoot: data.hash256s.c,
time: data.timestamps.past,
index: 10,
nextConsensus: keys[0].address,
size: 256,
witnesses: [createWitness()],
witness: createWitness(),
...options,
});
const createBlock = (options: Partial<Block> = {}): Block => ({
...createHeader(),
transactions: [createConfirmedTransaction()],
...options,
});
export const factory = {
createContractJSON,
createAnyContractParameterJSON,
createIntegerContractParameterJSON,
createArrayContractParameterJSON,
createBooleanContractParameterJSON,
createByteArrayContractParameterJSON,
createHash160ContractParameterJSON,
createHash256ContractParameterJSON,
createInteropInterfaceContractParameterJSON,
createMapContractParameterJSON,
createPublicKeyContractParameterJSON,
createSignatureContractParameterJSON,
createStringContractParameterJSON,
createVoidContractParameterJSON,
createInvocationDataJSON,
createTransactionResultSuccessJSON,
createTransactionResultErrorJSON,
createTransactionJSON,
createTransactionWithInvocationDataJSON,
createTransactionReceipt,
createCallReceiptJSON,
createLogActionJSON,
createVerifyScriptResultJSON,
createVerifyTransactionResultJSON,
createBlockJSON,
createPeerJSON,
createNetworkSettingsJSON,
createStorageItemJSON,
createContract,
createRawInvocationData,
createTransactionModel,
createTransaction,
createConfirmedTransaction,
createInvocationResultSuccess,
createInvocationResultError,
createRawCallReceipt,
createNetworkSettings,
createWitness,
createLockedWallet,
createUnlockedWallet,
createOtherWallet,
createTransfer,
createDeployContractMethodDescriptor,
createRawInvocationResultError,
createRawInvocationResultSuccess,
createRawLog,
createRawNotification,
createABIEvent,
createContractMethodDescriptor,
createForwardValue,
createHash160ContractParameter,
createIntegerContractParameter,
createStringContractParameter,
createStringABIReturn,
createIntegerABIParameter,
createIntegerABIReturn,
createStringABIParameter,
createRawTransferNotification,
createSmartContractDefinition,
createRawInvokeReceipt,
createBooleanContractParameter,
createUserAccount,
createUserAccountID,
createTransactionResult,
createBlock,
createRawInvocationResultSuccessJSON,
createRawInvocationResultErrorJSON,
}; | the_stack |
import { AppDataElementsStyleTypes } from "~/types/appData";
import { StyleDescItem } from "~/types/modules";
export const style: AppDataElementsStyleTypes = {
basic: {},
gameroot: {},
//#region 转盘
roulette_wrap: {},
roulette_lottery: {},
roulette_wheel: {
border: {
radiusTopLeft: [20, "rem"],
radiusTopRight: [20, "rem"],
radiusBottomLeft: [20, "rem"],
radiusBottomRight: [20, "rem"],
},
backgroundGroup: {
backgroundColor: "rgba(213, 205, 255, 1)",
},
boxShadow: [
{
inset: true,
spread: [0.5, "rem"],
color: "rgba(120, 98, 227, 1 )",
},
],
},
roulette_award: {},
roulette_prizealias: {},
roulette_gameImg: {},
roulette_divide: {
backgroundGroup: {
backgroundColor: "rgba(103, 58, 183, 0.38)",
},
},
roulette_needle: {
backgroundGroup: {
backgroundColor: "rgba(103, 58, 183, 1)",
},
border: {
radiusTopLeft: [10, "rem"],
radiusTopRight: [10, "rem"],
radiusBottomLeft: [10, "rem"],
radiusBottomRight: [10, "rem"],
},
},
roulette_lotterybutton: {
backgroundGroup: {
backgroundColor: "rgba(63, 81, 181, 0.8)",
},
border: {
radiusTopLeft: [10, "rem"],
radiusTopRight: [10, "rem"],
radiusBottomLeft: [10, "rem"],
radiusBottomRight: [10, "rem"],
},
},
//#endregion
//#region 九宫格
boxroulette_items_wrap: {},
boxroulette_items_lottery: {},
boxroulette_items_prizeItem: {
backgroundGroup: {
backgroundColor: "rgba(214, 203, 255, 1)",
},
border: {
radiusTopLeft: [0.8, "rem"],
radiusTopRight: [0.8, "rem"],
radiusBottomLeft: [0.8, "rem"],
radiusBottomRight: [0.8, "rem"],
},
},
boxroulette_items_selected_wrap: {
backgroundGroup: {
backgroundColor: "rgba(255, 225, 135, 0)",
},
border: {
borderPosition: {
border: true,
borderTop: false,
borderRight: false,
borderLeft: false,
borderBottom: false,
},
radiusTopLeft: [0.9, "rem"],
radiusTopRight: [0.9, "rem"],
radiusBottomLeft: [0.9, "rem"],
radiusBottomRight: [0.9, "rem"],
},
display: {
display: "block",
},
boxShadow: [
{
inset: true,
color: "rgba(103, 58, 183, 0.38 )",
spread: [0.2, "rem"],
blur: [0.5, "rem"],
},
{
color: "rgba(63, 81, 181, 1 )",
spread: [0.15, "rem"],
inset: true,
},
],
},
boxroulette_items_selected: {
border: {
borderStyle: "none",
borderPosition: {
border: true,
borderTop: false,
borderRight: false,
borderLeft: false,
borderBottom: false,
},
borderColor: "rgba(0, 0, 0, 0)",
radiusTopLeft: [0.8, "rem"],
radiusTopRight: [0.8, "rem"],
radiusBottomLeft: [0.8, "rem"],
radiusBottomRight: [0.8, "rem"],
},
},
boxroulette_items_gameimg: {},
boxroulette_items_prizealias: {},
boxroulette_items_lotterybuttonwrap: {
border: {
radiusTopLeft: [0.8, "rem"],
radiusTopRight: [0.8, "rem"],
radiusBottomLeft: [0.8, "rem"],
radiusBottomRight: [0.8, "rem"],
},
backgroundGroup: {
backgroundColor: "rgba(103, 58, 183, 1)",
},
},
boxroulette_items_lotterybutton: {},
boxroulette_items_prizeItem_wrap: {
display: {
padding: [
[0.2, "rem"],
[0.2, "rem"],
[0.2, "rem"],
[0.2, "rem"],
],
},
},
//#endregion
//#region 翻牌
flipcard_item: {
backgroundGroup: {},
display: {
padding: [
[0.2, "rem"],
[0.2, "rem"],
[0.2, "rem"],
[0.2, "rem"],
],
},
},
flipcard_flipper: {
backgroundGroup: {
backgroundColor: "rgba(255, 193, 7, 1)",
},
},
flipcard_front: {
backgroundGroup: {
backgroundColor: "rgba(193, 159, 255, 1)",
},
},
flipcard_back: {
backgroundGroup: {
backgroundColor: "rgba(156, 39, 176, 1)",
},
},
flipcard_prizeAlias: {
font: {
color: "rgba(255, 255, 255, 1)",
},
},
flipcard_prizeImg: {
border: {
radiusTopLeft: [2, "rem"],
radiusTopRight: [2, "rem"],
radiusBottomLeft: [2, "rem"],
radiusBottomRight: [2, "rem"],
},
},
//#endregion
//#region 红包
redenvelope_wrap: {},
redenvelope_redpack: {
display: {
height: [50, "vh"],
position: "absolute",
top: [-20, "%"],
},
},
redenvelope_redpackopen: {},
redenvelope_topcontent: {},
redenvelope_info: {},
redenvelope_subtitle: {},
redenvelope_title: {},
redenvelope_result: {},
redenvelope_gameprizename: {},
redenvelope_gameawardmsg: {},
redenvelope_actionbox: {},
redenvelope_startbutton: {},
redenvelope_resultcontent: {},
redenvelope_gameprize: {},
redenvelope_memo: {},
redenvelope_ensure: {},
//#endregion
//#region 骰子
dice_side: {
backgroundGroup: {
backgroundColor: "rgba(156, 39, 176, 1)",
},
boxShadow: [
{
inset: true,
color: "rgba(176, 38, 210, 0.66 )",
},
],
},
dice_dot: {
backgroundGroup: {
backgroundColor: "rgba(255, 255, 255, 1)",
},
boxShadow: [
{
inset: true,
spread: [0, "rem"],
color: "rgba(0, 0, 0, 0.29 )",
blur: [0.2, "rem"],
},
],
},
dice_dice: {
backgroundGroup: {},
display: {
position: "absolute",
left: [4, "rem"],
},
},
dice_wrap: {},
//#endregion
//#region 老虎机
slotmachine_wrap: {
display: {
height: [6, "rem"],
},
backgroundGroup: {},
},
slotmachine_game: {
boxShadow: [
{
inset: true,
shiftDown: [3, "rem"],
color: "rgba(255, 255, 255, 0.13 )",
shiftRight: ["", ""],
blur: [null, "rem"],
},
{
inset: true,
color: "rgba(95, 39, 176, 0.6 )",
shiftRight: ["", ""],
spread: [0, "rem"],
blur: [1.2, "rem"],
},
],
border: {
radiusTopLeft: [1, "rem"],
radiusTopRight: [1, "rem"],
radiusBottomLeft: [1, "rem"],
radiusBottomRight: [1, "rem"],
},
backgroundGroup: {
backgroundColor: "rgba(216, 186, 222, 1)",
},
},
slotmachine_gamewrap: {
border: {
radiusTopLeft: [1, "rem"],
radiusTopRight: [1, "rem"],
radiusBottomLeft: [1, "rem"],
radiusBottomRight: [1, "rem"],
},
},
slotmachine_gameitem_wrap: {},
slotmachine_gameitem: {},
slotmachine_gameimg: {
display: {
width: [5, "rem"],
position: "absolute",
left: ["unset", "-"],
top: [5, "%"],
right: [55, "%"],
},
backgroundGroup: {
backgroundColor: "rgba(199, 145, 213, 1)",
},
border: {
radiusTopLeft: [4, "rem"],
radiusTopRight: [4, "rem"],
radiusBottomLeft: [4, "rem"],
radiusBottomRight: [4, "rem"],
},
},
slotmachine_prizealias: {
font: {
lineHeight: [2.5, "rem"],
fontSize: [1.5, "rem"],
align: "left",
color: "rgba(126, 98, 175, 1)",
fontWeight: "bold",
},
backgroundGroup: {},
display: {
position: "absolute",
left: [50, "%"],
},
textShadow: [
{
color: "rgba(255, 255, 255, 1 )",
shiftDown: [1, ""],
},
],
},
slotmachine_startbtn: {
backgroundGroup: {
backgroundColor: "rgba(103, 58, 183, 1)",
},
display: {
width: [4, "rem"],
height: [4, "rem"],
margin: [
[1, "rem"],
["auto", "-"],
[1, "rem"],
["auto", "-"],
],
},
font: {
lineHeight: [4, "rem"],
color: "rgba(255, 255, 255, 1)",
fontSize: [0.9, "rem"],
},
border: {
radiusTopLeft: [50, ""],
radiusTopRight: [50, ""],
radiusBottomLeft: [50, ""],
radiusBottomRight: [50, ""],
borderStyle: "solid",
borderPosition: {
border: true,
borderTop: false,
borderRight: false,
borderLeft: false,
borderBottom: false,
},
borderColor: "rgba(127, 78, 218, 1)",
borderWidth: [0.5, "rem"],
},
boxShadow: [
{
inset: true,
shiftDown: [-1.5, "rem"],
color: "rgba(200, 36, 243, 0.16 )",
},
{
color: "rgba(68, 53, 143, 1 )",
shiftDown: [-0.2, "rem"],
},
],
},
//#endregion
//#region 简约抽奖(按钮)
case_button: {
border: {
radiusTopLeft: [1, "rem"],
radiusTopRight: [1, "rem"],
radiusBottomLeft: [1, "rem"],
radiusBottomRight: [1, "rem"],
borderStyle: "none",
borderWidth: [1, "px"],
borderPosition: {
border: true,
borderTop: false,
borderRight: false,
borderLeft: false,
borderBottom: false,
},
},
display: {
padding: [
[0.5, "rem"],
[1, "rem"],
[0.5, "rem"],
[1, "rem"],
],
},
backgroundGroup: {
backgroundColor: "rgba(103, 58, 183, 1)",
},
font: {
color: "rgba(255, 255, 255, 1)",
fontWeight: "bold",
fontSize: [1, "rem"],
},
},
//#endregion
//#region 通用弹窗
dialog_overlay: {},
dialog_content_wrap: {},
dialog_content: {},
dialog_modules: {
backgroundGroup: {
backgroundColor: "rgba(255, 255, 255, 1)",
},
border: {
radiusTopLeft: [1, "rem"],
radiusTopRight: [1, "rem"],
radiusBottomLeft: [1, "rem"],
radiusBottomRight: [1, "rem"],
},
display: {
width: [80, "vw"],
},
},
dialog_article: {},
dialog_contentwrap: {},
dialog_close: {
display: {
width: [1.6, "rem"],
height: [1.6, "rem"],
position: "absolute",
bottom: [-3.5, "rem"],
left: [50, "%"],
top: ["unset", "-"],
margin: [null, null, null, [-0.8, "rem"]],
},
backgroundGroup: {
backgroundList: [
{
imageUrl:
"https://yyjzx.blob.core.chinacloudapi.cn/upload-test/images/0924132958042.png",
repeat: "no-repeat",
sizeY: [100, "%"],
sizeX: [100, "%"],
},
],
backgroundColor: "rgba(0, 0, 0, 0)",
},
},
dialog_submit: {
backgroundGroup: {
backgroundList: [
{
gradient: [
{
color: "rgba(156, 39, 176, 1)",
transition: 1,
},
{
color: "rgba(103, 58, 183, 1)",
transition: 100,
},
],
gradientDirections: "top",
},
],
},
border: {
borderPosition: {
borderTop: false,
borderRight: false,
borderBottom: false,
borderLeft: false,
border: true,
},
radiusTopLeft: [1, "rem"],
radiusTopRight: [1, "rem"],
radiusBottomLeft: [1, "rem"],
radiusBottomRight: [1, "rem"],
borderStyle: "none",
borderWidth: [0, "px"],
},
font: {
color: "rgba(255, 255, 255, 1)",
fontSize: [1, "rem"],
},
display: {
padding: [
[0.5, "rem"],
[1, "rem"],
[0.5, "rem"],
[1, "rem"],
],
},
},
//#endregion
//#region 中奖弹窗
successmodal_contenttop: {},
successmodal_article_content: {},
successmodal_header: {},
successmodal_modaltitle: {
display: {
padding: [[1, "rem"], null, null, null],
},
font: {
fontWeight: "bold",
fontSize: [1.2, "rem"],
},
},
successmodal_prizename: {
display: {
padding: [[1, "rem"], null, null, null],
},
},
successmodal_awardmsg: {},
successmodal_prizeimg: {
display: {
width: [50, "%"],
},
},
successmodal_memo: {},
successmodal_footer: {
display: {
padding: [[1, "rem"], null, [2, "rem"], null],
},
},
successmodal_contentbottom: {},
//#endregion
//#region 未中奖信息
failedmodal_contenttop: {},
failedmodal_article_content: {},
failedmodal_header: {},
failedmodal_modaltitle: {},
failedmodal_prizename: {
display: {
padding: [[1, "rem"], null, null, null],
},
},
failedmodal_awardmsg: {},
failedmodal_prizeimg: {
display: {
width: [50, "%"],
},
},
failedmodal_memo: {},
failedmodal_footer: {
display: {
padding: [[1, "rem"], null, [2, "rem"], null],
},
},
failedmodal_contentbottom: {},
//#endregion
//#region 地址弹窗
addressmodal_addressbox: {},
addressmodal_formbox: {},
addressmodal_header: {},
addressmodal_main: {},
addressmodal_player: {},
addressmodal_subtitle: {},
addressmodal_row: {},
addressmodal_label: {},
addressmodal_input: {},
addressmodal_textarea: {},
//#endregion
//#region 规则弹窗
rules_content: {},
rules_header: {
font: {
fontSize: [1.2, "rem"],
},
display: {
padding: [[1, "rem"], null, [0.5, "rem"], null],
},
},
rules_list: {},
rules_list_item: {},
rules_footer: {},
//#endregion
//#region 记录弹窗
records_content: {},
records_header: {
font: {
fontSize: [1.2, "rem"],
},
display: {
padding: [[1, "rem"], null, [0.5, "rem"], null],
},
},
records_list: {},
records_list_item: {},
records_list_item_prizeimg_wrap: {},
records_list_item_prizeimg: {},
records_list_item_text: {},
records_list_item_prizename: {},
records_list_item_wintime: {},
records_list_item_saveaddress: {},
records_list_item_address: {},
records_footer: {},
//#endregion
};
export const styleDescription:
| {
[keys: string]: string;
}
| StyleDescItem[] = [
{
title: "基础",
value: "basic",
children: [
{
title: "游戏",
value: "gameroot",
children: [
{
title: "大转盘",
value: "roulette_wrap",
children: [
{
title: "转盘",
value: "roulette_wheel",
children: [
{
title: "奖品",
value: "roulette_award",
children: [
{
title: "奖品图片",
value: "roulette_gameImg",
},
{
title: "奖品别名/名称",
value: "roulette_prizealias",
},
],
},
{
title: "分割线",
value: "roulette_divide",
},
],
},
{
title: "指针",
value: "roulette_needle",
},
{
title: "抽奖按钮",
value: "roulette_lotterybutton",
},
],
},
{
title: "九宫格",
value: "boxroulette_items_wrap",
children: [
{
title: "游戏外框",
value: "boxroulette_items_lottery",
children: [
{
title: "奖品外框",
value: "boxroulette_items_prizeItem_wrap",
children: [
{
title: "奖品",
value: "boxroulette_items_prizeItem",
children: [
{
title: "奖品激活/选中外框",
value: "boxroulette_items_selected_wrap",
children: [
{
title: "奖品激活/选中",
value: "boxroulette_items_selected",
},
],
},
{
title: "奖品图片",
value: "boxroulette_items_gameimg",
},
{
title: "奖品名称",
value: "boxroulette_items_prizealias",
},
],
},
],
},
{
title: "抽奖按钮外框",
value: "boxroulette_items_lotterybuttonwrap",
children: [
{
title: "抽奖按钮",
value: "boxroulette_items_lotterybutton",
},
],
},
],
},
],
},
{
title: "翻牌",
value: "flipcard_wrap",
children: [
{
title: "牌",
value: "flipcard_item",
children: [
{
title: "牌面",
value: "flipcard_front",
},
{
title: "牌底",
value: "flipcard_back",
children: [
{
title: "奖品图片",
value: "flipcard_prizeImg",
},
{
title: "奖品名称",
value: "flipcard_prizeAlias",
},
],
},
],
},
],
},
{
title: "红包",
value: "redenvelope_wrap",
children: [
{
title: "红包外框",
value: "redenvelope_redpack",
children: [
{
title: "红包底",
value: "redenvelope_redpackopen",
},
{
title: "红包封面",
value: "redenvelope_topcontent",
children: [
{
title: "提示文",
value: "redenvelope_info",
children: [
{
title: "标题",
value: "redenvelope_title",
},
{
title: "副标题",
value: "redenvelope_subtitle",
},
],
},
{
title: "打开提示文",
value: "redenvelope_result",
children: [
{
title: "奖品名",
value: "redenvelope_gameprizename",
},
{
title: "奖品信息",
value: "redenvelope_gameawardmsg",
},
],
},
{
title: "按钮外框",
value: "redenvelope_actionbox",
children: [
{
title: "按钮",
value: "redenvelope_startbutton",
},
],
},
{
title: "中奖内容",
value: "redenvelope_resultcontent",
children: [
{
title: "奖品图片",
value: "redenvelope_gameprize",
},
{
title: "奖品备注",
value: "redenvelope_memo",
},
{
title: "操作按钮",
value: "redenvelope_ensure",
},
],
},
],
},
],
},
],
},
{
title: "骰子",
value: "dice_wrap",
children: [
{
title: "骰子外框",
value: "dice_dice",
children: [
{
title: "面",
value: "dice_side",
},
{
title: "点",
value: "dice_dot",
},
],
},
],
},
{
title: "老虎机",
value: "slotmachine_wrap",
children: [
{
title: "游戏",
value: "slotmachine_game",
children: [
{
title: "奖品外框",
value: "slotmachine_gamewrap",
children: [
{
title: "奖品",
value: "slotmachine_gameitem_wrap",
children: [
{
title: "单项奖品",
value: "slotmachine_gameitem",
children: [
{
title: "奖品图片",
value: "slotmachine_gameimg",
},
{
title: "奖品别名",
value: "slotmachine_prizealias",
},
],
},
],
},
],
},
{
title: "游戏按钮",
value: "slotmachine_startbtn",
},
],
},
],
},
{
title: "纯按钮抽奖",
value: "case_button",
},
],
},
{
title: "弹窗(遮罩层)",
value: "dialog_overlay",
children: [
{
title: "包裹器",
value: "dialog_content_wrap",
children: [
{
title: "外框",
value: "dialog_content",
children: [
{
title: "弹窗",
value: "dialog_modules",
children: [
{
title: "内容外框",
value: "dialog_article",
},
{
title: "内容",
value: "dialog_contentwrap",
},
{
title: "提交按钮",
value: "dialog_submit",
},
],
},
{
title: "关闭按钮/图标",
value: "dialog_close",
},
],
},
],
},
],
},
{
title: "中奖弹窗",
value: "successmodal_article_content",
children: [
{
title: "顶部",
value: "successmodal_contenttop",
},
{
title: "头部",
value: "successmodal_header",
children: [
{
title: "标题",
value: "successmodal_modaltitle",
},
],
},
{
title: "奖品名",
value: "successmodal_prizename",
},
{
title: "获奖信息",
value: "successmodal_awardmsg",
},
{
title: "奖品图片",
value: "successmodal_prizeimg",
},
{
title: "奖品备注",
value: "successmodal_memo",
},
{
title: "底部",
value: "successmodal_contentbottom",
},
{
title: "脚部",
value: "successmodal_footer",
},
],
},
{
title: "未中奖弹窗",
value: "failedmodal_article_content",
children: [
{
title: "顶部",
value: "failedmodal_contenttop",
},
{
title: "头部",
value: "failedmodal_header",
children: [
{
title: "标题",
value: "failedmodal_modaltitle",
},
],
},
{
title: "奖品名",
value: "failedmodal_prizename",
},
{
title: "获奖信息",
value: "failedmodal_awardmsg",
},
{
title: "奖品图片",
value: "failedmodal_prizeimg",
},
{
title: "奖品备注",
value: "failedmodal_memo",
},
{
title: "底部",
value: "failedmodal_contentbottom",
},
{
title: "脚部",
value: "failedmodal_footer",
},
],
},
{
title: "地址弹窗",
value: "addressmodal_addressbox",
children: [
{
title: "外框",
value: "addressmodal_formbox",
children: [
{
title: "头部/标题",
value: "addressmodal_header",
},
{
title: "内容",
value: "addressmodal_main",
children: [
{
title: "玩家信息",
value: "addressmodal_player",
},
{
title: "子标题",
value: "addressmodal_subtitle",
},
{
title: "表单项",
value: "addressmodal_row",
children: [
{
title: "标签",
value: "addressmodal_label",
},
{
title: "输入框",
value: "addressmodal_input",
},
{
title: "文本框",
value: "addressmodal_textarea",
},
],
},
],
},
{
title: "脚部",
value: "addressmodal_footer",
},
],
},
],
},
{
title: "规则弹窗",
value: "rules_content",
children: [
{
title: "标题/头部",
value: "rules_header",
},
{
title: "内容",
value: "rules_list",
children: [
{
title: "规则项",
value: "rules_list_item",
},
],
},
{
title: "脚部",
value: "rules_footer",
},
],
},
{
title: "中奖记录",
value: "records_content",
children: [
{
title: "标题/头部",
value: "records_header",
},
{
title: "记录列表",
value: "records_list",
children: [
{
title: "记录项",
value: "records_list_item",
children: [
{
title: "奖品图片外框",
value: "records_list_item_prizeimg_wrap",
children: [
{
title: "奖品图片",
value: "records_list_item_prizeimg",
},
],
},
{
title: "内容",
value: "records_list_item_text",
children: [
{
title: "奖品名称",
value: "records_list_item_prizename",
},
{
title: "时间",
value: "records_list_item_wintime",
},
{
title: "填写地址",
value: "records_list_item_saveaddress",
},
{
title: "地址信息",
value: "records_list_item_address",
},
],
},
],
},
],
},
{
title: "脚部",
value: "records_footer",
},
],
},
],
},
]; | the_stack |
import { Component } from 'react';
import { connect } from 'react-redux';
import { Dispatch } from 'redux';
import { removeExpressionUI, updateExpressionUI } from '../../redux/Actions';
import { validateExpressionDomain } from '../../services/Libs';
import { ReduxAction } from '../../typings/ReduxConstants';
import ExpressionOptions from './ExpressionOptions';
import IconButton from './IconButton';
class EmptyState {
public expressionInput = '';
public editMode = false;
public id: string | undefined = '';
public invalid = '';
}
interface OwnProps {
expressions: ReadonlyArray<Expression>;
expressionColumnTitle: string;
storeId: string;
emptyElement: JSX.Element;
}
interface DispatchProps {
onRemoveExpression: (payload: Expression) => void;
onUpdateExpression: (payload: Expression) => void;
}
type ExpressionTableProps = DispatchProps & OwnProps;
class ExpressionTable extends Component<ExpressionTableProps, EmptyState> {
private editInput: HTMLInputElement | undefined | null;
constructor(props: ExpressionTableProps) {
super(props);
this.state = new EmptyState();
}
public startEditing(expression: Expression) {
this.setState({
editMode: true,
expressionInput: expression.expression,
id: expression.id,
invalid: '',
});
}
public componentDidUpdate() {
if (
this.editInput &&
this.state.editMode &&
document.activeElement !== document.getElementById('formText')
) {
this.editInput.focus();
}
}
public moveCaretToEnd(e: any) {
const tempValue = e.target.value;
e.target.value = '';
e.target.value = tempValue;
}
public clearEdit() {
if (this.editInput) {
if (this.editInput.parentElement) {
this.editInput.parentElement.classList.remove('was-validated');
}
this.editInput.setCustomValidity('');
this.editInput.checkValidity();
this.editInput = undefined;
}
this.setState(new EmptyState());
}
public commitEdit() {
if (!this.validateEdit()) return;
const original = (this.props.expressions || []).find(
(expression) => expression.id === this.state.id,
);
if (original) {
this.props.onUpdateExpression({
...original,
expression: this.state.expressionInput,
storeId: this.props.storeId,
});
}
this.setState(new EmptyState());
this.editInput = undefined;
}
public validateEdit(): boolean {
if (!this.state.editMode || !this.editInput || !this.state.id) return false;
const result = validateExpressionDomain(
this.state.expressionInput.trim(),
).trim();
if (result) {
// validation failed.
return this.setInvalid(result);
}
// Past this point, presume valid expression entry.
this.editInput.setCustomValidity('');
if (this.editInput.parentElement) {
this.editInput.parentElement.classList.remove('was-validated');
}
this.editInput.checkValidity();
return true;
}
public render() {
const {
onRemoveExpression,
onUpdateExpression,
expressionColumnTitle,
emptyElement,
} = this.props;
const { editMode, id, expressionInput, invalid } = this.state;
const expressions =
this.props.expressions === undefined ? [] : this.props.expressions;
if (expressions.length === 0) {
return emptyElement;
}
return (
<table className="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col" />
<th scope="col">{expressionColumnTitle}</th>
<th scope="col">{browser.i18n.getMessage('optionsText')}</th>
<th scope="col">{browser.i18n.getMessage('listTypeText')}</th>
</tr>
</thead>
<tbody className="expressionTable">
{expressions.map((expression) => (
<tr key={`${expression.expression}-${expression.listType}`}>
<td
style={{
textAlign: 'center',
}}
>
<IconButton
title={browser.i18n.getMessage('removeExpressionText')}
className="btn-outline-danger"
iconName="trash"
onClick={() => {
onRemoveExpression(expression);
}}
/>
</td>
{editMode && id === expression.id ? (
<td className="editableExpression">
<input
ref={(c) => {
this.editInput = c;
}}
className="form-control"
value={expressionInput}
onFocus={this.moveCaretToEnd}
onChange={(e) =>
this.setState({
expressionInput: e.target.value,
})
}
onKeyUp={(e) => {
if (e.key.toLowerCase().includes('enter')) {
this.commitEdit();
} else if (e.key.toLowerCase().includes('escape')) {
this.clearEdit();
}
}}
type="url"
autoFocus={true}
style={{
margin: 0,
}}
formNoValidate={true}
/>
<div className="invalid-feedback">{invalid}</div>
<IconButton
title={browser.i18n.getMessage('stopEditingText')}
className="btn-outline-danger"
iconName="ban"
styleReact={{
float: 'left',
marginTop: '8px',
width: '45%',
}}
onClick={() => {
this.clearEdit();
}}
/>
<IconButton
title={browser.i18n.getMessage('saveExpressionText')}
className="btn-outline-success"
iconName="save"
styleReact={{
float: 'right',
marginTop: '8px',
width: '45%',
}}
onClick={() => {
this.commitEdit();
}}
/>
</td>
) : (
<td>
<textarea
className="form-control form-control-plaintext"
readOnly={true}
rows={1}
style={{
margin: 0,
overflowX: 'scroll',
paddingLeft: '5px',
paddingRight: '5px',
resize: 'none',
whiteSpace: 'nowrap',
}}
>
{expression.expression}
</textarea>
<IconButton
title={browser.i18n.getMessage('editExpressionText')}
iconName="pen"
className="btn-outline-info showOnRowHover"
styleReact={{
marginTop: '5px',
width: '100%',
}}
onClick={() => {
this.startEditing(expression);
}}
/>
</td>
)}
<td>
<div
style={{
verticalAlign: 'middle',
}}
>
<ExpressionOptions expression={expression} />
</div>
</td>
<td>
<div
style={{
display: 'block',
verticalAlign: 'middle',
}}
>
{`${
expression.listType === 'WHITE'
? browser.i18n.getMessage('whiteListWordText')
: browser.i18n.getMessage('greyListWordText')
}`}
</div>
<IconButton
title={`${
expression.listType === 'WHITE'
? browser.i18n.getMessage('toggleToGreyListWordText')
: browser.i18n.getMessage('toggleToWhiteListWordText')
}`}
iconName="exchange-alt"
className="btn-outline-dark showOnRowHover"
styleReact={{
marginTop: '5px',
width: '100%',
}}
onClick={() =>
onUpdateExpression({
...expression,
listType:
expression.listType === ListType.GREY
? ListType.WHITE
: ListType.GREY,
})
}
/>
</td>
</tr>
))}
</tbody>
</table>
);
}
private setInvalid(s: string): boolean {
if (!this.editInput) return false;
this.setState({
invalid: s,
});
this.editInput.setCustomValidity(s);
if (this.editInput.parentElement) {
this.editInput.parentElement.classList.add('was-validated');
}
this.editInput.checkValidity();
// should always return false since we set error above.
return false;
}
}
const mapDispatchToProps = (dispatch: Dispatch<ReduxAction>) => ({
onRemoveExpression(payload: Expression) {
dispatch(removeExpressionUI(payload));
},
onUpdateExpression(payload: Expression) {
dispatch(updateExpressionUI(payload));
},
});
export default connect(null, mapDispatchToProps)(ExpressionTable); | the_stack |
import * as React from "react";
import {
Row,
Col,
Icon,
Card,
Tabs,
Table,
Radio,
DatePicker,
Tooltip,
Menu,
Dropdown
} from "antd";
import { observer, inject } from "mobx-react";
import numeral from "numeral";
import {
ChartCard,
yuan,
MiniArea,
MiniBar,
MiniProgress,
Field,
Bar,
Pie,
TimelineChart
} from "../../components/Charts";
import Trend from "../../components/Trend";
import NumberInfo from "../../components/NumberInfo";
import { getTimeDistance } from "../../utils/utils";
import "./Analysis.less";
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const rankingListData = [];
for (let i = 0; i < 7; i += 1) {
rankingListData.push({
title: `工专路 ${i} 号店`,
total: 323234
});
}
const Yuan = ({ children }) => (
<span dangerouslySetInnerHTML={{ __html: yuan(children) }} />
);
interface IAnalysisColumns {
title: string;
dataIndex: string;
key: string;
render?: (text, record) => JSX.Element;
sorter?: (a, b) => number;
align?: "center" | "left" | "right";
className?: string;
}
@inject((store: { Analysis }) => {
return {
chart: store.Analysis.chart,
getChartsData: store.Analysis.getChartsData,
clearChartsData: store.Analysis.clearChartsData
};
})
@observer
class DashboardAnalysis extends React.Component<
{
chart;
loading: boolean;
getChartsData: () => void;
clearChartsData: () => void;
},
{ rangePickerValue; salesType; currentTabKey }
> {
constructor(props) {
super(props);
this.state = {
salesType: "all",
currentTabKey: "",
rangePickerValue: getTimeDistance("year")
};
}
public componentDidMount() {
this.props.getChartsData();
}
public componentWillUnmount() {
this.props.clearChartsData();
}
private handleChangeSalesType = e => {
this.setState({
salesType: e.target.value
});
};
private handleTabChange = key => {
this.setState({
currentTabKey: key
});
};
private handleRangePickerChange = rangePickerValue => {
this.setState({
rangePickerValue
});
this.props.getChartsData();
};
private selectDate = type => {
this.setState({
rangePickerValue: getTimeDistance(type)
});
this.props.getChartsData();
};
private isActive(type) {
const { rangePickerValue } = this.state;
const value = getTimeDistance(type);
if (!rangePickerValue[0] || !rangePickerValue[1]) {
return;
}
if (
rangePickerValue[0].isSame(value[0], "day") &&
rangePickerValue[1].isSame(value[1], "day")
) {
return "currentDate";
}
}
public render() {
const { rangePickerValue, salesType, currentTabKey } = this.state;
const { chart, loading } = this.props;
const {
visitData,
visitData2,
salesData,
searchData,
offlineData,
// offlineChartData,
salesTypeData,
salesTypeDataOnline,
salesTypeDataOffline
} = chart;
const salesPieData =
salesType === "all"
? salesTypeData
: salesType === "online"
? salesTypeDataOnline
: salesTypeDataOffline;
const menu = (
<Menu>
<Menu.Item>操作一</Menu.Item>
<Menu.Item>操作二</Menu.Item>
</Menu>
);
const iconGroup = (
<span className={"iconGroup"}>
<Dropdown overlay={menu} placement="bottomRight">
<Icon type="ellipsis" />
</Dropdown>
</span>
);
const salesExtra = (
<div className={"salesExtraWrap"}>
<div className={"salesExtra"}>
<a
className={this.isActive("today")}
onClick={() => this.selectDate("today")}
>
今日
</a>
<a
className={this.isActive("week")}
onClick={() => this.selectDate("week")}
>
本周
</a>
<a
className={this.isActive("month")}
onClick={() => this.selectDate("month")}
>
本月
</a>
<a
className={this.isActive("year")}
onClick={() => this.selectDate("year")}
>
全年
</a>
</div>
<RangePicker
value={rangePickerValue}
onChange={this.handleRangePickerChange}
style={{ width: 256 }}
/>
</div>
);
const columns: IAnalysisColumns[] = [
{
title: "排名",
dataIndex: "index",
key: "index"
},
{
title: "搜索关键词",
dataIndex: "keyword",
key: "keyword",
render: text => <a href="/">{text}</a>
},
{
title: "用户数",
dataIndex: "count",
key: "count",
sorter: (a, b) => a.count - b.count,
className: "alignRight"
},
{
title: "周涨幅",
dataIndex: "range",
key: "range",
sorter: (a, b) => a.range - b.range,
render: (text, record) => (
<Trend flag={record.status === 1 ? "down" : "up"}>
<span style={{ marginRight: 4 }}>{text}%</span>
</Trend>
),
align: "right"
}
];
// const activeKey = currentTabKey || (offlineData && offlineData[0] && offlineData[0].name);
// const CustomTab = ({ data, currentTabKey: currentKey }) => (
// <Row gutter={8} style={{ width: 138, margin: '8px 0' }}>
// <Col span={12}>
// <NumberInfo
// title={data.name}
// subTitle="转化率"
// gap={2}
// total={`${data.cvr * 100}%`}
// theme={currentKey !== data.name && 'light'}
// />
// </Col>
// <Col span={12} style={{ paddingTop: 36 }}>
// <Pie
// animate={false}
// color={currentKey !== data.name && '#BDE4FF'}
// inner={0.55}
// tooltip={false}
// margin={[0, 0, 0, 0]}
// percent={`${data.cvr * 100}`}
// height={64}
// />
// </Col>
// </Row>
// );
const topColResponsiveProps = {
xs: 24,
sm: 12,
md: 12,
lg: 12,
xl: 6,
style: { marginBottom: 24 }
};
return (
<React.Fragment>
<Row gutter={24}>
<Col {...topColResponsiveProps}>
<ChartCard
bordered={false}
title="总销售额"
action={
<Tooltip title="指标说明">
<Icon type="info-circle-o" />
</Tooltip>
}
total={() => <Yuan>126560</Yuan>}
footer={
<Field
label="日均销售额"
value={`¥${numeral(12423).format("0,0")}`}
/>
}
contentHeight={46}
>
<Trend flag="up" style={{ marginRight: 16 }}>
周同比<span className={"trendText"}>12%</span>
</Trend>
<Trend flag="down">
日环比<span className={"trendText"}>11%</span>
</Trend>
</ChartCard>
</Col>
<Col {...topColResponsiveProps}>
<ChartCard
bordered={false}
title="访问量"
action={
<Tooltip title="指标说明">
<Icon type="info-circle-o" />
</Tooltip>
}
total={numeral(8846).format("0,0")}
footer={
<Field
label="日访问量"
value={numeral(1234).format("0,0")}
/>
}
contentHeight={46}
>
<MiniArea color="#975FE4" data={visitData || []} />
</ChartCard>
</Col>
<Col {...topColResponsiveProps}>
<ChartCard
bordered={false}
title="支付笔数"
action={
<Tooltip title="指标说明">
<Icon type="info-circle-o" />
</Tooltip>
}
total={numeral(6560).format("0,0")}
footer={<Field label="转化率" value="60%" />}
contentHeight={46}
>
<MiniBar data={visitData} />
</ChartCard>
</Col>
<Col {...topColResponsiveProps}>
<ChartCard
bordered={false}
title="运营活动效果"
action={
<Tooltip title="指标说明">
<Icon type="info-circle-o" />
</Tooltip>
}
total="78%"
footer={
<div
style={{
whiteSpace: "nowrap",
overflow: "hidden"
}}
>
<Trend flag="up" style={{ marginRight: 3 }}>
周同比
<span className={"trendText"}>12%</span>
</Trend>
<Trend flag="down">
日环比
<span className={"trendText"}>11%</span>
</Trend>
</div>
}
contentHeight={46}
>
<MiniProgress
percent={78}
strokeWidth={8}
target={80}
color="#13C2C2"
/>
</ChartCard>
</Col>
</Row>
<Card
loading={loading}
bordered={false}
bodyStyle={{ padding: 0 }}
>
<div className={"salesCard"}>
<Tabs
tabBarExtraContent={salesExtra}
size="large"
tabBarStyle={{ marginBottom: 24 }}
>
<TabPane tab="销售额" key="sales">
<Row>
<Col
xl={16}
lg={12}
md={12}
sm={24}
xs={24}
>
<div className={"salesBar"}>
<Bar
height={295}
title="销售额趋势"
data={salesData}
/>
</div>
</Col>
<Col xl={8} lg={12} md={12} sm={24} xs={24}>
<div className={"salesRank"}>
<h4 className={"rankingTitle"}>
门店销售额排名
</h4>
<ul className={"rankingList"}>
{rankingListData.map(
(item, i) => (
<li key={item.title}>
<span
className={
i < 3
? "active"
: ""
}
>
{i + 1}
</span>
<span>
{item.title}
</span>
<span>
{numeral(
item.total
).format("0,0")}
</span>
</li>
)
)}
</ul>
</div>
</Col>
</Row>
</TabPane>
<TabPane tab="访问量" key="views">
<Row>
<Col
xl={16}
lg={12}
md={12}
sm={24}
xs={24}
>
<div className={"salesBar"}>
<Bar
height={292}
title="访问量趋势"
data={salesData}
/>
</div>
</Col>
<Col xl={8} lg={12} md={12} sm={24} xs={24}>
<div className={"salesRank"}>
<h4 className={"rankingTitle"}>
门店访问量排名
</h4>
<ul className={"rankingList"}>
{rankingListData.map(
(item, i) => (
<li key={item.title}>
<span
className={
i < 3
? "active"
: ""
}
>
{i + 1}
</span>
<span>
{item.title}
</span>
<span>
{numeral(
item.total
).format("0,0")}
</span>
</li>
)
)}
</ul>
</div>
</Col>
</Row>
</TabPane>
</Tabs>
</div>
</Card>
<Row gutter={24}>
<Col xl={12} lg={24} md={24} sm={24} xs={24}>
<Card
loading={loading}
bordered={false}
title="线上热门搜索"
extra={iconGroup}
style={{ marginTop: 24 }}
>
<Row gutter={68}>
<Col
sm={12}
xs={24}
style={{ marginBottom: 24 }}
>
<NumberInfo
subTitle={
<span>
搜索用户数
<Tooltip title="指标文案">
<Icon
style={{
marginLeft: 8
}}
type="info-circle-o"
/>
</Tooltip>
</span>
}
gap={8}
total={numeral(12321).format("0,0")}
status="up"
subTotal={17.1}
/>
<MiniArea
line={true}
height={45}
data={visitData2}
/>
</Col>
<Col
sm={12}
xs={24}
style={{ marginBottom: 24 }}
>
<NumberInfo
subTitle="人均搜索次数"
total={2.7}
status="down"
subTotal={26.2}
gap={8}
/>
<MiniArea
line={true}
height={45}
data={visitData2}
/>
</Col>
</Row>
<Table
rowKey={record => record.index}
size="small"
columns={columns}
dataSource={searchData}
pagination={{
style: { marginBottom: 0 },
pageSize: 5
}}
/>
</Card>
</Col>
<Col xl={12} lg={24} md={24} sm={24} xs={24}>
<Card
loading={loading}
className={"salesCard"}
bordered={false}
title="销售额类别占比"
bodyStyle={{ padding: 24 }}
extra={
<div className={"salesCardExtra"}>
{iconGroup}
<div className={"salesTypeRadio"}>
<Radio.Group
value={salesType}
onChange={
this.handleChangeSalesType
}
>
<Radio.Button value="all">
全部渠道
</Radio.Button>
<Radio.Button value="online">
线上
</Radio.Button>
<Radio.Button value="offline">
门店
</Radio.Button>
</Radio.Group>
</div>
</div>
}
style={{ marginTop: 24, minHeight: 509 }}
>
<h4 style={{ marginTop: 8, marginBottom: 32 }}>
销售额
</h4>
<Pie
hasLegend={true}
subTitle="销售额"
total={() => (
<Yuan>
{salesPieData &&
salesPieData.reduce(
(pre, now) => now.y + pre,
0
)}
</Yuan>
)}
data={salesPieData || []}
valueFormat={value => <Yuan>{value}</Yuan>}
height={248}
lineWidth={4}
/>
</Card>
</Col>
</Row>
{/* <Card
loading={loading}
className={'offlineCard'}
bordered={false}
bodyStyle={{ padding: '0 0 32px 0' }}
style={{ marginTop: 32 }}
>
<Tabs activeKey={activeKey} onChange={this.handleTabChange}>
{offlineData && offlineData.map(shop => (
<TabPane tab={<CustomTab data={shop} currentTabKey={activeKey} />} key={shop.name}>
<div style={{ padding: '0 24px' }}>
{
offlineChartData ?
<TimelineChart
height={400}
data={offlineChartData}
titleMap={{ y1: '客流量', y2: '支付笔数' }}
/> : ''
}
</div>
</TabPane>
))}
</Tabs>
</Card> */}
</React.Fragment>
);
}
}
export default DashboardAnalysis; | the_stack |
import { expect } from "chai";
import { ReactWrapper, shallow, ShallowWrapper } from "enzyme";
import * as React from "react";
import * as sinon from "sinon";
import { ToolbarItemContext } from "@itwin/components-react";
import { WithOnOutsideClickProps } from "@itwin/core-react";
import { Group, Item } from "@itwin/appui-layout-react";
import { IModelApp, NoRenderApp } from "@itwin/core-frontend";
import {
ExpandableSection, FrameworkVersion, ListItem, ListItemType, ListPicker, ListPickerBase, ListPickerItem, ListPickerPropsExtended, UiFramework,
} from "../../appui-react";
import TestUtils, { mount } from "../TestUtils";
import { Provider } from "react-redux";
const title = "Test";
const listItems = new Array<ListItem>();
const setEnabled = sinon.spy();
describe("ListPicker", () => {
before(async () => {
await TestUtils.initializeUiFramework();
await NoRenderApp.startup();
const listItem: ListItem = {
enabled: true,
type: ListItemType.Item,
name: "123456789012345678901234567890",
};
listItems.push(listItem);
const separatorItem: ListItem = {
enabled: false,
type: ListItemType.Separator,
};
listItems.push(separatorItem);
const containerItem: ListItem = {
enabled: true,
type: ListItemType.Container,
children: [],
};
containerItem.children!.push(listItem);
listItems.push(containerItem);
const emptyContainerItem: ListItem = {
enabled: true,
type: ListItemType.Container,
children: [],
};
listItems.push(emptyContainerItem);
});
after(async () => {
TestUtils.terminateUiFramework();
await IModelApp.shutdown();
});
describe("v2 rendering", () => {
before(async () => {
UiFramework.setUiVersion("2");
await TestUtils.flushAsyncOperations();
});
it("should render correctly", () => {
shallow(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ToolbarItemContext.Provider
value={{
hasOverflow: false,
useHeight: false,
onResize: () => { },
}}
>
<ListPicker
title={title}
items={listItems}
setEnabled={setEnabled}
/>
</ToolbarItemContext.Provider>
</FrameworkVersion>
</Provider>
).should.matchSnapshot();
});
it("v2 should mount & unmount correctly", () => {
const enableAllFunc = () => { };
const disableAllFunc = () => { };
const invertFunc = () => { };
const component = mount(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ToolbarItemContext.Provider
value={{
hasOverflow: false,
useHeight: false,
onResize: () => { },
}}
>
<ListPicker
title={title}
items={listItems}
setEnabled={setEnabled}
enableAllFunc={enableAllFunc}
disableAllFunc={disableAllFunc}
invertFunc={invertFunc}
/>
</ToolbarItemContext.Provider>
</FrameworkVersion>
</Provider>
);
component.unmount();
});
});
describe("v1 rendering", () => {
before(async () => {
UiFramework.setUiVersion("1");
await TestUtils.flushAsyncOperations();
});
after(async () => {
// restore to default "2" setting
UiFramework.setUiVersion("2");
await TestUtils.flushAsyncOperations();
});
it("should render correctly", () => {
shallow(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ListPicker
title={title}
items={listItems}
setEnabled={setEnabled}
/>
</FrameworkVersion>
</Provider>
).should.matchSnapshot();
});
it("should mount & unmount correctly", () => {
const enableAllFunc = () => { };
const disableAllFunc = () => { };
const invertFunc = () => { };
const component = mount(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ListPicker
title={title}
items={listItems}
setEnabled={setEnabled}
enableAllFunc={enableAllFunc}
disableAllFunc={disableAllFunc}
invertFunc={invertFunc}
/>
</FrameworkVersion>
</Provider>
);
component.unmount();
});
});
describe("isSpecialItem", () => {
let listPickerWrapper: ShallowWrapper<any>;
let listPickerInstance: ListPicker;
beforeEach(() => {
listPickerWrapper = shallow(
<ListPicker
title={title}
items={listItems}
setEnabled={setEnabled}
/>,
);
listPickerInstance = listPickerWrapper.instance() as ListPicker;
});
it("should return true if item key is special", () => {
expect(
listPickerInstance.isSpecialItem({
key: ListPicker.Key_All,
enabled: true,
} as ListItem),
).to.be.true;
expect(
listPickerInstance.isSpecialItem({
key: ListPicker.Key_Invert,
enabled: true,
} as ListItem),
).to.be.true;
expect(
listPickerInstance.isSpecialItem({
key: ListPicker.Key_None,
enabled: true,
} as ListItem),
).to.be.true;
expect(
listPickerInstance.isSpecialItem({
key: ListPicker.Key_Separator,
enabled: true,
} as ListItem),
).to.be.true;
});
it("should return true if item type is special", () => {
expect(
listPickerInstance.isSpecialItem({
key: "",
type: ListItemType.Container,
enabled: true,
} as ListItem),
).to.be.true;
});
it("should return false if item type is not special", () => {
expect(
listPickerInstance.isSpecialItem({
key: "",
type: ListItemType.Item,
enabled: true,
} as ListItem),
).to.be.false;
});
});
describe("ListPickerItem", () => {
it("should render correctly", () => {
shallow(
<ListPickerItem
key="key"
/>,
).should.matchSnapshot();
});
it("should unmount correctly", () => {
const unknownItem: ListItem = {
key: "unknown-item",
name: "unknown",
enabled: false,
type: ListItemType.Item,
};
const singleItemList = new Array<ListItem>();
singleItemList.push(unknownItem);
const component = mount(
<ListPickerItem
key="key"
isActive={true}
isFocused={true}
/>,
);
component.unmount();
});
});
describe("ExpandableSection", () => {
it("should render correctly", () => {
shallow(<ExpandableSection />);
});
it("should unmount correctly", () => {
const component = mount(
<ExpandableSection />,
);
component.unmount();
});
it("should handle onClick", () => {
const component = mount(
<ExpandableSection />,
);
component.find("div.ListPickerInnerContainer-header").simulate("click");
component.update();
component.find("div.ListPickerInnerContainer-header-expanded");
expect(component.length).to.eq(1);
});
});
describe("ListPickerBase", () => {
let listPickerBaseWrapper: ShallowWrapper<any>;
let listPickerBaseInstance: ListPickerBase;
beforeEach(() => {
listPickerBaseWrapper = shallow(
<ListPickerBase
title={title}
items={listItems}
setEnabled={setEnabled}
/>);
listPickerBaseInstance = listPickerBaseWrapper.instance() as ListPickerBase;
});
it("should render correctly", () => {
shallow(
<ListPickerBase
title={title}
items={listItems}
setEnabled={setEnabled}
/>,
).dive().should.matchSnapshot();
});
it("should minimize", () => {
listPickerBaseInstance.minimize();
expect(listPickerBaseWrapper.state("expanded")).to.be.false;
});
it("should return true if expanded", () => {
listPickerBaseWrapper.setState({ expanded: true });
listPickerBaseInstance.forceUpdate();
expect(listPickerBaseInstance.isExpanded()).to.be.true;
});
it("should return false if not expanded", () => {
listPickerBaseWrapper.setState({ expanded: false });
listPickerBaseInstance.forceUpdate();
expect(listPickerBaseInstance.isExpanded()).to.be.false;
});
it("should return expanded content", () => {
listPickerBaseInstance.getExpandedContent();
});
it("simulate expanding", () => {
const spyOnExpanded = sinon.spy();
const component = mount(
<ListPickerBase
title={title}
items={listItems}
setEnabled={setEnabled}
onExpanded={spyOnExpanded}
/>,
);
const item = component.find(Item); // eslint-disable-line deprecation/deprecation
expect(item).not.to.be.undefined;
item.prop("onClick")!();
component.update();
expect(spyOnExpanded.calledOnce).to.be.true;
});
it("should unmount correctly", () => {
const component = mount(
<ListPickerBase
title={title}
items={listItems}
setEnabled={setEnabled}
/>,
);
component.unmount();
});
it("should close on outside click", () => {
const spy = sinon.spy();
const component = mount<ListPickerBase>(
<ListPickerBase
title={title}
items={listItems}
setEnabled={setEnabled}
onExpanded={spy}
/>,
);
component.setState({ expanded: true });
document.dispatchEvent(new MouseEvent("pointerdown"));
document.dispatchEvent(new MouseEvent("pointerup"));
component.state().expanded.should.false;
spy.calledOnceWithExactly(false);
});
});
describe("setEnabled V1 only", () => {
let listPickerWrapper: ReactWrapper<ListPickerPropsExtended>;
const localSetEnabled = sinon.fake();
const localListItems = new Array<ListItem>();
const allSpyMethod = sinon.fake();
const noneSpyMethod = sinon.fake();
const invertSpyMethod = sinon.fake();
before(async () => {
UiFramework.setUiVersion("1");
await TestUtils.flushAsyncOperations();
const listItem: ListItem = {
enabled: true,
type: ListItemType.Item,
name: "not-special",
};
localListItems.push(listItem);
const invalidListItem: ListItem = {
enabled: true,
type: 100,
name: "invalid-item",
};
localListItems.push(invalidListItem);
});
after(async () => {
// restore to default "2" setting
UiFramework.setUiVersion("2");
await TestUtils.flushAsyncOperations();
});
beforeEach(() => {
listPickerWrapper = mount(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ListPicker
title={title}
items={localListItems}
setEnabled={localSetEnabled}
enableAllFunc={allSpyMethod}
disableAllFunc={noneSpyMethod}
invertFunc={invertSpyMethod}
iconSpec={<svg />}
/>
</FrameworkVersion>
</Provider>
);
const item = listPickerWrapper.find(Item); // eslint-disable-line deprecation/deprecation
expect(item).not.to.be.undefined;
item.prop("onClick")!();
listPickerWrapper.update();
});
it("should call enableAllFunc handler when All clicked", () => {
const listPickerItem = listPickerWrapper.find({ label: "pickerButtons.all" });
listPickerItem.should.exist;
listPickerItem.find(".ListPicker-item").simulate("click");
allSpyMethod.calledOnce.should.true;
});
it("should call disableAllFunc handler when All clicked", () => {
const listPickerItem = listPickerWrapper.find({ label: "pickerButtons.none" });
listPickerItem.should.exist;
listPickerItem.find(".ListPicker-item").simulate("click");
noneSpyMethod.calledOnce.should.true;
});
it("should call invertFunc handler when All clicked", () => {
const listPickerItem = listPickerWrapper.find({ label: "pickerButtons.invert" });
listPickerItem.should.exist;
listPickerItem.find(".ListPicker-item").simulate("click");
invertSpyMethod.calledOnce.should.true;
});
it("should call setEnabled handler when item clicked that isn't special", () => {
const listPickerItem = listPickerWrapper.find({ label: "not-special" });
listPickerItem.should.exist;
listPickerItem.find(".ListPicker-item").simulate("click");
localSetEnabled.calledOnce.should.true;
});
});
describe("Multiple ListPickers v1 only", () => {
const localListItems = new Array<ListItem>();
const listItem: ListItem = {
enabled: true,
type: ListItemType.Item,
name: "123456789012345678901234567890",
};
before(async () => {
UiFramework.setUiVersion("1");
await TestUtils.flushAsyncOperations();
localListItems.push(listItem);
});
after(async () => {
// restore to default "2" setting
UiFramework.setUiVersion("2");
await TestUtils.flushAsyncOperations();
});
it("Close other ListPicker", () => {
const wrapper1 = mount(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ListPicker
title={title}
items={localListItems}
setEnabled={setEnabled}
/>
</FrameworkVersion>
</Provider>
);
const itemComponent1 = wrapper1.find(Item);
expect(itemComponent1).not.to.be.undefined;
itemComponent1.simulate("click");
wrapper1.update();
wrapper1.find(Group).should.exist; // eslint-disable-line deprecation/deprecation
const wrapper2 = mount(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ListPicker
title={title}
items={listItems}
setEnabled={setEnabled}
/>
</FrameworkVersion>
</Provider>
);
const itemComponent2 = wrapper2.find(Item);
expect(itemComponent2).not.to.be.undefined;
itemComponent2.simulate("click");
wrapper2.update();
wrapper2.find(Group).should.exist; // eslint-disable-line deprecation/deprecation
wrapper1.update();
wrapper1.find(Group).length.should.eq(0); // eslint-disable-line deprecation/deprecation
itemComponent2.simulate("click");
wrapper2.update();
wrapper2.find(Group).length.should.eq(0); // eslint-disable-line deprecation/deprecation
});
});
describe("onOutsideClick", () => {
before(async () => {
UiFramework.setUiVersion("1");
await TestUtils.flushAsyncOperations();
});
after(async () => {
// restore to default "2" setting
UiFramework.setUiVersion("2");
await TestUtils.flushAsyncOperations();
});
it("should minimize on outside click", () => {
const spy = sinon.spy();
const sut = mount(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ListPickerBase
title={title}
items={listItems}
setEnabled={setEnabled}
onExpanded={spy}
/>
</FrameworkVersion>
</Provider>
);
sut.find(ListPickerBase).setState({ expanded: true });
const containedGroup = sut.findWhere((w) => {
return w.name() === "WithOnOutsideClick";
}) as ReactWrapper<WithOnOutsideClickProps>;
const event = new MouseEvent("");
sinon.stub(event, "target").get(() => document.createElement("div"));
containedGroup.prop("onOutsideClick")!(event);
expect(spy.calledOnce).to.be.true;
});
});
it("should not minimize on outside click", () => {
const spy = sinon.spy();
const sut = mount(
<Provider store={TestUtils.store}>
<FrameworkVersion>
<ListPickerBase
title={title}
items={listItems}
setEnabled={setEnabled}
onExpanded={spy}
/>
</FrameworkVersion>
</Provider>
);
sut.find(ListPickerBase).setState({ expanded: true });
const containedGroup = sut.findWhere((w) => {
return w.name() === "WithOnOutsideClick";
}) as ReactWrapper<WithOnOutsideClickProps>;
const event = new MouseEvent("");
containedGroup.prop("onOutsideClick")!(event);
expect(spy.called).to.be.false;
});
}); | the_stack |
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { SearchService } from './search.service';
import { Router, UrlTree } from '@angular/router';
import { RequestService } from '../../data/request.service';
import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub';
import { RouterStub } from '../../../shared/testing/router.stub';
import { HALEndpointService } from '../hal-endpoint.service';
import { combineLatest as observableCombineLatest, Observable, of as observableOf } from 'rxjs';
import { PaginatedSearchOptions } from '../../../shared/search/paginated-search-options.model';
import { RemoteData } from '../../data/remote-data';
import { RequestEntry } from '../../data/request.reducer';
import { getMockRequestService } from '../../../shared/mocks/request.service.mock';
import { CommunityDataService } from '../../data/community-data.service';
import { ViewMode } from '../view-mode.model';
import { DSpaceObjectDataService } from '../../data/dspace-object-data.service';
import { map } from 'rxjs/operators';
import { RouteService } from '../../services/route.service';
import { routeServiceStub } from '../../../shared/testing/route-service.stub';
import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { SearchObjects } from '../../../shared/search/search-objects.model';
import { PaginationService } from '../../pagination/pagination.service';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../cache/models/sort-options.model';
import { FindListOptions } from '../../data/request.models';
import { SearchConfigurationService } from './search-configuration.service';
import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub';
@Component({ template: '' })
class DummyComponent {
}
describe('SearchService', () => {
describe('By default', () => {
let searchService: SearchService;
const router = new RouterStub();
const route = new ActivatedRouteStub();
const searchConfigService = {paginationID: 'page-id'};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
RouterTestingModule.withRoutes([
{ path: 'search', component: DummyComponent, pathMatch: 'full' },
])
],
declarations: [
DummyComponent
],
providers: [
{ provide: Router, useValue: router },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: RequestService, useValue: getMockRequestService() },
{ provide: RemoteDataBuildService, useValue: {} },
{ provide: HALEndpointService, useValue: {} },
{ provide: CommunityDataService, useValue: {} },
{ provide: DSpaceObjectDataService, useValue: {} },
{ provide: PaginationService, useValue: {} },
{ provide: SearchConfigurationService, useValue: searchConfigService },
SearchService
],
});
searchService = TestBed.inject(SearchService);
});
it('should return list view mode', () => {
searchService.getViewMode().subscribe((viewMode) => {
expect(viewMode).toBe(ViewMode.ListElement);
});
});
});
describe('', () => {
let searchService: SearchService;
const router = new RouterStub();
let routeService;
const halService = {
/* tslint:disable:no-empty */
getEndpoint: () => {
}
/* tslint:enable:no-empty */
};
const remoteDataBuildService = {
toRemoteDataObservable: (requestEntryObs: Observable<RequestEntry>, payloadObs: Observable<any>) => {
return observableCombineLatest([requestEntryObs, payloadObs]).pipe(
map(([req, pay]) => {
return { req, pay };
})
);
},
aggregate: (input: Observable<RemoteData<any>>[]): Observable<RemoteData<any[]>> => {
return createSuccessfulRemoteDataObject$([]);
},
buildFromHref: (href: string): Observable<RemoteData<any>> => {
return createSuccessfulRemoteDataObject$(Object.assign(new SearchObjects(), {
page: []
}));
}
};
const paginationService = new PaginationServiceStub();
const searchConfigService = {paginationID: 'page-id'};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
RouterTestingModule.withRoutes([
{ path: 'search', component: DummyComponent, pathMatch: 'full' },
])
],
declarations: [
DummyComponent
],
providers: [
{ provide: Router, useValue: router },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: RequestService, useValue: getMockRequestService() },
{ provide: RemoteDataBuildService, useValue: remoteDataBuildService },
{ provide: HALEndpointService, useValue: halService },
{ provide: CommunityDataService, useValue: {} },
{ provide: DSpaceObjectDataService, useValue: {} },
{ provide: PaginationService, useValue: paginationService },
{ provide: SearchConfigurationService, useValue: searchConfigService },
SearchService
],
});
searchService = TestBed.inject(SearchService);
routeService = TestBed.inject(RouteService);
const urlTree = Object.assign(new UrlTree(), { root: { children: { primary: 'search' } } });
router.parseUrl.and.returnValue(urlTree);
});
it('should call the navigate method on the Router with view mode list parameter as a parameter when setViewMode is called', () => {
searchService.setViewMode(ViewMode.ListElement);
expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith('page-id', ['/search'], {page: 1}, { view: ViewMode.ListElement }
);
});
it('should call the navigate method on the Router with view mode grid parameter as a parameter when setViewMode is called', () => {
searchService.setViewMode(ViewMode.GridElement);
expect(paginationService.updateRouteWithUrl).toHaveBeenCalledWith('page-id', ['/search'], {page: 1}, { view: ViewMode.GridElement }
);
});
it('should return ViewMode.List when the viewMode is set to ViewMode.List in the ActivatedRoute', () => {
let viewMode = ViewMode.GridElement;
spyOn(routeService, 'getQueryParamMap').and.returnValue(observableOf(new Map([
['view', ViewMode.ListElement],
])));
searchService.getViewMode().subscribe((mode) => viewMode = mode);
expect(viewMode).toEqual(ViewMode.ListElement);
});
it('should return ViewMode.Grid when the viewMode is set to ViewMode.Grid in the ActivatedRoute', () => {
let viewMode = ViewMode.ListElement;
spyOn(routeService, 'getQueryParamMap').and.returnValue(observableOf(new Map([
['view', ViewMode.GridElement],
])));
searchService.getViewMode().subscribe((mode) => viewMode = mode);
expect(viewMode).toEqual(ViewMode.GridElement);
});
describe('when search is called', () => {
const endPoint = 'http://endpoint.com/test/test';
const searchOptions = new PaginatedSearchOptions({});
beforeEach(() => {
spyOn((searchService as any).halService, 'getEndpoint').and.returnValue(observableOf(endPoint));
spyOn((searchService as any).rdb, 'buildFromHref').and.callThrough();
/* tslint:disable:no-empty */
searchService.search(searchOptions).subscribe((t) => {
}); // subscribe to make sure all methods are called
/* tslint:enable:no-empty */
});
it('should call getEndpoint on the halService', () => {
expect((searchService as any).halService.getEndpoint).toHaveBeenCalled();
});
it('should send out the request on the request service', () => {
expect((searchService as any).requestService.send).toHaveBeenCalled();
});
it('should call getByHref on the request service with the correct request url', () => {
expect((searchService as any).rdb.buildFromHref).toHaveBeenCalledWith(endPoint);
});
});
describe('when getConfig is called without a scope', () => {
const endPoint = 'http://endpoint.com/test/config';
beforeEach(() => {
spyOn((searchService as any).halService, 'getEndpoint').and.returnValue(observableOf(endPoint));
spyOn((searchService as any).rdb, 'buildFromHref').and.callThrough();
/* tslint:disable:no-empty */
searchService.getConfig(null).subscribe((t) => {
}); // subscribe to make sure all methods are called
/* tslint:enable:no-empty */
});
it('should call getEndpoint on the halService', () => {
expect((searchService as any).halService.getEndpoint).toHaveBeenCalled();
});
it('should send out the request on the request service', () => {
expect((searchService as any).requestService.send).toHaveBeenCalled();
});
it('should call send containing a request with the correct request url', () => {
expect((searchService as any).requestService.send).toHaveBeenCalledWith(jasmine.objectContaining({ href: endPoint }), true);
});
});
describe('when getConfig is called with a scope', () => {
const endPoint = 'http://endpoint.com/test/config';
const scope = 'test';
const requestUrl = endPoint + '?scope=' + scope;
beforeEach(() => {
spyOn((searchService as any).halService, 'getEndpoint').and.returnValue(observableOf(endPoint));
/* tslint:disable:no-empty */
searchService.getConfig(scope).subscribe((t) => {
}); // subscribe to make sure all methods are called
/* tslint:enable:no-empty */
});
it('should call getEndpoint on the halService', () => {
expect((searchService as any).halService.getEndpoint).toHaveBeenCalled();
});
it('should send out the request on the request service', () => {
expect((searchService as any).requestService.send).toHaveBeenCalled();
});
it('should call send containing a request with the correct request url', () => {
expect((searchService as any).requestService.send).toHaveBeenCalledWith(jasmine.objectContaining({ href: requestUrl }), true);
});
});
describe('when getSearchConfigurationFor is called without a scope', () => {
const endPoint = 'http://endpoint.com/test/config';
beforeEach(() => {
spyOn((searchService as any).halService, 'getEndpoint').and.returnValue(observableOf(endPoint));
spyOn((searchService as any).rdb, 'buildFromHref').and.callThrough();
/* tslint:disable:no-empty */
searchService.getSearchConfigurationFor(null).subscribe((t) => {
}); // subscribe to make sure all methods are called
/* tslint:enable:no-empty */
});
it('should call getEndpoint on the halService', () => {
expect((searchService as any).halService.getEndpoint).toHaveBeenCalled();
});
it('should send out the request on the request service', () => {
expect((searchService as any).requestService.send).toHaveBeenCalled();
});
it('should call send containing a request with the correct request url', () => {
expect((searchService as any).requestService.send).toHaveBeenCalledWith(jasmine.objectContaining({ href: endPoint }), true);
});
});
describe('when getSearchConfigurationFor is called with a scope', () => {
const endPoint = 'http://endpoint.com/test/config';
const scope = 'test';
const requestUrl = endPoint + '?scope=' + scope;
beforeEach(() => {
spyOn((searchService as any).halService, 'getEndpoint').and.returnValue(observableOf(endPoint));
/* tslint:disable:no-empty */
searchService.getSearchConfigurationFor(scope).subscribe((t) => {
}); // subscribe to make sure all methods are called
/* tslint:enable:no-empty */
});
it('should call getEndpoint on the halService', () => {
expect((searchService as any).halService.getEndpoint).toHaveBeenCalled();
});
it('should send out the request on the request service', () => {
expect((searchService as any).requestService.send).toHaveBeenCalled();
});
it('should call send containing a request with the correct request url', () => {
expect((searchService as any).requestService.send).toHaveBeenCalledWith(jasmine.objectContaining({ href: requestUrl }), true);
});
});
});
}); | the_stack |
import { Desc } from "./describe";
import CompositeUnsubscribe from "./compositeunsubscribe";
import { EventStream, newEventStream } from "./observable";
import UpdateBarrier from "./internal/updatebarrier";
import { fromObservable, isTrigger, Source } from "./internal/source";
import { endEvent, Event, Value } from "./event";
import { more, noMore, Reply } from "./reply";
import { all, map, toArray, toFunction, contains, any, indexOf, filter } from "./_";
import { assert } from "./internal/assert";
import never from "./never";
import propertyFromStreamSubscribe from "./internal/propertyfromstreamsubscribe"
import Observable, { ObservableConstructor } from "./observable";
import { Unsub } from "./types";
import { Property } from "./observable";
import { isObservable } from "./helpers";
export type ObservableOrSource<V> = Observable<V> | Source<any, V>
/**
* Join pattern consisting of a single EventStream and a mapping function.
*/
export type Pattern1<I1,O> = [ObservableOrSource<I1>, O | ((a: I1) => O)]
/**
* Join pattern consisting of a 2 Observables and a combinator function. At least one of the Observables must be an EventStream.
*/
export type Pattern2<I1,I2,O> = [ObservableOrSource<I1>, ObservableOrSource<I1>, O | ((a: I1, b: I2) => O)]
/**
* Join pattern consisting of a 3 Observables and a combinator function. At least one of the Observables must be an EventStream.
*/
export type Pattern3<I1,I2,I3,O> = [ObservableOrSource<I1>, ObservableOrSource<I1>, ObservableOrSource<I3>, O | ((a: I1, b: I2, c: I3) => O)]
/**
* Join pattern consisting of a 4 Observables and a combinator function. At least one of the Observables must be an EventStream.
*/
export type Pattern4<I1,I2,I3,I4,O> = [ObservableOrSource<I1>, ObservableOrSource<I1>, ObservableOrSource<I3>, ObservableOrSource<I4>, O | ((a: I1, b: I2, c: I3, d: I4) => O)]
/**
* Join pattern consisting of a 5 Observables and a combinator function. At least one of the Observables must be an EventStream.
*/
export type Pattern5<I1,I2,I3,I4,I5,O> = [ObservableOrSource<I1>, ObservableOrSource<I1>, ObservableOrSource<I3>, ObservableOrSource<I4>, ObservableOrSource<I5>, O | ((a: I1, b: I2, c: I3, d: I4, e: I5) => O)]
/**
* Join pattern consisting of a 6 Observables and a combinator function. At least one of the Observables must be an EventStream.
*/
export type Pattern6<I1,I2,I3,I4,I5,I6,O> = [ObservableOrSource<I1>, ObservableOrSource<I1>, ObservableOrSource<I3>, ObservableOrSource<I4>, ObservableOrSource<I5>, ObservableOrSource<I6>, O | ((a: I1, b: I2, c: I3, d: I4, e: I5, f: I6) => O)]
/** @hidden */
export type RawPattern = [AnyObservableOrSource[], AnyFunction]
/**
* Join pattern type, allowing up to 6 sources per pattern.
*/
export type Pattern<O> = Pattern1<any, O> | Pattern2<any, any, O> | Pattern3<any, any, any, O> |
Pattern4<any, any, any, any, O> | Pattern5<any, any, any, any, any, O> | Pattern6<any, any, any, any, any, any, O> |
RawPattern
/** @hidden */
export type AnySource = Source<any, any>
/** @hidden */
export type AnyFunction = Function
type AnyValue = Value<any>
/** @hidden */
export type AnyObservable = Observable<any>
/** @hidden */
export type AnyObservableOrSource = AnyObservable | AnySource
/**
The `when` method provides a generalization of the [`zip`](classes/observable.html#zip) function. While zip
synchronizes events from multiple streams pairwse, the join patterns used in `when` allow
the implementation of more advanced synchronization patterns.
Consider implementing a game with discrete time ticks. We want to
handle key-events synchronized on tick-events, with at most one key
event handled per tick. If there are no key events, we want to just
process a tick.
```js
Bacon.when(
[tick, keyEvent, function(_, k) { handleKeyEvent(k); return handleTick(); }],
[tick, handleTick])
```
Order is important here. If the [tick] patterns had been written
first, this would have been tried first, and preferred at each tick.
Join patterns are indeed a generalization of zip, and for EventStreams, zip is
equivalent to a single-rule join pattern. The following observables
have the same output, assuming that all sources are EventStreams.
```js
Bacon.zipWith(a,b,c, combine)
Bacon.when([a,b,c], combine)
```
Note that [`Bacon.when`](#bacon-when) does not trigger updates for events from Properties though;
if you use a Property in your pattern, its value will be just sampled when all the
other sources (EventStreams) have a value. This is useful when you need a value of a Property
in your calculations. If you want your pattern to fire for a Property too, you can
convert it into an EventStream using [`property.changes()`](#property-changes) or [`property.toEventStream()`](#property-toeventstream)
* @param {Pattern<O>} patterns Join patterns
* @typeparam O result type
*/
export function when<O>(...patterns: Pattern<O>[]): EventStream<O> {
return <any>when_(newEventStream, patterns)
}
/** @hidden */
export function whenP<O>(...patterns: Pattern<O>[]): Property<O> {
return <any>when_(propertyFromStreamSubscribe, patterns)
}
export default when;
/** @hidden */
export function when_<O>(ctor: ObservableConstructor, patterns: Pattern<O>[]): Observable<O> {
if (patterns.length === 0) { return never() }
var [sources, ixPats] = processRawPatterns(extractRawPatterns(patterns))
if (!sources.length) {
return never()
}
var needsBarrier: boolean = (any(sources, (s: AnySource) => s.flatten)) && containsDuplicateDeps(map(((s: AnySource) => s.obs), sources))
var desc = new Desc("Bacon", "when", Array.prototype.slice.call(patterns))
var resultStream = ctor(desc, function(sink) {
var triggers: Trigger[] = [];
var ends = false;
function match(p: IndexPattern) {
for (var i = 0; i < p.ixs.length; i++) {
let ix = p.ixs[i];
if (!sources[ix.index].hasAtLeast(ix.count)) {
return false;
}
}
return true;
}
function cannotMatch(p: IndexPattern): boolean {
for (var i = 0; i < p.ixs.length; i++) {
let ix = p.ixs[i];
if (!sources[ix.index].mayHave(ix.count)) {
return true;
}
}
return false
}
function nonFlattened(trigger: Trigger): boolean { return !trigger.source.flatten; }
function part(source: AnySource): (u: Unsub) => Unsub { return function(unsubAll): Unsub {
function flushLater() {
return UpdateBarrier.whenDoneWith(resultStream, flush);
}
function flushWhileTriggers(): Reply {
var trigger: Trigger | undefined
if ((trigger = triggers.pop()) !== undefined) {
var reply = more;
for (var i = 0, p; i < ixPats.length; i++) {
p = ixPats[i];
if (match(p)) {
const values: any[] = [];
for (var j = 0; j < p.ixs.length; j++) {
let event = sources[p.ixs[j].index].consume()
if (!event) throw new Error("Event was undefined")
values.push(event.value);
}
//console.log("flushing values", values)
let applied = p.f.apply(null, values);
//console.log('sinking', applied)
reply = sink((trigger).e.apply(applied));
if (triggers.length) {
triggers = filter(nonFlattened, triggers);
}
if (reply === noMore) {
return reply;
} else {
return flushWhileTriggers();
}
}
}
}
return more;
}
function flush(): void {
//console.log "flushing", _.toString(resultStream)
var reply: Reply = flushWhileTriggers();
if (ends) {
//console.log "ends detected"
if (all(sources, cannotSync) || all(ixPats, cannotMatch)) {
//console.log "actually ending"
reply = noMore;
sink(endEvent());
}
}
if (reply === noMore) { unsubAll(); }
}
return source.subscribe(function(e: Event<any>) {
var reply = more
if (e.isEnd) {
//console.log "got end"
ends = true;
source.markEnded();
flushLater();
} else if (e.isError) {
reply = sink(e);
} else {
let valueEvent = <AnyValue>e
//console.log "got value", e.value
source.push(valueEvent);
if (source.sync) {
//console.log "queuing", e.toString(), toString(resultStream)
triggers.push({source: source, e: valueEvent});
if (needsBarrier || UpdateBarrier.hasWaiters()) { flushLater(); } else { flush(); }
}
}
if (reply === noMore) { unsubAll(); }
return reply;
});
}}
return new CompositeUnsubscribe(map(part, sources)).unsubscribe;
});
return resultStream;
}
interface IndexPattern {
ixs: { index: number, count: number }[]
f: AnyFunction
}
function processRawPatterns(rawPatterns: RawPattern[]): [AnySource[], IndexPattern[]] {
var sources: AnyObservableOrSource[] = [];
var pats: IndexPattern[] = [];
for (let i = 0; i < rawPatterns.length; i++) {
let [patSources, f] = rawPatterns[i]
var pat: IndexPattern = {f, ixs: []};
var triggerFound = false;
for (var j = 0, s; j < patSources.length; j++) {
s = patSources[j];
var index = indexOf(sources, s);
if (!triggerFound) {
triggerFound = isTrigger(s);
}
if (index < 0) {
sources.push(s);
index = sources.length - 1;
}
for (var k = 0; k < pat.ixs.length; k++) {
let ix = pat.ixs[k];
if (ix.index === index) {
ix.count++;
}
}
pat.ixs.push({index: index, count: 1});
}
if (patSources.length > 0 && !triggerFound) {
throw new Error("At least one EventStream required, none found in " + patSources)
}
if (patSources.length > 0) {
pats.push(pat);
}
}
return [map(fromObservable as any /* sorry */, sources), pats]
}
function extractLegacyPatterns(sourceArgs: any[]): RawPattern[] {
var i = 0
var len = sourceArgs.length;
var rawPatterns: RawPattern[] = []
while (i < len) {
let patSources: AnyObservableOrSource[] = toArray(sourceArgs[i++]);
let f: AnyFunction = toFunction(sourceArgs[i++]);
rawPatterns.push([patSources, f])
}
var usage = "when: expecting arguments in the form (Observable+,function)+";
assert(usage, (len % 2 === 0));
return rawPatterns
}
function isTypedOrRawPattern(pattern: Pattern<any>) {
return (pattern instanceof Array) && (!isObservable(pattern[pattern.length - 1]))
}
function isRawPattern(pattern: Pattern<any>): pattern is RawPattern {
return pattern[0] instanceof Array
}
/** @hidden */
export function extractRawPatterns<O>(patterns: Pattern<O>[]): RawPattern[] {
let rawPatterns: RawPattern[] = []
for (let i = 0; i < patterns.length; i++) {
let pattern = patterns[i]
if (!isTypedOrRawPattern(pattern)) {
// Fallback to legacy patterns
return extractLegacyPatterns(patterns)
}
if (isRawPattern(pattern)) {
rawPatterns.push([pattern[0], toFunction(pattern[1])])
} else { // typed pattern, then
let sources: AnySource[] = <any>pattern.slice(0, pattern.length - 1)
let f: AnyFunction = <any>toFunction(<any>pattern[pattern.length - 1])
rawPatterns.push([sources, f])
}
}
return rawPatterns
}
interface Trigger {
e: Value<any>
source: AnySource
}
function containsDuplicateDeps(observables: AnyObservable[], state: AnyObservable[] = []) {
function checkObservable(obs: AnyObservable): boolean {
if (contains(state, obs)) {
return true;
} else {
var deps = obs.internalDeps();
if (deps.length) {
state.push(obs);
return any(deps, checkObservable);
} else {
state.push(obs);
return false;
}
}
}
return any(observables, checkObservable);
}
function cannotSync(source: AnySource) {
return !source.sync || source.ended;
} | the_stack |
export enum NodeTypes {
TEXT = 'TEXT', // TEXT = (TEXT\s+ | TEXT\s+)*
NAMESPACE = 'NAMESPACE', // namespace splited by ., to support @use which is namespace based
VARIABLE = 'VARIABLE', // VARIABLE.value === variable's name , expression deleted after evaluation
PUNC = 'PUNC', // punctuation: parens((|)), comma(,), semicolon(;) etc.
OPERATOR = 'OPERATOR', // arithmeticOperator | comparisonOperator
VAR_KEY = 'VAR_KEY', // to solve "TEXT-#{VARIABLE}" , expression replaced after evaluation
PLACEHOLDER = 'PLACEHOLDER', // %TEXT
KEYWORD = 'KEYWORD',
IDENTIFIER = 'IDENTIFIER',
EMPTY = 'EMPTY',
UNKNOWN = 'UNKNOWN',
SELECTOR = 'SELECTOR',
/**
* https://sass-lang.com/documentation/values/lists
* any expressions separated with spaces or commas count as a list;
* iterable eg: $each value in list
*/
LIST = 'LIST',
BINARY = 'BINARY',
CALL = 'CALL',
/**
* Statement
* */
BLOCK = 'BLOCK',
BODY = 'BODY',
RULE = 'RULE',
DECLARATION = 'DECLARATION',
// keyword statement
PLUGIN = 'PLUGIN',
IMPORT = 'IMPORT',
USE = 'USE',
FORWARD = 'FORWARD',
INCLUDE = 'INCLUDE',// use mixin
EXTEND = 'EXTEND',// combind repeated css
MIXIN = 'MIXIN', // allow you to define styles that can be re-used throughout your RootNode.
CONTENT = 'CONTENT',// must end with @return
FUNCTION = 'FUNCTION',// must end with @return
/**
* internal Atrule
*/
MediaFeature = 'MediaFeature',
MediaPrelude = 'MediaPrelude',
KeyframesPrelude = 'KeyframesPrelude',
MediaQuery = 'MediaQuery',
Atrule = 'Atrule',
// exceptions
ERROR = 'ERROR',
// control flow
RETURN = 'RETURN',// always return a text
// choice statement
IFSTATEMENT = 'IFSTATEMENT',
//Loops
EACHSTATEMENT = 'EACHSTATEMENT',
RootNode = 'RootNode',
}
/**
* new keyword add steps
* 0. add test cases to test folder
* 1. modify ast.ts (add new Node ast etc)
* 2. modify lexical keywords
* 4.
*/
export type keywordType = '@extend'
| '@mixin' | '@content' | '@include'
| '@import' | '@use' | '@forward'
| '@if' | '@else'
| '@error'
| '@each'
| '@function' | '@return'
| '@plugin'
export type internalAtRuleNames = 'media' | 'keyframes' | 'support' | 'charset' | 'font-face' | string;
export type puncType = '(' | ')' | ',' | ';' | '#' | '{' | '}'
export type assignPuncType = ':'
export type arithmeticOperator = '+' | '-' | '*' | '/' | '%'
export type comparisonOperator = '>' | '<' | '>=' | '<=' | '==' | '!='
export const locStub: SourceLocation = {
filename: '',
start: { line: 1, column: 1, offset: 0 },
end: { line: 1, column: 1, offset: 0 }
}
export interface Position {
offset: number // from start of file
line: number
column: number
}
export interface SourceLocation {
filename: string
start: Position
end: Position
// source: string
}
export interface Node {
[key: string]: any
type: NodeTypes
loc: SourceLocation
}
/**
* mainly used fo @use namespace to interpret namespaced: Variable | CallExpression | Include
*
*/
export interface Namespace extends Node {
namespace?: string | string[]
}
export interface TextNode extends Node {
type: NodeTypes.TEXT
value: string
}
export interface EmptyNode extends Node {
type: NodeTypes.EMPTY
}
export interface VariableNode extends Namespace {
type: NodeTypes.VARIABLE
value: string
}
export interface IdentifierNode extends Namespace {
type: NodeTypes.IDENTIFIER
name: string
}
export interface PlaceholderNode extends Node {
type: NodeTypes.PLACEHOLDER
value: string
}
export interface VarKeyNode extends Namespace {
type: NodeTypes.VAR_KEY
value: string
}
export interface PuncNode extends Node {
type: NodeTypes.PUNC
value: puncType
}
export interface OperatorNode extends Node {
type: NodeTypes.OPERATOR
value: arithmeticOperator | comparisonOperator
}
export interface SelectorNode extends Node {
type: NodeTypes.SELECTOR
meta: MediaStatement['prelude'][] // helper to trace nested media parent
value: TextNode | PlaceholderNode | ListNode | EmptyNode
}
// combined node
export interface BinaryNode extends Node {
type: NodeTypes.BINARY
operator: OperatorNode
left: TextNode | VariableNode | BinaryNode
right: TextNode | VariableNode | BinaryNode
}
export interface ListNode extends Node {
type: NodeTypes.LIST
value: SimpleExpressionNode[]
}
export interface CallExpression extends Node {
type: NodeTypes.CALL
id: IdentifierNode
args: ArgsType
}
export type SimpleExpressionNode = TextNode | PuncNode | OperatorNode | VariableNode | VarKeyNode | BinaryNode | ListNode | CallExpression | EmptyNode
/* Statement */
export type Statement =
BodyStatement
| RuleStatement
| DeclarationStatement
| ImportStatement
| UseStatement
| ForwardStatement
| IncludeStatement
| ExtendStatement
| MixinStatement
| FunctionStatement
| ErrorStatement
| IfStatement
| EachStatement
| ReturnStatement
| Atrule
| PluginStatement
export type ArgsType = (TextNode | VariableNode | BinaryNode | DeclarationStatement)[]
/**
* used with self designed statement eg: @function @mixin
* will be deleted after evaluation, so it will not exist in codegen step
*/
export interface BodyStatement extends Node {
type: NodeTypes.BODY
children: RuleStatement['children']
}
export interface RuleStatement extends Node {
type: NodeTypes.RULE
selector: SelectorNode
children: (Statement | CodegenNode)[]
}
export interface DeclarationStatement extends Node {
type: NodeTypes.DECLARATION
left: VariableNode | TextNode | VarKeyNode
right: ListNode | TextNode // ListNode before transform , TextNode after transform
}
// keyword statement
export interface ImportStatement extends Node {
type: NodeTypes.IMPORT
params: TextNode[]
}
export interface UseStatement extends Node {
type: NodeTypes.USE
params: TextNode[]
}
export interface ForwardStatement extends Node {
type: NodeTypes.FORWARD
params: TextNode[]
}
export interface PluginStatement extends Node {
type: NodeTypes.PLUGIN
value: TextNode
}
export interface ContentPlaceholder extends Node { // @content
type: NodeTypes.CONTENT
}
export interface IncludeStatement extends Node { // used with mixin, eg: @include reset-mixin
type: NodeTypes.INCLUDE
id: IdentifierNode
args: ArgsType
content?: BodyStatement
}
export interface ExtendStatement extends Node { // @extend .error;
type: NodeTypes.EXTEND
param: TextNode | PlaceholderNode
}
export interface MixinStatement extends Node {
type: NodeTypes.MIXIN
id: IdentifierNode
params: (VariableNode | DeclarationStatement)[]
body: BodyStatement
}
export interface FunctionStatement extends Node {
type: NodeTypes.FUNCTION
id: IdentifierNode
params: MixinStatement['params']
body: BodyStatement
}
export interface ReturnStatement extends Node {
type: NodeTypes.RETURN
argument: DeclarationStatement['right']
}
export interface ErrorStatement extends Node {
type: NodeTypes.ERROR
value: ListNode
}
// choice statement
export interface IfStatement extends Node {
type: NodeTypes.IFSTATEMENT
test: BinaryNode | TextNode
consequent: BodyStatement
alternate: IfStatement | BodyStatement | null
}
export interface EachStatement extends Node {
type: NodeTypes.EACHSTATEMENT
left: VariableNode
right: VariableNode
body: RuleStatement
}
/**
* interface prototype for css internal Atrule eg: @media @keyframes @font-face @charset etc
* Todos: change @import by Atrule
*/
export interface Atrule extends Node {
type: NodeTypes.Atrule
name: internalAtRuleNames
block: BodyStatement
prelude: MediaPrelude | KeyframesPrelude
}
/**
* @media ast tree (simplified) start
* (reference: https://github.com/csstree/csstree)
* eg: When the width is between 600px and 900px OR above 1100px - change the appearance of <div>
* @media screen and (max-width: 900px) and (min-width: 600px), (min-width: 1100px) {}
*
*/
export interface MediaFeature extends Node { // (min-width: 600px)
type: NodeTypes.MediaFeature
name: string
value: SimpleExpressionNode // after transform , in codegen value will be TextNode
}
export interface MediaQuery extends Node {
type: NodeTypes.MediaQuery
children: (TextNode | MediaFeature)[] // TextNode contains special identifier: screen | and
}
export interface MediaPrelude extends Node {
type: NodeTypes.MediaPrelude
children: MediaQuery[] // splited by ','
}
export interface MediaStatement extends Atrule {
name: 'media'
prelude: MediaPrelude
}
export interface KeyframesPrelude extends Node {
type: NodeTypes.KeyframesPrelude
children: (TextNode | VarKeyNode)[]
}
export interface Keyframes extends Atrule {
name: string // keyframes | -webkit-keyframes etc
prelude: KeyframesPrelude
}
/**
* @media ast tree end
*/
/**
* codeGenNode is ast that could directly codegen to css
*/
export type CodegenNode = TextNode | ProgCodeGenNode | RootNode
export type ProgCodeGenNode = RuleStatement | EmptyNode | SelectorNode | DeclarationStatement | Atrule | MediaStatement | MediaPrelude | Keyframes | KeyframesPrelude
/**
* {
* filename: scssSourceCode
* }
* used to generate sourceMap
*/
export type FileSourceMap = {
[filename: string]: string
}
export interface RootNode extends Node {
type: NodeTypes.RootNode
fileSourceMap: FileSourceMap
children: (Statement | CodegenNode)[]
}
// work before ast transform
export function createKeyframesPrelude(children: KeyframesPrelude['children']): KeyframesPrelude {
return {
type: NodeTypes.KeyframesPrelude,
children,
loc: {
start: children[0].loc.start,
end: children[children.length - 1].loc.end,
filename: children[0].loc.filename
}
}
}
export function createKeyframes(name: string, prelude: Keyframes['prelude'], block: Keyframes['block']): Keyframes {
return {
type: NodeTypes.Atrule,
name,
block,
prelude,
loc: {
start: prelude.loc.start,
end: block.loc.end,
filename: prelude.loc.filename
}
}
}
export function createMediaFeature(declaration: DeclarationStatement): MediaFeature {
return {
type: NodeTypes.MediaFeature,
name: declaration.left.value,
value: (declaration.right as ListNode).value[0],
loc: declaration.loc
}
}
export function createMediaQuery(children: MediaQuery['children']): MediaQuery {
return {
type: NodeTypes.MediaQuery,
children,
loc: locStub
}
}
export function createMediaPrelude(children: MediaPrelude['children']): MediaPrelude {
return {
type: NodeTypes.MediaPrelude,
children,
loc: locStub
}
}
export function createMediaStatement(prelude: MediaStatement['prelude'], block: MediaStatement['block']): MediaStatement {
return {
type: NodeTypes.Atrule,
name: 'media',
block,
prelude,
loc: {
start: prelude.loc.start,
end: block.loc.end,
filename: prelude.loc.filename
}
}
}
export function createIdentifierNode(id: TextNode): IdentifierNode {
let arr = id.value.split('.'),
name = arr.pop() as string,
namespace = arr;
return {
loc: id.loc || locStub,
namespace,
name,
type: NodeTypes.IDENTIFIER
}
}
export function createCallExpression(id: CallExpression['id'], args: CallExpression['args']): CallExpression {
return {
type: NodeTypes.CALL,
id,
args,
loc: {
start: id.loc.start,
end: args.length ? args[args.length - 1].loc.end : id.loc.end,
filename: id.loc.filename
}
}
}
export function createDeclarationStatement(left: DeclarationStatement['left'], right: DeclarationStatement['right']): DeclarationStatement {
return {
type: NodeTypes.DECLARATION,
left: left,
right: right,
loc: {
start: left.loc.start,
end: right.length ? right[right.length - 1].loc.end : right.loc.end,
filename: left.loc.filename
}
}
}
export function createListNode(list: SimpleExpressionNode[]): ListNode {
return {
type: NodeTypes.LIST,
value: list,
loc: {
start: list[0].loc.start,
end: list[list.length - 1].loc.end,
filename: list[0].loc.filename
}
}
}
export function createMixinStatement(id: MixinStatement['id'], params: MixinStatement['params'], body: MixinStatement['body']): MixinStatement {
return {
type: NodeTypes.MIXIN,
id,
params,
body,
loc: locStub
}
}
export function createFunctionStatement(id: FunctionStatement['id'], params: FunctionStatement['params'], body: FunctionStatement['body']): FunctionStatement {
return {
type: NodeTypes.FUNCTION,
id,
params,
// always contain a ReturnStatement in the last line
body,
loc: locStub
}
}
export function createReturnStatement(list: SimpleExpressionNode[]): ReturnStatement {
return {
type: NodeTypes.RETURN,
argument: createListNode(list),
loc: locStub
}
}
export function createRuleStatement(selector: RuleStatement['selector'], children: RuleStatement['children'], loc: SourceLocation = locStub): RuleStatement {
return {
type: NodeTypes.RULE,
selector,
children,
loc
}
}
export function createContentPlaceholder(loc: ContentPlaceholder['loc'] = locStub): ContentPlaceholder {
return {
type: NodeTypes.CONTENT,
loc
}
}
export function createIncludeStatement(id: IncludeStatement['id'], args: IncludeStatement['args'], content?: IncludeStatement['content']): IncludeStatement {
let node: IncludeStatement = {
type: NodeTypes.INCLUDE,
id,
args,
loc: locStub
}
if (content) {
node.content = content
}
return node;
}
export function createIfStatement(test: IfStatement['test'], consequent: IfStatement['consequent'], alternate: IfStatement['alternate']): IfStatement {
return {
type: NodeTypes.IFSTATEMENT,
test,
consequent,
alternate,
loc: locStub
}
}
export function createEachStatement(left: EachStatement['left'], right: EachStatement['right'], body: EachStatement['body']): EachStatement {
return {
type: NodeTypes.EACHSTATEMENT,
left,
right,
body,
loc: locStub
}
}
export function createVarKeyExpression(value: VarKeyNode['value'], loc: Node['loc']): VarKeyNode {
return {
type: NodeTypes.VAR_KEY,
value,
loc
}
}
export function createTextNode(value: TextNode['value'] = '', loc: Node['loc'] = locStub): TextNode {
return {
type: NodeTypes.TEXT,
value,
loc
}
}
export function createSelectorNode(value: SelectorNode['value'] = createTextNode(), meta: SelectorNode['meta'] = []): SelectorNode {
return {
type: NodeTypes.SELECTOR,
meta,
loc: value.loc,
value: value
}
}
export function createEmptyNode(loc: Node['loc'] = locStub): EmptyNode {
return {
type: NodeTypes.EMPTY,
loc
}
}
export function createBodyStatement(children: BodyStatement['children']): BodyStatement {
return {
type: NodeTypes.BODY,
children,
loc: locStub
};
}
export function createRootNode(children: RootNode['children'] = [], fileSourceMap: RootNode['fileSourceMap'], loc: Node['loc'] = locStub): RootNode {
return {
type: NodeTypes.RootNode,
children,
fileSourceMap,
loc
}
}
export function createRuleFromBody(body: BodyStatement): RuleStatement {
return createRuleStatement(
createSelectorNode(createTextNode('')),
body.children
);
}
export function createRuleFromMedia(media: MediaStatement): RuleStatement {
return createRuleStatement(
createSelectorNode(
createTextNode(''),
[media.prelude]
),
media.block.children
);
}
export function createMediaFromRule(rules: RuleStatement[] | RuleStatement): MediaStatement {
if (!rules.length) {
rules = [rules as RuleStatement]
}
/**
* merge media prelude list as one glued by 'and' idetifier
* */
function mergeMediaPreludeList(preludeList: MediaStatement['prelude'][]): MediaStatement['prelude'] {
function mergeMediaPreludeChildren(children: MediaPrelude['children']): MediaQuery {
let mediaQueryChildren = children.reduce(
(mediaQueryList: MediaQuery['children'], mediaQuery: MediaQuery) =>
mediaQueryList.concat(mediaQuery['children'])
, [])
return createMediaQuery(mediaQueryChildren)
}
let children: MediaPrelude['children'] = [];
preludeList.forEach((prelude: MediaStatement['prelude']) => {
if (children.length > 0) { // push 'and' identifer to glue mediaQuery
children.push(createMediaQuery([createTextNode('and')]))
}
children = children.concat(prelude.children)
})
// return mediaPrelude with only one child
return createMediaPrelude(children.length > 1 ? [mergeMediaPreludeChildren(children)] : children)
}
let prelude = mergeMediaPreludeList(
Array.from(
new Set(
rules.reduce(
(preludeList: MediaStatement['prelude'][], rule: RuleStatement) =>
preludeList.concat(rule.selector.meta)
, [])
)
)
)
// reset rule selector meta
rules.forEach((rule: RuleStatement) => rule.selector.meta = [])
return createMediaStatement(prelude, createBodyStatement(rules as RuleStatement[]))
}
export function createVariableWithNamespace(namespace: Namespace, variable: VariableNode): VariableNode {
return {
...variable,
namespace: namespace.namespace,
loc: {
...namespace.loc,
start: namespace.loc.start,
end: variable.loc.end
}
}
} | the_stack |
import { Plan, PrismaClient } from '@prisma/client'
import fs from 'fs'
import moment from 'moment'
import nock from 'nock'
import path from 'path'
import { createProbot, Probot } from 'probot'
import { createLogger, format, Logger, transports } from 'winston'
import { logToJSON, removeLogsDateFields } from '../__fixtures__/utils'
/* Fixtures */
import installationPayload from './../__fixtures__/github/installation.created'
import issuesLabeledPayload from './../__fixtures__/github/issues.labeled'
import pullRequestLabeledPayload from './../__fixtures__/github/pr.labeled'
import labelCreatedPayload from './../__fixtures__/github/label.created'
// import marketplacePurchasePayload from './../__fixtures__/github/marketplace_purchase.purchased'
// import marketplaceCancelPayload from './../__fixtures__/github/marketplace_purchase.cancelled'
import prPayload from './../__fixtures__/github/pullrequest.opened'
import pushPayload from './../__fixtures__/github/push'
import repositoryCreatedPayload from './../__fixtures__/github/repository.created'
const configFixture = fs.readFileSync(
path.resolve(__dirname, './../__fixtures__/labelsync.yml'),
{ encoding: 'utf-8' },
)
const wildcardConfigFixture = fs.readFileSync(
path.resolve(__dirname, './../__fixtures__/configurations/wildcard.yml'),
{ encoding: 'utf-8' },
)
const newRepoConfigFixture = fs.readFileSync(
path.resolve(__dirname, './../__fixtures__/configurations/new.yml'),
{ encoding: 'utf-8' },
)
const siblingsConfigFixture = fs.readFileSync(
path.resolve(__dirname, './../__fixtures__/configurations/siblings.yml'),
{ encoding: 'utf-8' },
)
const LOGS_FILE = path.resolve(__dirname, 'logs', 'github_integration.log')
/* Probot app */
const manager = require('../../src')
describe('github:', () => {
let client: PrismaClient
beforeAll(async () => {
// Network settings
nock.disableNetConnect()
// local servers
nock.enableNetConnect((host) => {
return host.includes('localhost') || host.includes('127.0.0.1')
})
// DataStores
client = new PrismaClient()
})
afterAll(async () => {
nock.cleanAll()
nock.enableNetConnect()
await client.$disconnect()
})
/**
* TESTS
*/
const plans: Plan[] = ['FREE', 'PAID']
for (const plan of plans) {
describe(`${plan}`, () => {
/* Tests on each plan. */
let winston: Logger
let probot: Probot
/* Plan specific setup */
beforeEach(async () => {
await client.installation.deleteMany({ where: {} })
// Create an installation.
await client.installation.create({
data: {
account: 'maticzav',
email: 'email',
plan,
periodEndsAt: moment().add(1, 'h').toDate(),
activated: true,
},
})
/* Setup probot */
probot = createProbot({ id: 123, githubToken: 'token', cert: 'test' })
const app = probot.load((app) => manager(app, client, winston))
})
afterEach(() => {
nock.cleanAll()
})
beforeAll(() => {
/* Reset logs. */
if (fs.existsSync(LOGS_FILE)) fs.unlinkSync(LOGS_FILE)
winston = createLogger({
level: 'debug',
exitOnError: false,
format: format.json(),
transports: [new transports.File({ filename: LOGS_FILE })],
})
})
// test(
// 'marketplace purchase event',
// async () => {
// await probot.receive({
// id: 'marketplace.purchased',
// name: 'marketplace_purchase',
// payload: marketplacePurchasePayload,
// })
// /* Tests */
// const purchase = await client.purchase.findUnique({
// where: { owner: 'username' },
// })
// expect(purchase).not.toBeNull()
// expect(purchase).not.toBeUndefined()
// },
// 5 * 60 * 1000,
// )
// test(
// 'marketplace cancel event',
// async () => {
// await probot.receive({
// id: 'marketplace.cancel',
// name: 'marketplace_purchase',
// payload: marketplaceCancelPayload,
// })
// /* Tests */
// const purchases = await client.purchase.findMany({
// where: {
// owner: 'maticzav',
// },
// })
// expect(purchases.length).toBe(0)
// },
// 5 * 60 * 1000,
// )
test(
'installation event bootstrap config',
async () => {
expect.assertions(5)
const repoEndpoint = jest.fn().mockReturnValue({})
const createRepoEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
expect(body).toEqual({
name: 'maticzav-labelsync',
description: 'LabelSync configuration repository.',
auto_init: true,
})
return
})
let blobs: { [sha: number]: string } = {}
const createBlobEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
const sha = Object.keys(blobs).length
blobs[sha] = body.content
return { url: 'url', sha }
})
let trees: { [sha: number]: string } = {}
const createTreeEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
const sha = Object.keys(trees).length
trees[sha] = body.tree
return { sha: sha, url: 'url', tree: body.tree }
})
const parentSha = Math.floor(Math.random() * 1000).toString()
const getRefEndpoint = jest.fn().mockImplementation((uri, body) => {
return { object: { sha: parentSha } }
})
const commitSha = Math.floor(Math.random() * 1000).toString()
const createCommitEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
expect(body.parents).toEqual([parentSha])
return { sha: commitSha }
})
const updateRefEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
expect(body.sha).toBe(commitSha)
return { object: { sha: '' } }
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get('/repos/maticzav/maticzav-labelsync')
.reply(404, repoEndpoint)
nock('https://api.github.com')
.post('/orgs/maticzav/repos')
.reply(200, createRepoEndpoint)
nock('https://api.github.com')
.post('/repos/maticzav/maticzav-labelsync/git/blobs')
.reply(200, createBlobEndpoint)
.persist()
nock('https://api.github.com')
.post('/repos/maticzav/maticzav-labelsync/git/trees')
.reply(200, createTreeEndpoint)
.persist()
nock('https://api.github.com')
.get('/repos/maticzav/maticzav-labelsync/git/refs/heads/master')
.reply(200, getRefEndpoint)
nock('https://api.github.com')
.post('/repos/maticzav/maticzav-labelsync/git/commits')
.reply(200, createCommitEndpoint)
nock('https://api.github.com')
.patch('/repos/maticzav/maticzav-labelsync/git/refs/heads/master')
.reply(200, updateRefEndpoint)
await probot.receive({
id: 'installation.boot',
name: 'installation',
payload: installationPayload,
})
/* Tests */
expect(repoEndpoint).toBeCalledTimes(1)
expect(createRepoEndpoint).toBeCalledTimes(1)
/* Moved to the other test in Github */
// expect(blobs).toMatchSnapshot()
// expect(trees).toMatchSnapshot()
},
5 * 60 * 1000,
)
test(
'installation invalid config issue',
async () => {
expect.assertions(3)
const repoEndpoint = jest.fn().mockReturnValue({
default_branch: 'master',
})
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from('invalid: invalid').toString('base64'),
})
const issuesEndpoint = jest.fn().mockImplementation((uri, body) => {
expect(body).toMatchSnapshot()
return
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, () => {
return { token: 'test' }
})
nock('https://api.github.com')
.get('/repos/maticzav/maticzav-labelsync')
.reply(200, repoEndpoint)
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.post('/repos/maticzav/maticzav-labelsync/issues')
.reply(200, issuesEndpoint)
.persist()
await probot.receive({
id: 'installation.invalid',
name: 'installation',
payload: installationPayload,
})
/* Tests */
expect(repoEndpoint).toBeCalledTimes(1)
expect(configEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test(
'installation event sync',
async () => {
expect.assertions(11)
const repoEndpoint = jest.fn().mockReturnValue({
default_branch: 'master',
})
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(configFixture).toString('base64'),
})
const installationsEndpoint = jest.fn().mockReturnValue({
repositories: [
{ name: 'changed' },
{ name: 'unchanged' },
{ name: 'other' },
],
})
const labelsEndpoint = jest.fn().mockImplementation((uri) => {
switch (uri) {
case '/repos/maticzav/changed/labels?per_page=100&page=1': {
return [
// {
// name: 'create/new',
// color: '000000',
// },
// {
// name: 'alias/new',
// color: '000000',
// },
{
name: 'alias/old:1',
color: '000000',
},
{
name: 'alias/old:2',
color: '000000',
},
{
name: 'update/color',
color: '000000',
},
{
name: 'remove',
color: '000000',
},
]
}
case '/repos/maticzav/unchanged/labels?per_page=100&page=1': {
return [
{
name: 'label-a',
color: '000000',
},
]
}
default: {
throw new Error(`TESTS: Unknown uri: ${uri}`)
}
}
})
const getIssuesForRepoEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
return []
})
const createLabelsEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
expect({ body, uri }).toEqual({
uri: '/repos/maticzav/changed/labels',
body: {
color: '000000',
name: 'create/new',
},
})
return
})
let updatedLabels: { uri: string; body: object }[] = []
const updateLabelsEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
updatedLabels.push({ uri, body })
return
})
let removedLabels: string[] = []
const removeLabelsEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
removedLabels.push(uri)
return
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, () => {
return { token: 'test' }
})
nock('https://api.github.com')
.get('/repos/maticzav/maticzav-labelsync')
.reply(200, repoEndpoint)
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.get('/installation/repositories?per_page=100&page=1')
.reply(200, installationsEndpoint)
nock('https://api.github.com')
.get(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, labelsEndpoint)
.persist()
nock('https://api.github.com')
.get(/\/repos\/maticzav\/\w+\/issues\?per_page\=100\&page\=1/)
.reply(200, getIssuesForRepoEndpoint)
.persist()
nock('https://api.github.com')
.post(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, createLabelsEndpoint)
.persist()
nock('https://api.github.com')
.patch(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, updateLabelsEndpoint)
.persist()
nock('https://api.github.com')
.delete(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, removeLabelsEndpoint)
.persist()
await probot.receive({
id: 'installation.sync',
name: 'installation',
payload: installationPayload,
})
/* Tests */
expect(repoEndpoint).toBeCalledTimes(1)
expect(configEndpoint).toBeCalledTimes(1)
expect(installationsEndpoint).toBeCalledTimes(1)
expect(labelsEndpoint).toBeCalledTimes(2)
expect(getIssuesForRepoEndpoint).toBeCalledTimes(1)
expect(createLabelsEndpoint).toBeCalledTimes(1)
expect(updateLabelsEndpoint).toBeCalledTimes(2)
expect(removeLabelsEndpoint).toBeCalledTimes(2)
expect(updatedLabels).toMatchSnapshot()
expect(removedLabels).toMatchSnapshot()
},
5 * 60 * 1000,
)
test(
'installation event insufficient permissions',
async () => {
expect.assertions(4)
const repoEndpoint = jest.fn().mockReturnValue({
default_branch: 'master',
})
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(configFixture).toString('base64'),
})
const installationsEndpoint = jest.fn().mockReturnValue({
repositories: [{ name: 'changed' }],
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, () => {
return { token: 'test' }
})
nock('https://api.github.com')
.get('/repos/maticzav/maticzav-labelsync')
.reply(200, repoEndpoint)
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.get('/installation/repositories?per_page=100&page=1')
.reply(200, installationsEndpoint)
nock('https://api.github.com')
.post('/repos/maticzav/maticzav-labelsync/issues')
.reply(200, (uri, body) => {
expect(body).toMatchSnapshot()
return
})
await probot.receive({
id: 'installation.insufficient',
name: 'installation',
payload: installationPayload,
})
/* Tests */
expect(repoEndpoint).toBeCalledTimes(1)
expect(configEndpoint).toBeCalledTimes(1)
expect(installationsEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test(
'push event',
async () => {
expect.assertions(13)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(configFixture).toString('base64'),
})
const installationsEndpoint = jest.fn().mockReturnValue({
repositories: [
{ name: 'unchanged' },
{ name: 'CHANGED' },
{ name: 'other' },
],
})
const labelsEndpoint = jest.fn().mockImplementation((uri) => {
switch (uri) {
case '/repos/maticzav/changed/labels?per_page=100&page=1': {
return [
// {
// name: 'create/new',
// color: '000000',
// },
// {
// name: 'alias/new',
// color: '000000',
// },
{
name: 'alias/old:1',
color: '000000',
},
{
name: 'alias/old:2',
color: '000000',
},
{
name: 'update/color',
color: '000000',
},
{
name: 'remove',
color: '000000',
},
]
}
case '/repos/maticzav/unchanged/labels?per_page=100&page=1': {
return [
{
name: 'label-a',
color: '000000',
},
]
}
default: {
throw new Error(`TESTS: Unknown uri: ${uri}`)
}
}
})
const getIssuesForRepoEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
return [
{
number: 1,
labels: [{ name: 'alias/old:1' }, { name: 'alias/old:2' }],
},
{
number: 3,
labels: [],
},
{
number: 4,
labels: [{ name: 'alias/old:2' }],
},
]
})
const createLabelsEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
expect({ body, uri }).toEqual({
uri: '/repos/maticzav/changed/labels',
body: {
color: '000000',
name: 'create/new',
},
})
return
})
let updatedLabels: { uri: string; body: object }[] = []
const updateLabelsEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
updatedLabels.push({ uri, body })
return
})
let removedLabels: string[] = []
const removeLabelsEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
removedLabels.push(uri)
return
})
let aliasedLabels: { uri: string; body: object }[] = []
const issueLabelsEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
aliasedLabels.push({ uri, body })
return
})
const commitCommentEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
expect(body).toMatchSnapshot()
return
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.get('/installation/repositories?per_page=100&page=1')
.reply(200, installationsEndpoint)
nock('https://api.github.com')
.get(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, labelsEndpoint)
.persist()
nock('https://api.github.com')
.get(/\/repos\/maticzav\/\w+\/issues\?per_page\=100\&page\=1/)
.reply(200, getIssuesForRepoEndpoint)
.persist()
nock('https://api.github.com')
.post(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, createLabelsEndpoint)
.persist()
nock('https://api.github.com')
.patch(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, updateLabelsEndpoint)
.persist()
nock('https://api.github.com')
.delete(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, removeLabelsEndpoint)
.persist()
nock('https://api.github.com')
.post(/\/repos\/maticzav\/\w+\/issues\/\d+\/labels/)
.reply(200, issueLabelsEndpoint)
.persist()
nock('https://api.github.com')
.post(
'/repos/maticzav/maticzav-labelsync/commits/0000000000000000000000000000000000000000/comments',
)
.reply(200, commitCommentEndpoint)
.persist()
await probot.receive({
id: 'push',
name: 'push',
payload: pushPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
expect(installationsEndpoint).toBeCalledTimes(1)
expect(labelsEndpoint).toBeCalledTimes(2)
expect(getIssuesForRepoEndpoint).toBeCalledTimes(1)
expect(createLabelsEndpoint).toBeCalledTimes(1)
expect(updateLabelsEndpoint).toBeCalledTimes(2)
expect(removeLabelsEndpoint).toBeCalledTimes(2)
expect(commitCommentEndpoint).toBeCalledTimes(1)
expect(updatedLabels).toMatchSnapshot()
expect(removedLabels).toMatchSnapshot()
expect(aliasedLabels).toMatchSnapshot()
},
5 * 60 * 1000,
)
test(
'push event invalid configuration',
async () => {
expect.assertions(3)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from('invalid: invalid').toString('base64'),
})
const commitCommentEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
expect(body).toMatchSnapshot()
return
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.post(
'/repos/maticzav/maticzav-labelsync/commits/0000000000000000000000000000000000000000/comments',
)
.reply(200, commitCommentEndpoint)
.persist()
await probot.receive({
id: 'push',
name: 'push',
payload: pushPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
expect(commitCommentEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test(
'push event with insufficient premissions',
async () => {
expect.assertions(3)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(configFixture).toString('base64'),
})
const installationsEndpoint = jest.fn().mockReturnValue({
repositories: [{ name: 'CHANGED' }],
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.get('/installation/repositories?per_page=100&page=1')
.reply(200, installationsEndpoint)
nock('https://api.github.com')
.post(
'/repos/maticzav/maticzav-labelsync/commits/0000000000000000000000000000000000000000/comments',
)
.reply(200, (uri, body) => {
expect(body).toMatchSnapshot()
return
})
.persist()
await probot.receive({
id: 'pushinsufficient',
name: 'push',
payload: pushPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
expect(installationsEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test(
'pull_request',
async () => {
expect.assertions(7)
const compareEndpoint = jest.fn().mockReturnValue({
files: [{ filename: 'labelsync.yml' }, { filename: 'README.md' }],
})
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(configFixture).toString('base64'),
})
const installationsEndpoint = jest.fn().mockReturnValue({
repositories: [
{ name: 'changed' },
{ name: 'unchanged' },
{ name: 'other' },
],
})
const labelsEndpoint = jest.fn().mockImplementation((uri) => {
switch (uri) {
case '/repos/maticzav/changed/labels?per_page=100&page=1': {
return [
// {
// name: 'create/new',
// color: '000000',
// },
// {
// name: 'alias/new',
// color: '000000',
// },
{
name: 'alias/old:1',
color: '000000',
},
{
name: 'alias/old:2',
color: '000000',
},
{
name: 'update/color',
color: '000000',
},
{
name: 'remove',
color: '000000',
},
]
}
case '/repos/maticzav/unchanged/labels?per_page=100&page=1': {
return [
{
name: 'label-a',
color: '000000',
},
]
}
default: {
throw new Error(`TESTS: Unknown uri: ${uri}`)
}
}
})
const getIssuesForRepoEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
return [
{
number: 1,
labels: [{ name: 'alias/old:1' }, { name: 'alias/old:2' }],
},
]
})
/* Mocks */
nock('https://api.github.com')
.get('/repos/maticzav/maticzav-labelsync/compare/master...labels')
.reply(200, compareEndpoint)
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.post('/repos/maticzav/maticzav-labelsync/check-runs')
.reply(200, (uri, body: any) => {
// body = JSON.parse(body)
delete body['started_at']
expect(body).toMatchSnapshot()
return { id: 123 }
})
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=labels',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.get('/installation/repositories?per_page=100&page=1')
.reply(200, installationsEndpoint)
nock('https://api.github.com')
.get(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, labelsEndpoint)
.persist()
nock('https://api.github.com')
.get(/\/repos\/maticzav\/\w+\/issues\?per_page\=100\&page\=1/)
.reply(200, getIssuesForRepoEndpoint)
.persist()
nock('https://api.github.com')
.post('/repos/maticzav/maticzav-labelsync/issues/2/comments')
.reply(200, (uri, body) => {
expect(body).toMatchSnapshot()
return
})
nock('https://api.github.com')
.patch('/repos/maticzav/maticzav-labelsync/check-runs/123')
.reply(200, (uri, body: any) => {
// body = JSON.parse(body)
delete body['completed_at']
expect(body).toMatchSnapshot()
return { id: 123 }
})
await probot.receive({
id: 'pr',
name: 'pull_request',
payload: prPayload,
})
/* Tests */
expect(compareEndpoint).toBeCalledTimes(1)
expect(configEndpoint).toBeCalledTimes(1)
expect(installationsEndpoint).toBeCalledTimes(1)
expect(getIssuesForRepoEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test(
'pull_request with no changes',
async () => {
expect.assertions(1)
const compareEndpoint = jest.fn().mockReturnValue({
files: [{ filename: 'README.md' }],
})
/* Mocks */
nock('https://api.github.com')
.get('/repos/maticzav/maticzav-labelsync/compare/master...labels')
.reply(200, compareEndpoint)
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
await probot.receive({
id: 'pr.no_changes',
name: 'pull_request',
payload: prPayload,
})
/* Tests */
expect(compareEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test(
'pull_request with insufficient permissions',
async () => {
expect.assertions(4)
const compareEndpoint = jest.fn().mockReturnValue({
files: [{ filename: 'README.md' }, { filename: 'labelsync.yml' }],
})
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(configFixture).toString('base64'),
})
const installationsEndpoint = jest.fn().mockReturnValue({
repositories: [{ name: 'changed' }],
})
/* Mocks */
nock('https://api.github.com')
.get('/repos/maticzav/maticzav-labelsync/compare/master...labels')
.reply(200, compareEndpoint)
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.post('/repos/maticzav/maticzav-labelsync/check-runs')
.reply(200, (uri, body: any) => {
// body = JSON.parse(body)
delete body['started_at']
expect(body).toMatchSnapshot()
return { id: 123 }
})
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=labels',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.get('/installation/repositories?per_page=100&page=1')
.reply(200, installationsEndpoint)
nock('https://api.github.com')
.patch('/repos/maticzav/maticzav-labelsync/check-runs/123')
.reply(200, (uri, body: any) => {
// body = JSON.parse(body)
delete body['completed_at']
expect(body).toMatchSnapshot()
return { id: 123 }
})
await probot.receive({
id: 'pr.insufficient',
name: 'pull_request',
payload: prPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
expect(installationsEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test(
'label.created event removes unsupported labels',
async () => {
expect.assertions(2)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(configFixture).toString('base64'),
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.delete(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, (uri) => {
expect(uri).toBe('/repos/maticzav/changed/labels/:bug:%20Bugfix')
})
.persist()
await probot.receive({
id: 'labelcreated',
name: 'label.created',
payload: labelCreatedPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
if (plan === 'PAID')
test(
'label.created event removes unsupported labels for wildcard configuration',
async () => {
expect.assertions(2)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(wildcardConfigFixture).toString('base64'),
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.delete(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, (uri) => {
expect(uri).toBe(
'/repos/maticzav/changed/labels/:bug:%20Bugfix',
)
})
.persist()
await probot.receive({
id: 'labelcreated-wildcard',
name: 'label.created',
payload: labelCreatedPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test(
'issues.labeled adds siblings',
async () => {
expect.assertions(2)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(siblingsConfigFixture).toString('base64'),
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
let addedLabels: string[] = []
nock('https://api.github.com')
.post('/repos/maticzav/changed/issues/1/labels')
.reply(200, (uri, body) => {
addedLabels.push(...(body as any))
return
})
.persist()
await probot.receive({
id: 'issueslabeled',
name: 'issues.labeled',
payload: issuesLabeledPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
expect(addedLabels).toMatchSnapshot()
},
5 * 60 * 1000,
)
test(
'pull_request.labeled adds siblings',
async () => {
expect.assertions(2)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(siblingsConfigFixture).toString('base64'),
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
let addedLabels: string[] = []
nock('https://api.github.com')
.post('/repos/maticzav/changed/issues/1/labels')
.reply(200, (uri, body) => {
addedLabels.push(...(body as any))
return
})
.persist()
await probot.receive({
id: 'pullrequestlabled',
name: 'pull_request.labeled',
payload: pullRequestLabeledPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
expect(addedLabels).toMatchSnapshot()
},
5 * 60 * 1000,
)
test(
'repository created event',
async () => {
expect.assertions(3)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(newRepoConfigFixture).toString('base64'),
})
const labelsEndpoint = jest.fn().mockImplementation((uri) => {
/* Nevermind the actual sync - this only checks that sync occurs. */
return []
})
const crudLabelEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
return
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.get(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, labelsEndpoint)
.persist()
nock('https://api.github.com')
.post(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, crudLabelEndpoint)
.persist()
await probot.receive({
id: 'repository.created',
name: 'repository',
payload: repositoryCreatedPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
expect(labelsEndpoint).toBeCalledTimes(1)
expect(crudLabelEndpoint).toBeCalledTimes(4)
},
5 * 60 * 1000,
)
if (plan === 'PAID')
test(
'repository created wildcard event',
async () => {
expect.assertions(3)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(wildcardConfigFixture).toString('base64'),
})
const labelsEndpoint = jest.fn().mockImplementation((uri) => {
/* Nevermind the actual sync - this only checks that sync occurs. */
return []
})
const crudLabelEndpoint = jest
.fn()
.mockImplementation((uri, body) => {
return
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
nock('https://api.github.com')
.get(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, labelsEndpoint)
.persist()
nock('https://api.github.com')
.post(/\/repos\/maticzav\/\w+\/labels/)
.reply(200, crudLabelEndpoint)
.persist()
await probot.receive({
id: 'repository.created',
name: 'repository',
payload: repositoryCreatedPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
expect(labelsEndpoint).toBeCalledTimes(1)
expect(crudLabelEndpoint).toBeCalledTimes(4)
},
5 * 60 * 1000,
)
if (plan === 'FREE')
test(
'repository created event on free',
async () => {
expect.assertions(1)
const configEndpoint = jest.fn().mockReturnValue({
content: Buffer.from(wildcardConfigFixture).toString('base64'),
})
/* Mocks */
nock('https://api.github.com')
.post('/app/installations/13055/access_tokens')
.reply(200, { token: 'test' })
nock('https://api.github.com')
.get(
'/repos/maticzav/maticzav-labelsync/contents/labelsync.yml?ref=refs%2Fheads%2Fmaster',
)
.reply(200, configEndpoint)
await probot.receive({
id: 'repository.created',
name: 'repository',
payload: repositoryCreatedPayload,
})
/* Tests */
expect(configEndpoint).toBeCalledTimes(1)
},
5 * 60 * 1000,
)
test('logs are reporting correctly', async () => {
const logs = fs.readFileSync(LOGS_FILE, { encoding: 'utf-8' })
const json = logToJSON(logs)
expect(json.map(removeLogsDateFields)).toMatchSnapshot()
})
/* End of tests */
})
}
}) | the_stack |
// tslint:disable:object-literal-sort-keys
export default {
metadata: {
name: 'xgboost-training-gzkm9',
generateName: 'xgboost-training-',
namespace: 'default',
selfLink: '/apis/argoproj.io/v1alpha1/namespaces/default/workflows/xgboost-training-gzkm9',
uid: '2c007465-41cf-11e8-bba7-42010a8a0fc2',
resourceVersion: '696668',
creationTimestamp: '2018-04-16T23:37:48Z',
labels: {
'workflows.argoproj.io/completed': 'true',
'workflows.argoproj.io/phase': 'Succeeded',
},
},
spec: {
templates: [
{
name: 'exit-handler',
inputs: {
parameters: [
{
name: 'project',
},
{
name: 'region',
},
{
name: 'cluster',
},
],
},
outputs: {},
metadata: {},
steps: [
[
{
name: 'deletecluster',
template: 'deletecluster',
arguments: {
parameters: [
{
name: 'project',
value: '{{inputs.parameters.project}}',
},
{
name: 'region',
value: '{{inputs.parameters.region}}',
},
{
name: 'name',
value: '{{inputs.parameters.cluster}}',
},
],
},
},
],
],
},
{
name: 'xgboost-training',
inputs: {
parameters: [
{
name: 'project',
},
{
name: 'region',
},
{
name: 'cluster',
},
{
name: 'output',
},
{
name: 'train',
},
{
name: 'eval',
},
{
name: 'schema',
},
{
name: 'target',
},
{
name: 'package',
},
{
name: 'workers',
},
{
name: 'rounds',
},
{
name: 'conf',
},
],
},
outputs: {},
metadata: {},
steps: [
[
{
name: 'createcluster',
template: 'createcluster',
arguments: {
parameters: [
{
name: 'project',
value: '{{inputs.parameters.project}}',
},
{
name: 'region',
value: '{{inputs.parameters.region}}',
},
{
name: 'name',
value: '{{inputs.parameters.cluster}}',
},
{
name: 'staging',
value: '{{inputs.parameters.output}}/{{workflow.name}}/staging',
},
],
},
},
],
[
{
name: 'analyze',
template: 'analyze',
arguments: {
parameters: [
{
name: 'project',
value: '{{inputs.parameters.project}}',
},
{
name: 'region',
value: '{{inputs.parameters.region}}',
},
{
name: 'cluster',
value: '{{inputs.parameters.cluster}}',
},
{
name: 'output',
value: '{{inputs.parameters.output}}/{{workflow.name}}/analysis',
},
{
name: 'train',
value: '{{inputs.parameters.train}}',
},
{
name: 'schema',
value: '{{inputs.parameters.schema}}',
},
],
},
},
],
[
{
name: 'transform',
template: 'transform',
arguments: {
parameters: [
{
name: 'project',
value: '{{inputs.parameters.project}}',
},
{
name: 'region',
value: '{{inputs.parameters.region}}',
},
{
name: 'cluster',
value: '{{inputs.parameters.cluster}}',
},
{
name: 'output',
value: '{{inputs.parameters.output}}/{{workflow.name}}/transform',
},
{
name: 'train',
value: '{{inputs.parameters.train}}',
},
{
name: 'eval',
value: '{{inputs.parameters.eval}}',
},
{
name: 'target',
value: '{{inputs.parameters.target}}',
},
{
name: 'analysis',
value: '{{inputs.parameters.output}}/{{workflow.name}}/analysis',
},
],
},
},
],
[
{
name: 'train',
template: 'train',
arguments: {
parameters: [
{
name: 'project',
value: '{{inputs.parameters.project}}',
},
{
name: 'region',
value: '{{inputs.parameters.region}}',
},
{
name: 'cluster',
value: '{{inputs.parameters.cluster}}',
},
{
name: 'output',
value: '{{inputs.parameters.output}}/{{workflow.name}}/model',
},
{
name: 'train',
value: '{{inputs.parameters.output}}/{{workflow.name}}/transform/train/part-*',
},
{
name: 'eval',
value: '{{inputs.parameters.output}}/{{workflow.name}}/transform/eval/part-*',
},
{
name: 'target',
value: '{{inputs.parameters.target}}',
},
{
name: 'analysis',
value: '{{inputs.parameters.output}}/{{workflow.name}}/analysis',
},
{
name: 'package',
value: '{{inputs.parameters.package}}',
},
{
name: 'workers',
value: '{{inputs.parameters.workers}}',
},
{
name: 'rounds',
value: '{{inputs.parameters.rounds}}',
},
{
name: 'conf',
value: '{{inputs.parameters.conf}}',
},
],
},
},
],
[
{
name: 'batchpredict',
template: 'batchpredict',
arguments: {
parameters: [
{
name: 'project',
value: '{{inputs.parameters.project}}',
},
{
name: 'region',
value: '{{inputs.parameters.region}}',
},
{
name: 'cluster',
value: '{{inputs.parameters.cluster}}',
},
{
name: 'output',
value: '{{inputs.parameters.output}}/{{workflow.name}}/batchpredict',
},
{
name: 'eval',
value: '{{inputs.parameters.output}}/{{workflow.name}}/transform/eval/part-*',
},
{
name: 'target',
value: '{{inputs.parameters.target}}',
},
{
name: 'analysis',
value: '{{inputs.parameters.output}}/{{workflow.name}}/analysis',
},
{
name: 'package',
value: '{{inputs.parameters.package}}',
},
{
name: 'model',
value: '{{inputs.parameters.output}}/{{workflow.name}}/model',
},
],
},
},
],
[
{
name: 'confusionmatrix',
template: 'confusionmatrix',
arguments: {
parameters: [
{
name: 'output',
value: '{{inputs.parameters.output}}/{{workflow.name}}/confusionmatrix',
},
{
name: 'predictions',
value: '{{inputs.parameters.output}}/{{workflow.name}}/batchpredict/part-*.csv',
},
{
name: 'analysis',
value: '{{inputs.parameters.output}}/{{workflow.name}}/analysis',
},
{
name: 'target',
value: '{{inputs.parameters.target}}',
},
],
},
},
],
],
},
{
name: 'createcluster',
inputs: {
parameters: [
{
name: 'project',
},
{
name: 'region',
},
{
name: 'name',
},
{
name: 'staging',
},
],
},
outputs: {},
metadata: {},
container: {
name: '',
image: 'gcr.io/ml-pipeline/ml-pipeline-dataproc-xgboost',
command: ['sh', '-c'],
args: [
'python /ml/create_cluster.py --project {{inputs.parameters.project}} ' +
'--region {{inputs.parameters.region}} --name {{inputs.parameters.name}} ' +
'--staging {{inputs.parameters.staging}}',
],
resources: {},
},
},
{
name: 'analyze',
inputs: {
parameters: [
{
name: 'project',
},
{
name: 'region',
},
{
name: 'cluster',
},
{
name: 'output',
},
{
name: 'train',
},
{
name: 'schema',
},
],
},
outputs: {},
metadata: {},
container: {
name: '',
image: 'gcr.io/ml-pipeline/ml-pipeline-dataproc-xgboost',
command: ['sh', '-c'],
args: [
'python /ml/analyze.py --project {{inputs.parameters.project}} ' +
'--region {{inputs.parameters.region}} --cluster ' +
'{{inputs.parameters.cluster}} --output ' +
'{{inputs.parameters.output}} --train {{inputs.parameters.train}} ' +
'--schema {{inputs.parameters.schema}}',
],
resources: {},
},
},
{
name: 'transform',
inputs: {
parameters: [
{
name: 'project',
},
{
name: 'region',
},
{
name: 'cluster',
},
{
name: 'output',
},
{
name: 'train',
},
{
name: 'eval',
},
{
name: 'target',
},
{
name: 'analysis',
},
],
},
outputs: {},
metadata: {},
container: {
name: '',
image: 'gcr.io/ml-pipeline/ml-pipeline-dataproc-xgboost',
command: ['sh', '-c'],
args: [
'python /ml/transform.py --project {{inputs.parameters.project}} ' +
'--region {{inputs.parameters.region}} --cluster ' +
'{{inputs.parameters.cluster}} --output ' +
'{{inputs.parameters.output}} --train {{inputs.parameters.train}} ' +
'--eval {{inputs.parameters.eval}} --target ' +
'{{inputs.parameters.target}} --analysis ' +
'{{inputs.parameters.analysis}}',
],
resources: {},
},
},
{
name: 'train',
inputs: {
parameters: [
{
name: 'project',
},
{
name: 'region',
},
{
name: 'cluster',
},
{
name: 'output',
},
{
name: 'train',
},
{
name: 'eval',
},
{
name: 'target',
},
{
name: 'analysis',
},
{
name: 'package',
},
{
name: 'workers',
},
{
name: 'rounds',
},
{
name: 'conf',
},
],
},
outputs: {},
metadata: {},
container: {
name: '',
image: 'gcr.io/ml-pipeline/ml-pipeline-dataproc-xgboost',
command: ['sh', '-c'],
args: [
// tslint:disable-next-line:max-line-length
'python /ml/train.py --project {{inputs.parameters.project}} --region {{inputs.parameters.region}} --cluster {{inputs.parameters.cluster}} --output {{inputs.parameters.output}} --train {{inputs.parameters.train}} --eval {{inputs.parameters.eval}} --target {{inputs.parameters.target}} --analysis {{inputs.parameters.analysis}} --package {{inputs.parameters.package}} --workers {{inputs.parameters.workers}} --rounds {{inputs.parameters.rounds}} --conf {{inputs.parameters.conf}}',
],
resources: {},
},
},
{
name: 'batchpredict',
inputs: {
parameters: [
{
name: 'project',
},
{
name: 'region',
},
{
name: 'cluster',
},
{
name: 'output',
},
{
name: 'eval',
},
{
name: 'model',
},
{
name: 'target',
},
{
name: 'package',
},
{
name: 'analysis',
},
],
},
outputs: {},
metadata: {},
container: {
name: '',
image: 'gcr.io/ml-pipeline/ml-pipeline-dataproc-xgboost',
command: ['sh', '-c'],
args: [
// tslint:disable-next-line:max-line-length
'python /ml/predict.py --project {{inputs.parameters.project}} --region {{inputs.parameters.region}} --cluster {{inputs.parameters.cluster}} --output {{inputs.parameters.output}} --predict {{inputs.parameters.eval}} --analysis {{inputs.parameters.analysis}} --target {{inputs.parameters.target}} --model {{inputs.parameters.model}} --package {{inputs.parameters.package}} ',
],
resources: {},
},
},
{
name: 'confusionmatrix',
inputs: {
parameters: [
{
name: 'output',
},
{
name: 'analysis',
},
{
name: 'predictions',
},
{
name: 'target',
},
],
},
outputs: {},
metadata: {},
container: {
name: '',
image: 'gcr.io/ml-pipeline/ml-pipeline-local',
command: ['sh', '-c'],
args: [
// tslint:disable-next-line:max-line-length
'python /ml/confusion_matrix.py --output {{inputs.parameters.output}} --predictions {{inputs.parameters.predictions}} --analysis {{inputs.parameters.analysis}} --target {{inputs.parameters.target}}',
],
resources: {},
},
},
{
name: 'deletecluster',
inputs: {
parameters: [
{
name: 'project',
},
{
name: 'region',
},
{
name: 'name',
},
],
},
outputs: {},
metadata: {},
container: {
name: '',
image: 'gcr.io/ml-pipeline/ml-pipeline-dataproc-xgboost',
command: ['sh', '-c'],
args: [
// tslint:disable-next-line:max-line-length
'python /ml/delete_cluster.py --project {{inputs.parameters.project}} --region {{inputs.parameters.region}} --name {{inputs.parameters.name}}',
],
resources: {},
},
},
],
entrypoint: 'xgboost-training',
arguments: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'cluster',
value: 'xgboost-spark-{{workflow.name}}',
},
{
name: 'output',
value: 'gs://sample-xgbbost-cm-output',
},
{
name: 'train',
value: 'gs://ml-pipeline-playground/newsgroup/train.csv',
},
{
name: 'eval',
value: 'gs://ml-pipeline-playground/newsgroup/eval.csv',
},
{
name: 'schema',
value: 'gs://ml-pipeline-playground/newsgroup/schema.json',
},
{
name: 'target',
value: 'news_label',
},
{
name: 'package',
// tslint:disable-next-line:max-line-length
value:
'gs://ml-pipeline-playground/xgboost4j-example-0.8-SNAPSHOT-jar-with-dependencies.jar',
},
{
name: 'workers',
value: '2',
},
{
name: 'rounds',
value: '200',
},
{
name: 'conf',
value: 'gs://ml-pipeline-playground/trainconfcla.json ',
},
],
},
onExit: 'exit-handler',
},
status: {
phase: 'Succeeded',
startedAt: '2018-04-16T23:37:48Z',
finishedAt: '2018-04-17T00:12:01Z',
nodes: {
'xgboost-training-gzkm9': {
id: 'xgboost-training-gzkm9',
name: 'xgboost-training-gzkm9',
displayName: 'xgboost-training-gzkm9',
type: 'Steps',
templateName: 'xgboost-training',
phase: 'Succeeded',
startedAt: '2018-04-16T23:37:48Z',
finishedAt: '2018-04-17T00:10:06Z',
inputs: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'cluster',
value: 'xgboost-spark-xgboost-training-gzkm9',
},
{
name: 'output',
value: 'gs://sample-xgbbost-cm-output',
},
{
name: 'train',
value: 'gs://ml-pipeline-playground/newsgroup/train.csv',
},
{
name: 'eval',
value: 'gs://ml-pipeline-playground/newsgroup/eval.csv',
},
{
name: 'schema',
value: 'gs://ml-pipeline-playground/newsgroup/schema.json',
},
{
name: 'target',
value: 'news_label',
},
{
name: 'package',
// tslint:disable-next-line:max-line-length
value:
'gs://ml-pipeline-playground/xgboost4j-example-0.8-SNAPSHOT-jar-with-dependencies.jar',
},
{
name: 'workers',
value: '2',
},
{
name: 'rounds',
value: '200',
},
{
name: 'conf',
value: 'gs://ml-pipeline-playground/trainconfcla.json ',
},
],
},
children: [
'xgboost-training-gzkm9-4204210601',
'xgboost-training-gzkm9-916047540',
'xgboost-training-gzkm9-915503087',
'xgboost-training-gzkm9-982760658',
'xgboost-training-gzkm9-4204798981',
'xgboost-training-gzkm9-916635920',
],
outboundNodes: ['xgboost-training-gzkm9-2203328319'],
},
'xgboost-training-gzkm9-1253553084': {
id: 'xgboost-training-gzkm9-1253553084',
name: 'xgboost-training-gzkm9.onExit',
displayName: 'xgboost-training-gzkm9.onExit',
type: 'Steps',
templateName: 'exit-handler',
phase: 'Pending',
message:
'ImagePullBackOff: Back-off pulling image "gcr.io/ml-pipeline/ml-pipeline-dataproc-create-cluster"',
startedAt: '2018-04-17T00:10:06Z',
finishedAt: '2018-04-17T00:12:01Z',
inputs: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'cluster',
value: 'xgboost-spark-xgboost-training-gzkm9',
},
],
},
children: ['xgboost-training-gzkm9-3439262870'],
outboundNodes: ['xgboost-training-gzkm9-3721733163'],
},
'xgboost-training-gzkm9-1761585008': {
id: 'xgboost-training-gzkm9-1761585008',
name: 'xgboost-training-gzkm9[4].batchpredict',
displayName: 'batchpredict',
type: 'Pod',
templateName: 'batchpredict',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-17T00:08:06Z',
finishedAt: '2018-04-17T00:08:59Z',
inputs: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'cluster',
value: 'xgboost-spark-xgboost-training-gzkm9',
},
{
name: 'output',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/batchpredict',
},
{
name: 'eval',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/transform/eval/part-*',
},
{
name: 'model',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/model',
},
{
name: 'target',
value: 'news_label',
},
{
name: 'package',
// tslint:disable-next-line:max-line-length
value:
'gs://ml-pipeline-playground/xgboost4j-example-0.8-SNAPSHOT-jar-with-dependencies.jar',
},
{
name: 'analysis',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/analysis',
},
],
},
children: ['xgboost-training-gzkm9-916635920'],
},
'xgboost-training-gzkm9-2203328319': {
id: 'xgboost-training-gzkm9-2203328319',
name: 'xgboost-training-gzkm9[5].confusionmatrix',
displayName: 'confusionmatrix',
type: 'Pod',
templateName: 'confusionmatrix',
phase: 'Failed',
message: 'Mock backend could not schedule pod; no k8s implementation in Javascript (yet).',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-17T00:08:59Z',
finishedAt: '2018-04-17T00:10:06Z',
inputs: {
parameters: [
{
name: 'analysis',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/analysis',
},
{
name: 'predictions',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/batchpredict/part-*.csv',
},
{
name: 'target',
value: 'news_label',
},
],
},
outputs: {
artifacts: [
{
name: 'mlpipeline-ui-metadata',
s3: {
bucket: 'somebucket',
key: 'confusionmatrix',
},
},
],
},
},
'xgboost-training-gzkm9-2365787662': {
id: 'xgboost-training-gzkm9-2365787662',
name: 'xgboost-training-gzkm9[3].train',
displayName: 'train',
type: 'Pod',
templateName: 'train',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-16T23:49:28Z',
finishedAt: '2018-04-17T00:08:05Z',
inputs: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'cluster',
value: 'xgboost-spark-xgboost-training-gzkm9',
},
{
name: 'train',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/transform/train/part-*',
},
{
name: 'eval',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/transform/eval/part-*',
},
{
name: 'target',
value: 'news_label',
},
{
name: 'analysis',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/analysis',
},
{
name: 'package',
// tslint:disable-next-line:max-line-length
value:
'gs://ml-pipeline-playground/xgboost4j-example-0.8-SNAPSHOT-jar-with-dependencies.jar',
},
{
name: 'workers',
value: '2',
},
{
name: 'rounds',
value: '200',
},
{
name: 'conf',
value: 'gs://ml-pipeline-playground/trainconfcla.json ',
},
],
},
outputs: {
artifacts: [
{
name: 'mlpipeline-ui-metadata',
s3: {
bucket: 'somebucket',
key: 'model',
},
},
],
},
children: ['xgboost-training-gzkm9-4204798981'],
},
'xgboost-training-gzkm9-2411879589': {
id: 'xgboost-training-gzkm9-2411879589',
name: 'xgboost-training-gzkm9[0].createcluster',
displayName: 'createcluster',
type: 'Pod',
templateName: 'createcluster',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-16T23:37:49Z',
finishedAt: '2018-04-16T23:39:56Z',
inputs: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'name',
value: 'xgboost-spark-xgboost-training-gzkm9',
},
{
name: 'staging',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/staging',
},
],
},
children: ['xgboost-training-gzkm9-916047540'],
},
'xgboost-training-gzkm9-2457131397': {
id: 'xgboost-training-gzkm9-2457131397',
name: 'xgboost-training-gzkm9[2].transform',
displayName: 'transform',
type: 'Pod',
templateName: 'transform',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-16T23:41:24Z',
finishedAt: '2018-04-16T23:49:27Z',
inputs: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'cluster',
value: 'xgboost-spark-xgboost-training-gzkm9',
},
{
name: 'train',
value: 'gs://ml-pipeline-playground/newsgroup/train.csv',
},
{
name: 'eval',
value: 'gs://ml-pipeline-playground/newsgroup/eval.csv',
},
{
name: 'target',
value: 'news_label',
},
{
name: 'analysis',
value: 'gs://sample-xgbbost-cm-output/xgboost-training-gzkm9/analysis',
},
],
},
outputs: {
artifacts: [
{
name: 'mlpipeline-ui-metadata',
s3: {
bucket: 'somebucket',
key: 'transform',
},
},
],
},
children: ['xgboost-training-gzkm9-982760658'],
},
'xgboost-training-gzkm9-3439262870': {
id: 'xgboost-training-gzkm9-3439262870',
name: 'xgboost-training-gzkm9.onExit[0]',
displayName: '[0]',
type: 'StepGroup',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9-1253553084',
startedAt: '2018-04-17T00:10:06Z',
finishedAt: '2018-04-17T00:12:01Z',
children: ['xgboost-training-gzkm9-3721733163'],
},
'xgboost-training-gzkm9-3636935406': {
id: 'xgboost-training-gzkm9-3636935406',
name: 'xgboost-training-gzkm9[1].analyze',
displayName: 'analyze',
type: 'Pod',
templateName: 'analyze',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-16T23:39:56Z',
finishedAt: '2018-04-16T23:41:24Z',
inputs: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'cluster',
value: 'xgboost-spark-xgboost-training-gzkm9',
},
{
name: 'train',
value: 'gs://ml-pipeline-playground/newsgroup/train.csv',
},
{
name: 'schema',
value: 'gs://ml-pipeline-playground/newsgroup/schema.json',
},
],
},
outputs: {
artifacts: [
{
name: 'mlpipeline-ui-metadata',
s3: {
bucket: 'somebucket',
key: 'analysis',
},
},
],
},
children: ['xgboost-training-gzkm9-915503087'],
},
'xgboost-training-gzkm9-3721733163': {
id: 'xgboost-training-gzkm9-3721733163',
name: 'xgboost-training-gzkm9.onExit[0].deletecluster',
displayName: 'deletecluster',
type: 'Pod',
templateName: 'deletecluster',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9-1253553084',
startedAt: '2018-04-17T00:10:06Z',
finishedAt: '2018-04-17T00:12:01Z',
inputs: {
parameters: [
{
name: 'project',
value: 'ml-pipeline',
},
{
name: 'region',
value: 'us-central1',
},
{
name: 'name',
value: 'xgboost-spark-xgboost-training-gzkm9',
},
],
},
},
'xgboost-training-gzkm9-4204210601': {
id: 'xgboost-training-gzkm9-4204210601',
name: 'xgboost-training-gzkm9[0]',
displayName: '[0]',
type: 'StepGroup',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-16T23:37:48Z',
finishedAt: '2018-04-16T23:39:56Z',
children: ['xgboost-training-gzkm9-2411879589'],
},
'xgboost-training-gzkm9-4204798981': {
id: 'xgboost-training-gzkm9-4204798981',
name: 'xgboost-training-gzkm9[4]',
displayName: '[4]',
type: 'StepGroup',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-17T00:08:06Z',
finishedAt: '2018-04-17T00:08:59Z',
children: ['xgboost-training-gzkm9-1761585008'],
},
'xgboost-training-gzkm9-915503087': {
id: 'xgboost-training-gzkm9-915503087',
name: 'xgboost-training-gzkm9[2]',
displayName: '[2]',
type: 'StepGroup',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-16T23:41:24Z',
finishedAt: '2018-04-16T23:49:28Z',
children: ['xgboost-training-gzkm9-2457131397'],
},
'xgboost-training-gzkm9-916047540': {
id: 'xgboost-training-gzkm9-916047540',
name: 'xgboost-training-gzkm9[1]',
displayName: '[1]',
type: 'StepGroup',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-16T23:39:56Z',
finishedAt: '2018-04-16T23:41:24Z',
children: ['xgboost-training-gzkm9-3636935406'],
},
'xgboost-training-gzkm9-916635920': {
id: 'xgboost-training-gzkm9-916635920',
name: 'xgboost-training-gzkm9[5]',
displayName: '[5]',
type: 'StepGroup',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-17T00:08:59Z',
finishedAt: '2018-04-17T00:10:06Z',
children: ['xgboost-training-gzkm9-2203328319'],
},
'xgboost-training-gzkm9-982760658': {
id: 'xgboost-training-gzkm9-982760658',
name: 'xgboost-training-gzkm9[3]',
displayName: '[3]',
type: 'StepGroup',
phase: 'Succeeded',
boundaryID: 'xgboost-training-gzkm9',
startedAt: '2018-04-16T23:49:28Z',
finishedAt: '2018-04-17T00:08:06Z',
children: ['xgboost-training-gzkm9-2365787662'],
},
},
},
}; | the_stack |
import { ScaleLinear } from 'd3-scale';
import { assign } from 'lodash-es';
import {
SingleTrack,
Datum,
FilterTransform,
LogTransform,
ExonSplitTransform,
Assembly,
StrConcatTransform,
StrReplaceTransform,
GenomicLengthTransform,
CoverageTransform,
CombineMatesTransform,
DisplaceTransform,
JSONParseTransform
} from '../gosling.schema';
import {
getChannelKeysByAggregateFnc,
getChannelKeysByType,
IsChannelDeep,
IsIncludeFilter,
IsOneOfFilter,
IsRangeFilter
} from '../gosling.schema.guards';
import { GET_CHROM_SIZES } from './assembly';
// import Logging from './log';
/**
* Apply filter
*/
export function filterData(filter: FilterTransform, data: Datum[]): Datum[] {
const { field, not } = filter;
let output: Datum[] = Array.from(data);
if (IsOneOfFilter(filter)) {
const { oneOf } = filter;
output = output.filter((d: Datum) => {
return not ? (oneOf as any[]).indexOf(d[field]) === -1 : (oneOf as any[]).indexOf(d[field]) !== -1;
});
} else if (IsRangeFilter(filter)) {
const { inRange } = filter;
output = output.filter((d: Datum) => {
return not
? !(inRange[0] <= d[field] && d[field] <= inRange[1])
: inRange[0] <= d[field] && d[field] <= inRange[1];
});
} else if (IsIncludeFilter(filter)) {
const { include } = filter;
output = output.filter((d: Datum) => {
return not ? `${d[field]}`.includes(include) : !`${d[field]}`.includes(include);
});
}
return output;
}
/**
* Calculate new data, like log transformation.
*/
export function concatString(concat: StrConcatTransform, data: Datum[]): Datum[] {
const { fields, separator, newField } = concat;
let output: Datum[] = Array.from(data);
output = output.map(d => {
const strs = fields.map(f => d[f]);
d[newField] = strs.join(separator);
return d;
});
return output;
}
export function replaceString(_: StrReplaceTransform, data: Datum[]): Datum[] {
const { field, replace, newField } = _;
let output: Datum[] = Array.from(data);
output = output.map(d => {
d[newField] = d[field]; // copy original string
replace.forEach(r => {
const { from, to } = r;
d[newField] = d[newField].toString().replaceAll(from, to);
});
return d;
});
return output;
}
/**
* Calculate new data, like log transformation.
*/
export function calculateData(log: LogTransform, data: Datum[]): Datum[] {
const { field, base, newField } = log;
let output: Datum[] = Array.from(data);
output = output.map(d => {
if (+d[field]) {
if (base === 'e') {
d[newField ?? field] = Math.log(+d[field]);
} else {
d[newField ?? field] = Math.log(+d[field]) / Math.log(base ?? 10);
}
}
return d;
});
return output;
}
/**
* Calculate genomic length using two genomic fields.
*/
export function calculateGenomicLength(_: GenomicLengthTransform, data: Datum[]): Datum[] {
const { startField, endField, newField } = _;
const output = Array.from(data);
output.forEach(d => {
const s = d[startField];
const e = d[endField];
if (!s || !e) {
// such field does not exist, so skip this row
// console.warn(`[Genomic Length] startField or endField (${s} or ${e}) does not exist.`);
return;
}
d[newField] = Math.abs(+e - +s);
});
return output;
}
/**
* Aggregate data rows and calculate coverage of reads.
*/
export function aggregateCoverage(_: CoverageTransform, data: Datum[], scale: ScaleLinear<any, any>): Datum[] {
// Logging.recordTime('aggregateCoverage');
const { startField, endField, newField, groupField } = _;
const coverage: { [group: string]: { [position: string]: number } } = {};
// Calculate coverage by one pixel.
const binSize = 1;
data.forEach(d => {
const curStart = scale(d[startField] as number);
const curEnd = scale(d[endField] as number);
const group = groupField ? d[groupField] : '__NO_GROUP__';
const adjustedStart = Math.floor(curStart);
for (let i = adjustedStart; i < curEnd; i += binSize) {
if (!coverage[group]) {
coverage[group] = {};
}
if (!coverage[group][i]) {
coverage[group][i] = 0;
}
coverage[group][i]++;
}
});
const output = Object.entries(coverage).flatMap(group => {
const [groupName, coverageRecords] = group;
return Object.entries(coverageRecords).map(entry => {
const [key, value] = entry;
return {
[startField]: scale.invert(+key),
[endField]: scale.invert(+key + binSize),
[newField ?? 'coverage']: value,
[groupField ?? 'group']: groupName
};
});
});
// console.log(coverage);
// Logging.printTime('aggregateCoverage');
return output;
}
export function combineMates(t: CombineMatesTransform, data: Datum[]) {
const { idField, maintainDuplicates } = t;
const isLongField = t.isLongField ?? 'is_long';
const maxInsertSize = t.maxInsertSize ?? 360;
const copyData: { data: Datum; added: boolean }[] = data.map(d => {
return { data: d, added: false };
});
const output: Datum[] = [];
copyData.forEach((d, i) => {
if (d.added) {
// this row is added already, so just skip
return;
}
if (i === copyData.length - 1) {
// no additional reads to search for
return;
}
if (!d.data[idField]) {
// id does not exist
console.warn(`[CombineMates] The id field (${idField}) does not exist.`);
return;
}
const id = d.data[idField];
const rest = copyData.slice(maintainDuplicates ? 0 : i + 1, copyData.length).filter((_, j) => i !== j);
const mateIndex = rest.findIndex(r => r.data[idField] === id);
if (mateIndex === -1) {
// no mate found. this read will not be included to the result data.
return;
}
const mate = copyData[mateIndex];
const newRow: Datum = {};
// assuming that keys are the same for mates
Object.keys(d.data).forEach(k => {
// if not maintaining duplicated rows, left mate should be stored in the first field
const [f, s] = maintainDuplicates ? [d, mate] : [d, mate].sort((a, b) => +a.data.from - +b.data.from);
newRow[`${k}`] = f.data[k];
newRow[`${k}_2`] = s.data[k];
const [left, right] = [d, mate].sort((a, b) => +a.data.from - +b.data.from);
newRow[isLongField] = Math.abs(+left.data.to - +right.data.from) >= maxInsertSize ? 'true' : 'false';
});
output.push(newRow);
if (!maintainDuplicates) {
mate.added = true; // set a flag so that we can skip this later
}
});
return output;
}
export function displace(t: DisplaceTransform, data: Datum[], scale: ScaleLinear<any, any>): Datum[] {
// Logging.recordTime('displace()');
const { boundingBox, method, newField } = t;
const { startField, endField, groupField } = boundingBox;
let padding = 0; // This is a pixel value.
if (boundingBox.padding && scale && !boundingBox.isPaddingBP) {
padding = Math.abs(scale.invert(boundingBox.padding) - scale.invert(0));
} else if (boundingBox.padding && boundingBox.isPaddingBP) {
padding = boundingBox.padding;
}
// Check whether we have sufficient information.
const base = Array.from(data);
if (base && base.length > 0) {
if (!Object.keys(base[0]).find(d => d === startField) || !Object.keys(base[0]).find(d => d === endField)) {
// We did not find the fields from the data, so exit here.
return base;
}
}
if (method === 'pile') {
const oldAlgorithm = false;
if (oldAlgorithm) {
// This will be deprecated soon.
const { maxRows } = t;
const boundingBoxes: { start: number; end: number; row: number }[] = [];
base.sort((a: Datum, b: Datum) => (a[startField] as number) - (b[startField] as number)).forEach(
(d: Datum) => {
const start = (d[startField] as number) - padding;
const end = (d[endField] as number) + padding;
const overlapped = boundingBoxes.filter(
box =>
(box.start === start && end === box.end) ||
(box.start <= start && start < box.end) ||
(box.start < end && end <= box.end) ||
(start < box.start && box.end < end)
);
// find the lowest non overlapped row
const uniqueRows = [
...Array.from(new Set(boundingBoxes.map(d => d.row))),
Math.max(...boundingBoxes.map(d => d.row)) + 1
];
const overlappedRows = overlapped.map(d => d.row);
const lowestNonOverlappedRow = Math.min(
...uniqueRows.filter(d => overlappedRows.indexOf(d) === -1)
);
// row index starts from zero
const row: number = overlapped.length === 0 ? 0 : lowestNonOverlappedRow;
d[newField] = `${maxRows && maxRows <= row ? maxRows - 1 : row}`;
boundingBoxes.push({ start, end, row });
}
);
} else {
// This piling algorithm is heavily based on
// https://github.com/higlass/higlass-pileup/blob/8538a34c6d884c28455d6178377ee1ea2c2c90ae/src/bam-fetcher-worker.js#L626
const { maxRows } = t;
const occupiedSpaceInRows: { [group: string]: { start: number; end: number }[] } = {};
const sorted = base.sort((a: Datum, b: Datum) => (a[startField] as number) - (b[startField] as number));
sorted.forEach((d: Datum) => {
const start = (d[startField] as number) - padding;
const end = (d[endField] as number) + padding;
// Create object if none
const group = groupField ? d[groupField] : '__NO_GROUP__';
if (!occupiedSpaceInRows[group]) {
occupiedSpaceInRows[group] = [];
}
// Find a row to place this segment
let rowIndex = occupiedSpaceInRows[group].findIndex(d => {
// Find a space and update the occupancy info.
if (end < d.start) {
d.start = start;
return true;
} else if (d.end < start) {
d.end = end;
return true;
}
return false;
});
if (rowIndex === -1) {
// We did not find sufficient space from the existing rows, so add a new row.
occupiedSpaceInRows[group].push({ start, end });
rowIndex = occupiedSpaceInRows[group].length - 1;
}
d[newField] = `${maxRows && maxRows <= rowIndex ? maxRows - 1 : rowIndex}`;
});
}
} else if (method === 'spread') {
const boundingBoxes: { start: number; end: number }[] = [];
base.sort((a: Datum, b: Datum) => (a[startField] as number) - (b[startField] as number)).forEach((d: Datum) => {
let start = (d[startField] as number) - padding;
let end = (d[endField] as number) + padding;
let overlapped = boundingBoxes.filter(
box =>
(box.start === start && end === box.end) ||
(box.start < start && start < box.end) ||
(box.start < end && end < box.end) ||
(start < box.start && box.end < end)
);
if (overlapped.length > 0) {
let trial = 0;
do {
overlapped = boundingBoxes.filter(
box =>
(box.start === start && end === box.end) ||
(box.start < start && start < box.end) ||
(box.start < end && end < box.end) ||
(start < box.start && box.end < end)
);
if (overlapped.length > 0) {
if (trial % 2 === 0) {
start += padding * trial;
end += padding * trial;
} else {
start -= padding * trial;
end -= padding * trial;
}
}
trial++;
// TODO: do not go outside of a tile.
} while (overlapped.length > 0 && trial < 1000);
}
d[`${newField}Start`] = `${start + padding}`;
d[`${newField}Etart`] = `${end - padding}`;
boundingBoxes.push({ start, end });
});
}
// Logging.printTime('displace()');
return base;
}
export function splitExon(split: ExonSplitTransform, data: Datum[], assembly: Assembly = 'hg38'): Datum[] {
const { separator, fields, flag } = split;
let output: Datum[] = Array.from(data);
output = output
.map((d: Datum) => {
const newRows: Datum[] = [];
fields.forEach(f => {
const { field, type, newField, chrField } = f;
const splitted = d[field].toString().split(separator);
splitted.forEach((s, i) => {
let newValue: string | number = s;
if (type === 'genomic') {
newValue = GET_CHROM_SIZES(assembly).interval[d[chrField]][0] + +s;
}
if (!newRows[i]) {
// No row exist, so create one.
newRows[i] = assign(JSON.parse(JSON.stringify(d)), {
[newField]: newValue,
[flag.field]: flag.value
});
} else {
newRows[i][newField] = newValue;
}
});
});
return [d, ...newRows];
})
.reduce((a, b) => a.concat(b), []);
return output;
}
// TODO: Get this data from the fetcher as a default with a flag variable.
export function parseSubJSON(_: JSONParseTransform, data: Datum[]): Datum[] {
const { field, genomicField, baseGenomicField, genomicLengthField } = _;
let output: Datum[] = Array.from(data);
output = output
.map((d: Datum) => {
let newRows: Datum[] = JSON.parse(d[field] as string);
newRows = newRows.map(row => {
if (row[genomicField] && d[baseGenomicField]) {
row[`${genomicField}_start`] = +row[genomicField] + +d[baseGenomicField];
row[`${genomicField}_end`] = +row[genomicField] + +d[baseGenomicField] + +row[genomicLengthField];
}
return assign(JSON.parse(JSON.stringify(d)), {
...row,
[`${genomicField}_start`]: row[`${genomicField}_start`],
[`${genomicField}_end`]: row[`${genomicField}_end`],
type: row.type ?? row.variant ?? null,
isParsedRow: 'yes'
});
});
return [d, ...newRows];
})
.reduce((a, b) => a.concat(b), []);
return output;
}
/**
* Experimental! Only support one category supported yet.
*/
export function aggregateData(spec: SingleTrack, data: Datum[]): Datum[] {
if (getChannelKeysByAggregateFnc(spec).length === 0) {
// we do not have aggregated fields
return data;
}
const nChannelKeys = getChannelKeysByType(spec, 'nominal');
if (nChannelKeys.length !== 1) {
console.warn('Currently, we only support aggregating datasets with single nominal field.');
return data;
}
const nFieldSpec = spec[nChannelKeys[0]];
if (!IsChannelDeep(nFieldSpec)) {
// this shouldn't be reached
return data;
}
const nField = nFieldSpec.field;
if (!nField) {
// this shouldn't be reached
return data;
}
const qChannelKeys = [...getChannelKeysByType(spec, 'quantitative'), ...getChannelKeysByType(spec, 'genomic')];
const aggregated: { [k: string]: number | string }[] = [];
const uniqueCategories = Array.from(new Set(data.map(d => d[nField])));
let failed = false;
uniqueCategories.forEach(c => {
const datum: { [k: string]: string | number } = {};
datum[nField] = c;
// for each quantitative fields
qChannelKeys.forEach(q => {
const qFieldSpec = spec[q];
if (!IsChannelDeep(qFieldSpec)) {
// this shouldn't be reached
failed = true;
return;
}
const { field: qField } = qFieldSpec;
if (!qField || !('aggregate' in qFieldSpec)) {
// this shouldn't be reached
failed = true;
return;
}
datum[qField] =
qFieldSpec.aggregate === 'max'
? Math.max(...data.filter(d => d[nField] === c).map(d => +d[qField]))
: Math.min(...data.filter(d => d[nField] === c).map(d => +d[qField]));
});
aggregated.push(datum);
});
// set aggregated data only if we successfully generated it
return !failed ? aggregated : data;
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A CaPool represents a group of CertificateAuthorities that form a trust anchor. A CaPool can be used to manage
* issuance policies for one or more CertificateAuthority resources and to rotate CA certificates in and out of the
* trust anchor.
*
* ## Example Usage
* ### Privateca Capool Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const defaultCaPool = new gcp.certificateauthority.CaPool("default", {
* labels: {
* foo: "bar",
* },
* location: "us-central1",
* publishingOptions: {
* publishCaCert: true,
* publishCrl: true,
* },
* tier: "ENTERPRISE",
* });
* ```
* ### Privateca Capool All Fields
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const defaultCaPool = new gcp.certificateauthority.CaPool("default", {
* issuancePolicy: {
* allowedIssuanceModes: {
* allowConfigBasedIssuance: true,
* allowCsrBasedIssuance: true,
* },
* allowedKeyTypes: [
* {
* ellipticCurve: {
* signatureAlgorithm: "ECDSA_P256",
* },
* },
* {
* rsa: {
* maxModulusSize: "10",
* minModulusSize: "5",
* },
* },
* ],
* baselineValues: {
* additionalExtensions: [{
* critical: true,
* objectId: {
* objectIdPaths: [
* 1,
* 7,
* ],
* },
* value: "asdf",
* }],
* aiaOcspServers: ["example.com"],
* caOptions: {
* isCa: true,
* maxIssuerPathLength: 10,
* },
* keyUsage: {
* baseKeyUsage: {
* certSign: false,
* contentCommitment: true,
* crlSign: true,
* dataEncipherment: true,
* decipherOnly: true,
* digitalSignature: true,
* keyAgreement: true,
* keyEncipherment: false,
* },
* extendedKeyUsage: {
* clientAuth: false,
* codeSigning: true,
* emailProtection: true,
* serverAuth: true,
* timeStamping: true,
* },
* },
* policyIds: [
* {
* objectIdPaths: [
* 1,
* 5,
* ],
* },
* {
* objectIdPaths: [
* 1,
* 5,
* 7,
* ],
* },
* ],
* },
* identityConstraints: {
* allowSubjectAltNamesPassthrough: true,
* allowSubjectPassthrough: true,
* celExpression: {
* expression: "subject_alt_names.all(san, san.type == DNS || san.type == EMAIL )",
* title: "My title",
* },
* },
* maximumLifetime: "50000s",
* },
* labels: {
* foo: "bar",
* },
* location: "us-central1",
* publishingOptions: {
* publishCaCert: false,
* publishCrl: true,
* },
* tier: "ENTERPRISE",
* });
* ```
*
* ## Import
*
* CaPool can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:certificateauthority/caPool:CaPool default projects/{{project}}/locations/{{location}}/caPools/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:certificateauthority/caPool:CaPool default {{project}}/{{location}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:certificateauthority/caPool:CaPool default {{location}}/{{name}}
* ```
*/
export class CaPool extends pulumi.CustomResource {
/**
* Get an existing CaPool resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: CaPoolState, opts?: pulumi.CustomResourceOptions): CaPool {
return new CaPool(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:certificateauthority/caPool:CaPool';
/**
* Returns true if the given object is an instance of CaPool. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is CaPool {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === CaPool.__pulumiType;
}
/**
* The IssuancePolicy to control how Certificates will be issued from this CaPool.
* Structure is documented below.
*/
public readonly issuancePolicy!: pulumi.Output<outputs.certificateauthority.CaPoolIssuancePolicy | undefined>;
/**
* Labels with user-defined metadata.
* An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass":
* "1.3kg", "count": "3" }.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* String indicating the location of the expression for error reporting, e.g. a file name and a position in the file.
*/
public readonly location!: pulumi.Output<string>;
/**
* The name for this CaPool.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* The PublishingOptions to follow when issuing Certificates from any CertificateAuthority in this CaPool.
* Structure is documented below.
*/
public readonly publishingOptions!: pulumi.Output<outputs.certificateauthority.CaPoolPublishingOptions | undefined>;
/**
* The Tier of this CaPool.
* Possible values are `ENTERPRISE` and `DEVOPS`.
*/
public readonly tier!: pulumi.Output<string>;
/**
* Create a CaPool resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: CaPoolArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: CaPoolArgs | CaPoolState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as CaPoolState | undefined;
inputs["issuancePolicy"] = state ? state.issuancePolicy : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["publishingOptions"] = state ? state.publishingOptions : undefined;
inputs["tier"] = state ? state.tier : undefined;
} else {
const args = argsOrState as CaPoolArgs | undefined;
if ((!args || args.location === undefined) && !opts.urn) {
throw new Error("Missing required property 'location'");
}
if ((!args || args.tier === undefined) && !opts.urn) {
throw new Error("Missing required property 'tier'");
}
inputs["issuancePolicy"] = args ? args.issuancePolicy : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["publishingOptions"] = args ? args.publishingOptions : undefined;
inputs["tier"] = args ? args.tier : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(CaPool.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering CaPool resources.
*/
export interface CaPoolState {
/**
* The IssuancePolicy to control how Certificates will be issued from this CaPool.
* Structure is documented below.
*/
issuancePolicy?: pulumi.Input<inputs.certificateauthority.CaPoolIssuancePolicy>;
/**
* Labels with user-defined metadata.
* An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass":
* "1.3kg", "count": "3" }.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* String indicating the location of the expression for error reporting, e.g. a file name and a position in the file.
*/
location?: pulumi.Input<string>;
/**
* The name for this CaPool.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The PublishingOptions to follow when issuing Certificates from any CertificateAuthority in this CaPool.
* Structure is documented below.
*/
publishingOptions?: pulumi.Input<inputs.certificateauthority.CaPoolPublishingOptions>;
/**
* The Tier of this CaPool.
* Possible values are `ENTERPRISE` and `DEVOPS`.
*/
tier?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a CaPool resource.
*/
export interface CaPoolArgs {
/**
* The IssuancePolicy to control how Certificates will be issued from this CaPool.
* Structure is documented below.
*/
issuancePolicy?: pulumi.Input<inputs.certificateauthority.CaPoolIssuancePolicy>;
/**
* Labels with user-defined metadata.
* An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass":
* "1.3kg", "count": "3" }.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* String indicating the location of the expression for error reporting, e.g. a file name and a position in the file.
*/
location: pulumi.Input<string>;
/**
* The name for this CaPool.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The PublishingOptions to follow when issuing Certificates from any CertificateAuthority in this CaPool.
* Structure is documented below.
*/
publishingOptions?: pulumi.Input<inputs.certificateauthority.CaPoolPublishingOptions>;
/**
* The Tier of this CaPool.
* Possible values are `ENTERPRISE` and `DEVOPS`.
*/
tier: pulumi.Input<string>;
} | the_stack |
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneToggle,
PropertyPaneLabel,
PropertyPaneChoiceGroup
} from '@microsoft/sp-property-pane';
import * as strings from 'EnhancedPowerAppsWebPartStrings';
import EnhancedPowerApps from './components/EnhancedPowerApps';
import { IEnhancedPowerAppsProps } from './components/IEnhancedPowerAppsProps';
/**
* Use this for dynamic properties
*/
import { DynamicProperty } from '@microsoft/sp-component-base';
/**
* Plain old boring web part thingies
*/
import {
BaseClientSideWebPart,
IWebPartPropertiesMetadata,
PropertyPaneDynamicFieldSet,
PropertyPaneDynamicField
} from '@microsoft/sp-webpart-base';
/**
* Use this for theme awareness
*/
import {
ThemeProvider,
ThemeChangedEventArgs,
IReadonlyTheme
} from '@microsoft/sp-component-base';
/**
* Use the multi-select for large checklists
*/
import { PropertyFieldMultiSelect } from '@pnp/spfx-property-controls/lib/PropertyFieldMultiSelect';
import { ThemeVariantSlots } from './ThemeVariantSlots';
import { PropertyPaneHTML } from '../../controls/PropertyPaneHTML/PropertyPaneHTML';
/**
* Super-cool text functions included in SPFx that people don't use often enough
*/
import { Text } from '@microsoft/sp-core-library';
export interface IEnhancedPowerAppsWebPartProps {
dynamicProp: DynamicProperty<string>;
appWebLink: string;
useDynamicProp: boolean;
dynamicPropName: string;
border: boolean;
layout: 'FixedHeight'|'AspectRatio';
height: number;
width: number;
aspectratio: '16:9'|'3:2'|'16:10'|'4:3'|'Custom';
themeValues: string[];
}
export default class EnhancedPowerAppsWebPart extends BaseClientSideWebPart<IEnhancedPowerAppsWebPartProps> {
private _themeProvider: ThemeProvider;
private _themeVariant: IReadonlyTheme | undefined;
protected onInit(): Promise<void> {
// Consume the new ThemeProvider service
this._themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
// If it exists, get the theme variant
this._themeVariant = this._themeProvider.tryGetTheme();
// Register a handler to be notified if the theme variant changes
this._themeProvider.themeChangedEvent.add(this, this._handleThemeChangedEvent);
return super.onInit();
}
public render(): void {
// Context variables and dynamic properties
const dynamicProp: string | undefined = this.properties.dynamicProp.tryGetValue();
const locale: string = this.context.pageContext.cultureInfo.currentCultureName;
// Get the client width. This is how we'll calculate the aspect ratio and resize the iframe
const { clientWidth } = this.domElement;
// Get the aspect width and height based on aspect ratio for the web part
let aspectWidth: number;
let aspectHeight: number;
switch(this.properties.aspectratio) {
case "16:10":
aspectWidth = 16;
aspectHeight = 10;
break;
case "16:9":
aspectWidth = 16;
aspectHeight = 9;
break;
case "3:2":
aspectWidth = 3;
aspectHeight = 2;
break;
case "4:3":
aspectWidth = 4;
aspectHeight = 3;
break;
case "Custom":
// Custom aspects just use the width and height properties
aspectWidth = this.properties.width;
aspectHeight = this.properties.height;
}
// If we're using fixed height, we pass the height and don't resize, otherwise we
// calculate the height based on the web part's width and selected aspect ratio
const clientHeight: number = this.properties.layout === 'FixedHeight' ?
this.properties.height :
clientWidth * (aspectHeight/aspectWidth);
const element: React.ReactElement<IEnhancedPowerAppsProps> = React.createElement(
EnhancedPowerApps,
{
locale: locale,
dynamicProp: dynamicProp,
useDynamicProp: this.properties.useDynamicProp,
dynamicPropName: this.properties.dynamicPropName,
onConfigure: this._onConfigure,
appWebLink: this.properties.appWebLink,
width: clientWidth,
height: clientHeight,
themeVariant: this._themeVariant,
border: this.properties.border,
themeValues: this.properties.themeValues
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
displayGroupsAsAccordion: true,
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
isCollapsed: false,
groupFields: [
PropertyPaneTextField('appWebLink', {
label: strings.AppWebLinkFieldLabel
})
]
},
{
groupName: strings.AppearanceGroupName,
isCollapsed: true,
groupFields: [
PropertyPaneToggle('border', {
label: strings.BorderFieldLabel
}),
PropertyPaneChoiceGroup('layout', {
label: strings.LayoutFieldLabel,
options: [
{
key: 'FixedHeight',
text: strings.LayoutFixedHeightOption,
iconProps: {
officeFabricIconFontName: 'FullWidth'
}
},
{
key: 'AspectRatio',
text: strings.LayoutAspectRatioOption,
iconProps: {
officeFabricIconFontName: 'AspectRatio'
}
}
]
}),
this.properties.layout === "FixedHeight" && PropertyPaneTextField('height', {
label: strings.HeightFieldLabel
}),
this.properties.layout === "AspectRatio" && PropertyPaneChoiceGroup('aspectratio', {
label: strings.AspectRatioFieldLabel,
options: [
{
key: '16:9',
text: '16:9',
},
{
key: '3:2',
text: '3:2',
},
{
key: '16:10',
text: '16:10',
},
{
key: '4:3',
text: '4:3',
},
{
key: 'Custom',
text: strings.AspectRatioCustomOption,
}
]
}),
this.properties.layout === "AspectRatio" && this.properties.aspectratio === "Custom" && PropertyPaneTextField('width', {
label: strings.WidthFieldLabel,
}),
this.properties.layout === "AspectRatio" && this.properties.aspectratio === "Custom" && PropertyPaneTextField('height', {
label: strings.HeightFieldLabel,
}),
]
},
{
groupName: strings.DynamicPropertiesGroupLabel,
isCollapsed: true,
groupFields: [
PropertyPaneHTML({
key: 'useDynamicProp',
html: Text.format(strings.DynamicsPropsGroupDescription1, this.properties.dynamicPropName!== undefined ?this.properties.dynamicPropName:'parametername')
}),
PropertyPaneHTML({
key: 'useDynamicProp',
html: strings.DynamicsPropsGroupDescription2
}),
PropertyPaneToggle('useDynamicProp', {
checked: this.properties.useDynamicProp === true,
label: strings.UseDynamicPropsFieldLabel
}),
this.properties.useDynamicProp === true && PropertyPaneDynamicFieldSet({
label: strings.SelectDynamicSource,
fields: [
PropertyPaneDynamicField('dynamicProp', {
label: strings.DynamicPropFieldLabel
})
]
}),
this.properties.useDynamicProp === true && PropertyPaneTextField('dynamicPropName', {
label: strings.DynamicPropsNameFieldLabel,
description: strings.DynamicsPropNameDescriptionLabel,
value: this.properties.dynamicPropName
})
]
},
{
groupName: strings.ThemeGroupName,
isCollapsed: true,
groupFields: [
PropertyPaneLabel('themeValuesPre',{
text: strings.ThemeValuePreLabel
}),
PropertyFieldMultiSelect('themeValues', {
key: 'multithemeValuesSelect',
label: strings.ThemeValueFieldLabel,
options: ThemeVariantSlots,
selectedKeys: this.properties.themeValues
}),
PropertyPaneHTML({
key: 'themeValuesPost',
html: strings.ThemeValuePostLabel
}),
]
}
]
}
]
};
}
protected get propertiesMetadata(): IWebPartPropertiesMetadata {
return {
// Specify the web part properties data type to allow the address
// information to be serialized by the SharePoint Framework.
'dynamicProp': {
dynamicPropertyType: 'string'
}
};
}
private _onConfigure = (): void => {
this.context.propertyPane.open();
}
/**
* Update the current theme variant reference and re-render.
*
* @param args The new theme
*/
private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void {
this._themeVariant = args.theme;
this.render();
}
/**
* Redraws the web part when resized
* @param _newWidth
*/
protected onAfterResize(_newWidth: number): void {
// redraw the web part
this.render();
}
} | the_stack |
import * as Fs from 'fs-extra';
import * as Minimist from 'minimist';
import * as Path from 'path';
import { Git } from './git';
import { localStorage as LocalStorage } from './local-storage';
import { Paths } from './paths';
import { Step } from './step';
import { Utils } from './utils';
/**
This is the editor for interactive rebases and amended commits. Instead of opening
an editing software like 'nano' or 'vim', this module will edit the file by specified
methods we choose.
*/
function init() {
if (require.main !== module) {
return;
}
const argv = Minimist(process.argv.slice(2), {
string: ['_', 'message', 'm', 'udiff'],
});
// The first argument will be the rebase file path provided to us by git
const method = argv._[0];
const steps = argv._.slice(1, -1);
const rebaseFilePath = argv._[argv._.length - 1];
// This method doesn't require us to parse operations, it just resets todo from a string
if (method === 'reset-todo') {
const todo = new LocalStorage.native(Paths.rebaseStates).getItem('TODO');
Fs.writeFileSync(rebaseFilePath, todo);
return;
}
const message = argv.message || argv.m;
const udiff = argv.udiff;
// Rebase file path will always be appended at the end of the arguments vector,
// therefore udiff has to have a value, otherwise it will be matched with the wrong
// argument
const options = {
udiff: udiff === 'true' ? '' : udiff,
};
const rebaseFileContent = Fs.readFileSync(rebaseFilePath, 'utf8');
// Convert to array of jsons so it would be more comfortable to word with
const operations = disassemblyOperations(rebaseFileContent);
// Set flag just in case recent rebase was aborted
LocalStorage.removeItem('REBASE_HOOKS_DISABLED');
// Automatically invoke a method by the provided arguments.
// The methods will manipulate the operations array.
switch (method) {
case 'edit':
editStep(operations, steps, options);
break;
case 'edit-head':
editHead(operations);
break;
case 'sort':
sortSteps(operations, options);
break;
case 'reword':
rewordStep(operations, message);
break;
case 'render':
renderManuals(operations);
break;
}
// Put everything back together and rewrite the rebase file
const newRebaseFileContent = assemblyOperations(operations);
Fs.writeFileSync(rebaseFilePath, newRebaseFileContent);
}
init();
// Edit the last step in the rebase file
function editStep(operations, steps, options) {
// Create initial step map
// Note that udiff is a string, since it may very well specify a module path
if (options.udiff != null) {
// Providing pending flag
Step.initializeStepMap(!!options.udiff);
}
if (!steps || steps.length === 0) {
const descriptor = Step.descriptor(operations[0].message);
const step = (descriptor && descriptor.number) || 'root';
steps = [step];
}
// This way we can store data on each step string
// We have to keep it as `new String` and not `String`!
/* tslint:disable-next-line */
steps = steps.map((step) => new String(step));
// Edit each commit which is relevant to the specified steps
steps.forEach((step) => {
if (String(step) === 'root') {
const operation = operations[0];
operation.method = 'edit';
step.operation = operation;
} else {
const operation = operations.find(({ message }) => {
if (!message) { return; }
const descriptor = Step.descriptor(message);
return descriptor && descriptor.number === String(step);
});
if (!operation) { return; }
operation.method = 'edit';
step.operation = operation;
}
});
// Probably editing the recent step in which case no sorts are needed
if (operations.length > 1) {
// Prepare meta-data for upcoming sorts
const descriptor = Step.descriptor(operations[0].message);
// Step exists
if (descriptor) {
LocalStorage.setItem('REBASE_OLD_STEP', descriptor.number);
LocalStorage.setItem('REBASE_NEW_STEP', descriptor.number);
} else {
LocalStorage.setItem('REBASE_OLD_STEP', 'root');
LocalStorage.setItem('REBASE_NEW_STEP', 'root');
}
// Building sort command
let sort = `node ${Paths.tortilla.editor} sort`;
if (options.udiff) {
sort = `${sort} --udiff=${options.udiff}`;
}
sort = `GIT_SEQUENCE_EDITOR="${sort}"`;
const saveRebaseState = `GIT_SEQUENCE_EDITOR="node ${Paths.tortilla.rebase} stash-rebase-state"`;
// Continue sorting the steps after step editing has been finished
steps.forEach((step) => {
const operation = step.operation;
if (!operation) { return; }
const index = operations.indexOf(operation);
// Insert the following operation AFTER the step's operation
operations.splice(index + 1, 0, {
method: 'exec',
command: `${sort} git rebase --edit-todo`,
});
// Insert the following operation BEFORE the step's operation
operations.splice(index, 0, {
method: 'exec',
command: `${saveRebaseState} git rebase --edit-todo`,
});
});
}
// Whether we edit the most recent step or not, rebranching process should be initiated
const rebranchSuper = `GIT_SEQUENCE_EDITOR="node ${Paths.tortilla.rebase} rebranch-super"`;
// After rebase has finished, update the brancehs referencing the super steps
operations.push({
method: 'exec',
command: `${rebranchSuper} git rebase --edit-todo`,
});
}
// Adjusts upcoming step numbers in rebase
function sortSteps(operations, options) {
// Grab meta-data
const oldStep = LocalStorage.getItem('REBASE_OLD_STEP');
const newStep = LocalStorage.getItem('REBASE_NEW_STEP');
const submoduleCwd = LocalStorage.getItem('SUBMODULE_CWD');
// If delta is 0 no sorts are needed
if (oldStep === newStep) {
LocalStorage.setItem('REBASE_HOOKS_DISABLED', 1);
// Escape unless we need to update stepDiffs for submodules
if (!submoduleCwd) { return; }
}
const stepLimit = getStepLimit(oldStep, newStep);
let editFlag = false;
let offset = 0;
operations.slice().some((operation, index) => {
const currStepDescriptor = Step.descriptor(operation.message || '');
// Skip commits which are not step commits
if (!currStepDescriptor) {
return;
}
const currStepSplit = currStepDescriptor.number.split('.');
const currSuperStep = currStepSplit[0];
const currSubStep = currStepSplit[1];
if (submoduleCwd) {
// If this is a super step, replace pick operation with the super pick
if (!currSubStep) {
operations.splice(index + offset, 1, {
method: 'exec',
command: `node ${Paths.tortilla.rebase} super-pick ${operation.hash}`,
});
}
} else if (currSuperStep > stepLimit) {
// Prepend local storage item setting operation, this would be a flag which will be
// used in git-hooks
operations.splice(index + offset++, 0, {
method: 'exec',
command: `node ${Paths.tortilla.localStorage} set REBASE_HOOKS_DISABLED 1`,
});
// Abort operations loop
return true;
}
// If this is a super step, replace pick operation with the super pick
if (!currSubStep) {
operations.splice(index + offset, 1, {
method: 'exec',
command: `node ${Paths.tortilla.rebase} super-pick ${operation.hash}`,
});
}
// If another step edit is pending, we will first perform the reword and only then
// we will proceed to the editing itself, since we wanna ensure that all the previous
// step indexes are already sorted
if (operation.method === 'edit') {
// Pick BEFORE edit
operations.splice(index + offset++, 0, {
...operation,
method: 'pick',
});
// Update commit's step number
operations.splice(index + offset++, 0, {
method: 'exec',
command: `GIT_EDITOR=true node ${Paths.tortilla.rebase} reword`,
});
const editor = `GIT_SEQUENCE_EDITOR="node ${Paths.tortilla.editor} edit-head"`;
// Replace edited step with the reworded one
operations.splice(index + offset++, 0, {
method: 'exec',
command: `${editor} git rebase --edit-todo`,
});
operations.splice(index + offset, 1);
// The sorting process should continue after we've finished editing the step, for now
// we will need to abort the current sorting process
return editFlag = true;
}
// Update commit's step number
operations.splice(index + ++offset, 0, {
method: 'exec',
command: `GIT_EDITOR=true node ${Paths.tortilla.rebase} reword`,
});
});
// Remove hooks storage items so it won't affect post-rebase operations, but only if
// there are no any further step edits pending
if (!editFlag) {
operations.push({
method: 'exec',
command: `node ${Paths.tortilla.localStorage} remove HOOK_STEP`,
});
// If specified udiff is a path to another tortilla repo
if (options.udiff) {
const subCwd = Utils.cwd();
const cwd = Path.resolve(Utils.cwd(), options.udiff);
// Update the specified repo's manual files
// Note that TORTILLA_CHILD_PROCESS and TORTILLA_CWD flags are set to
// prevent external interventions, mostly because of tests
operations.push({
method: 'exec',
command: Utils.shCmd(`
export GIT_DIR=${cwd}/.git
export GIT_WORK_TREE=${cwd}
export TORTILLA_CHILD_PROCESS=true
export TORTILLA_CWD=${cwd}
export TORTILLA_SUBMODULE_CWD=${subCwd}
if node ${Paths.cli.tortilla} step edit --root ; then
git rebase --continue
else
git rebase --abort
fi
`),
});
}
// Ensure step map is being disposed
operations.push({
method: 'exec',
command: `node ${Paths.tortilla.localStorage} remove STEP_MAP STEP_MAP_PENDING`,
});
}
}
// Edit the commit which is presented as the current HEAD
function editHead(operations) {
// Prepare meta-data for upcoming sorts
const descriptor = Step.descriptor(operations[0].message);
// Descriptor should always exist, but just in case
if (descriptor) {
LocalStorage.setItem('REBASE_OLD_STEP', descriptor.number);
}
const head = Git.recentCommit(['--format=%h m']).split(' ');
const hash = head.shift();
const message = head.join(' ');
// Remove head commit so there won't be any conflicts
operations.push({
method: 'exec',
command: 'git reset --hard HEAD~1',
});
// Re-pick and edit head commit
operations.push({
method: 'edit',
hash,
message,
});
}
// Reword the last step in the rebase file
function rewordStep(operations, message) {
const argv = [Paths.tortilla.rebase, 'reword'];
if (message) {
argv.push(`"${message}"`);
}
// Replace original message with the provided message
operations.splice(1, 0, {
method: 'exec',
command: `node ${argv.join(' ')}`,
});
}
// Render all manuals since the beginning of history to the opposite format
function renderManuals(operations) {
let offset = 2;
// Render README.md
operations.splice(1, 0, {
method: 'exec',
command: `node ${Paths.tortilla.manual} render --root`,
});
operations.slice(offset).forEach((operation, index) => {
const stepDescriptor = Step.superDescriptor(operation.message);
if (!stepDescriptor) {
return;
}
// Render step manual file
operations.splice(index + ++offset, 0, {
method: 'exec',
command: `node ${Paths.tortilla.manual} render ${stepDescriptor.number}`,
});
return offset;
});
// Re-adjust branch references since hash values are outdated at this point
operations.push({
method: 'exec',
command: `node ${Paths.tortilla.rebase} rebranch-super`,
});
}
// The step limit of which sorts are needed would be determined by the step
// which is greater
function getStepLimit(oldStep, newStep) {
oldStep = oldStep === 'root' ? '0' : oldStep;
let newSuperStep = newStep === 'root' ? '0' : newStep;
// Grabbing step splits for easy access
const oldStepSplits = oldStep.split('.');
const newStepSplits = newStep.split('.');
const oldSuperStep = oldStepSplits[0];
newSuperStep = newStepSplits[0];
const oldSubStep = oldStepSplits[1];
const newSubStep = newStepSplits[1];
if (oldSuperStep === newSuperStep) {
// 1.1, 1.2 or 1.2, 1.1 or 1.1 or 1.1, 1
if (oldSubStep) {
return oldSuperStep;
}
// 1, 1.1
return Infinity;
}
// 1, 2.1
if (!oldSubStep && newSubStep && Number(newSuperStep) === Number(oldSuperStep) + 1) {
return newSuperStep;
}
// 2.1, 1
if (!newSubStep && oldSubStep && Number(oldSuperStep) === Number(newSuperStep) + 1) {
return oldSuperStep;
}
// 1, 2 or 1, 3.1 or 1.1, 2.1 or 1.1, 2
return Infinity;
}
// Convert rebase file content to operations array
function disassemblyOperations(rebaseFileContent) {
const operations = rebaseFileContent.match(/^[a-z]+\s.{7}.*$/mg);
if (!operations) {
return [];
}
return operations.map((line) => {
const split = line.split(' ');
return {
method: split[0],
hash: split[1],
message: split.slice(2).join(' '),
};
});
}
// Convert operations array to rebase file content
function assemblyOperations(operations) {
return operations
// Compose lines
.map((operation) => Object
.keys(operation)
.map((k) => operation[k])
.join(' '),
)
// Connect lines
.join('\n') + '\n';
} | the_stack |
import React from "react";
import { WebBundlr } from "@bundlr-network/client"
import BigNumber from "bignumber.js";
import { Button } from "@chakra-ui/button";
import { Input, HStack, Text, VStack, useToast, Menu, MenuButton, MenuList, MenuItem, Tooltip } from "@chakra-ui/react";
import { ChevronDownIcon } from "@chakra-ui/icons"
import WalletConnectProvider from "@walletconnect/web3-provider";
import { providers } from "ethers"
import { Web3Provider } from "@ethersproject/providers";
// import { PhantomWalletAdapter } from "@solana/wallet-adapter-phantom"
import * as nearAPI from "near-api-js"
import { WalletConnection } from "near-api-js";
const { keyStores, connect } = nearAPI;
declare var window: any // TODO: specifically extend type to valid injected objects.
function App() {
const defaultCurrency = "Select a Currency"
const defaultSelection = "Select a Provider"
const [currency, setCurrency] = React.useState<string>(defaultCurrency);
const [address, setAddress] = React.useState<string>();
const [selection, setSelection] = React.useState<string>(defaultSelection);
const [balance, setBalance] = React.useState<string>();
const [img, setImg] = React.useState<Buffer>();
const [price, setPrice] = React.useState<BigNumber>();
const [bundler, setBundler] = React.useState<WebBundlr>();
const [bundlerHttpAddress, setBundlerAddress] = React.useState<string>(
"https://node1.bundlr.network"
);
const [fundAmount, setFundingAmount] = React.useState<string>();
const [withdrawAmount, setWithdrawAmount] = React.useState<string>();
const [provider, setProvider] = React.useState<Web3Provider>();
const toast = useToast();
const intervalRef = React.useRef<number>();
const clean = async () => {
clearInterval(intervalRef.current)
setBalance(undefined);
setImg(undefined);
setPrice(undefined);
setBundler(undefined);
setProvider(undefined);
setAddress(undefined);
setCurrency(defaultCurrency);
setSelection(defaultSelection);
}
const handleFileClick = () => {
var fileInputEl = document.createElement("input");
fileInputEl.type = "file";
fileInputEl.accept = "image/*";
fileInputEl.style.display = "none";
document.body.appendChild(fileInputEl);
fileInputEl.addEventListener("input", function (e) {
handleUpload(e as any);
document.body.removeChild(fileInputEl);
});
fileInputEl.click();
};
const handleUpload = async (evt: React.ChangeEvent<HTMLInputElement>) => {
let files = evt.target.files;
let reader = new FileReader();
if (files && files.length > 0) {
reader.onload = function () {
if (reader.result) {
setImg(Buffer.from(reader.result as ArrayBuffer));
}
};
reader.readAsArrayBuffer(files[0]);
}
};
const handlePrice = async () => {
if (img) {
const price = await bundler?.utils.getPrice(currency as string, img.length);
//@ts-ignore
setPrice(price?.toString());
}
};
const uploadFile = async () => {
if (img) {
await bundler?.uploader.upload(img, [{ name: "Content-Type", value: "image/png" }])
.then((res) => {
toast({
status: res?.status === 200 || res?.status === 201 ? "success" : "error",
title: res?.status === 200 || res?.status === 201 ? "Successful!" : `Unsuccessful! ${res?.status}`,
description: res?.data.id ? `https://arweave.net/${res.data.id}` : undefined,
duration: 15000,
});
})
.catch(e => { toast({ status: "error", title: `Failed to upload - ${e}` }) })
}
};
const fund = async () => {
if (bundler && fundAmount) {
toast({ status: "info", title: "Funding...", duration: 15000 })
const value = parseInput(fundAmount)
if (!value) return
await bundler.fund(value)
.then(res => { toast({ status: "success", title: `Funded ${res?.target}`, description: ` tx ID : ${res?.id}`, duration: 10000 }) })
.catch(e => {
toast({ status: "error", title: `Failed to fund - ${e.data?.message || e.message}` })
})
}
};
const withdraw = async () => {
if (bundler && withdrawAmount) {
toast({ status: "info", title: "Withdrawing..", duration: 15000 })
const value = parseInput(withdrawAmount)
if (!value) return
await bundler
.withdrawBalance(value)
.then((data) => {
toast({
status: "success",
title: `Withdrawal successful - ${data.data?.tx_id}`,
duration: 5000,
});
})
.catch((err: any) => {
toast({
status: "error",
title: "Withdrawal Unsuccessful!",
description: err.message,
duration: 5000,
});
});
}
};
// field change event handlers
const updateAddress = (evt: React.BaseSyntheticEvent) => {
setBundlerAddress(evt.target.value);
};
const updateFundAmount = (evt: React.BaseSyntheticEvent) => {
setFundingAmount(evt.target.value);
};
const updateWithdrawAmount = (evt: React.BaseSyntheticEvent) => {
setWithdrawAmount(evt.target.value);
};
const connectWeb3 = async (connector: any) => {
if (provider) {
await clean();
}
const p = new providers.Web3Provider(connector);
await p._ready();
return p
}
/**
* Map of providers with initialisation code - c is the configuration object from currencyMap
*/
const providerMap = {
"MetaMask": async (c: any) => {
if (!window?.ethereum?.isMetaMask) return;
await window.ethereum.enable();
const provider = await connectWeb3(window.ethereum);
const chainId = `0x${c.chainId.toString(16)}`
try { // additional logic for requesting a chain switch and conditional chain add.
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId }],
})
} catch (e: any) {
if (e.code === 4902) {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId, rpcUrls: c.rpcUrls, chainName: c.chainName
}],
});
}
}
return provider;
},
"WalletConnect": async (c: any) => { return await connectWeb3(await (new WalletConnectProvider(c)).enable()) },
// "Phantom": async (c: any) => {
// if (window.solana.isPhantom) {
// await window.solana.connect();
// const p = new PhantomWalletAdapter()
// await p.connect()
// return p;
// }
// },
"wallet.near.org": async (c: any) => {
const near = await connect(c);
const wallet = new WalletConnection(near, "bundlr");
if (!wallet.isSignedIn()) {
toast({ status: "info", title: "You are being redirected to authorize this application..." })
window.setTimeout(() => { wallet.requestSignIn() }, 4000)
// wallet.requestSignIn();
}
else if (!await c.keyStore.getKey(wallet._networkId, wallet.getAccountId())) {
toast({ status: "warning", title: "Click 'Connect' to be redirected to authorize access key creation." })
}
return wallet
}
} as any
const ethProviders = ["MetaMask", "WalletConnect"]
const currencyMap = {
// "solana": {
// providers: ["Phantom"], opts: {}
// },
"matic": {
providers: ethProviders,
opts: {
chainId: 137,
chainName: 'Polygon Mainnet',
rpcUrls: ["https://rpc-mainnet.maticvigil.com"],
},
},
"arbitrum": {
providers: ethProviders,
opts: {
chainName: "Arbitrum One",
chainId: 42161,
rpcUrls: ["https://arb1.arbitrum.io/rpc"]
}
},
"bnb": {
providers: ethProviders,
opts: {
chainName: "Binance Smart Chain",
chainId: 56,
rpcUrls: ["https://bsc-dataseed.binance.org/"]
}
},
"avalanche": {
providers: ethProviders,
opts: {
chainName: "Avalanche Network",
chainId: 43114,
rpcUrls: ["https://api.avax.network/ext/bc/C/rpc"]
}
},
"boba": {
providers: ethProviders,
opts: {
chainName: "BOBA L2",
chainId: 288,
rpcUrls: ["https://mainnet.boba.network"]
}
},
"near": {
providers: ["wallet.near.org"],
opts: {
networkId: "mainnet",
keyStore: new keyStores.BrowserLocalStorageKeyStore(),
nodeUrl: "https://rpc.mainnet.near.org",
walletUrl: "https://wallet.mainnet.near.org",
helperUrl: "https://helper.mainnet.near.org",
explorerUrl: "https://explorer.mainnet.near.org",
}
}
} as any
/**
* initialises the selected provider/currency
* @param cname currency name
* @param pname provider name
* @returns
*/
const initProvider = async () => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
if (provider) {
setProvider(undefined);
setBundler(undefined);
setAddress(undefined);
return;
}
const pname = selection as string;
const cname = currency as string;
const p = providerMap[pname] // get provider entry
const c = currencyMap[cname]
console.log(`loading: ${pname} for ${cname}`)
const providerInstance = await p(c.opts).catch((e: Error) => { toast({ status: "error", title: `Failed to load provider ${pname}`, duration: 10000 }); console.log(e); return; })
setProvider(providerInstance)
};
const initBundlr = async () => {
const bundlr = new WebBundlr(bundlerHttpAddress, currency, provider)
try {
// Check for valid bundlr node
await bundlr.utils.getBundlerAddress(currency)
} catch {
toast({ status: "error", title: `Failed to connect to bundlr ${bundlerHttpAddress}`, duration: 10000 })
return;
}
try {
await bundlr.ready();
} catch (err) {
console.log(err);
} //@ts-ignore
if (!bundlr.address) {
console.log("something went wrong");
}
toast({ status: "success", title: `Connected to ${bundlerHttpAddress}` })
setAddress(bundlr?.address)
setBundler(bundlr);
}
const toProperCase = (s: string) => { return s.charAt(0).toUpperCase() + s.substring(1).toLowerCase() }
const toggleRefresh = async () => {
if (intervalRef) {
clearInterval(intervalRef.current)
}
intervalRef.current = window.setInterval(async () => { bundler?.getLoadedBalance().then((r) => { setBalance(r.toString()) }).catch(_ => clearInterval(intervalRef.current)) }, 5000)
}
// parse decimal input into atomic units
const parseInput = (input: string | number) => {
const conv = new BigNumber(input).multipliedBy(bundler!.currencyConfig.base[1]);
if (conv.isLessThan(1)) {
toast({ status: "error", title: `Value too small!` })
return;
}
return conv;
}
return (
<VStack mt={10} >
<HStack>
{" "}
<Menu >
<MenuButton as={Button} rightIcon={<ChevronDownIcon />}>
{toProperCase(currency)}
</MenuButton>
<MenuList>
{Object.keys(currencyMap).map((v) => {
return (<MenuItem key={v} onClick={() => { clean(); setCurrency(v) }}>{toProperCase(v)}</MenuItem>) // proper/title case
})}
</MenuList>
</Menu>
<Menu >
<MenuButton disabled={currency === defaultCurrency} as={Button} rightIcon={<ChevronDownIcon />}>
{selection}
</MenuButton>
<MenuList>
{Object.keys(providerMap).map((v) => {
return ((currencyMap[currency] && currencyMap[currency].providers.indexOf(v) !== -1) ? (<MenuItem key={v} onClick={() => setSelection(v)}>{v}</MenuItem>) : undefined)
})}
</MenuList>
</Menu>
<Button disabled={!(selection !== defaultSelection && currency !== defaultCurrency && bundlerHttpAddress.length > 8)} onClick={async () => await initProvider()}>
{provider ? "Disconnect" : "Connect"}
</Button>
</HStack>
<Text>Connected Account: {address ?? "None"}</Text>
<HStack>
<Button w={400} disabled={!provider} onClick={async () => await initBundlr()}>
Connect to Bundlr
</Button>
<Input
value={bundlerHttpAddress}
onChange={updateAddress}
placeholder="Bundler Address"
/>
</HStack>
{
bundler && (
<>
<HStack>
<Button
onClick={async () => {
address &&
bundler!
.getBalance(address)
.then((res: BigNumber) => {
setBalance(res.toString())
});
await toggleRefresh();
}}
>
Get {toProperCase(currency)} Balance
</Button>
{balance && (
<Tooltip label={`(${balance} ${bundler.currencyConfig.base[0]})`}>
<Text>
{toProperCase(currency)} Balance: {bundler.utils.unitConverter(balance).toFixed(7, 2).toString()} {bundler.currencyConfig.ticker.toLowerCase()}
</Text>
</Tooltip>
)}
</HStack>
<HStack>
<Button w={200} onClick={fund}>
Fund Bundlr
</Button>
<Input
placeholder={`${toProperCase(currency)} Amount`}
value={fundAmount}
onChange={updateFundAmount}
/>
</HStack>
<HStack>
<Button w={200} onClick={withdraw}>
Withdraw Balance
</Button>
<Input
placeholder={`${toProperCase(currency)} Amount`}
value={withdrawAmount}
onChange={updateWithdrawAmount}
/>
</HStack>
<Button onClick={handleFileClick}>Select file from Device</Button>
{
img && (
<>
<HStack>
<Button onClick={handlePrice}>Get Price</Button>
{price && (
<Text>{`Cost: ${bundler.utils.unitConverter(price).toString()} ${bundler.currencyConfig.ticker.toLowerCase()} `}</Text>
)}
</HStack>
<Button onClick={uploadFile}>Upload to Bundlr Network</Button>
</>
)
}
</>
)
}
</VStack >
);
}
export default App; | the_stack |
import * as vue from "vue"
import { buildInterface, ToastInterface } from "../../../src/ts/interface"
import { EVENTS, TYPE } from "../../../src/ts/constants"
import { loadPlugin } from "../../utils/plugin"
import { ToastOptions } from "../../../src/types"
import { EventBus } from "../../../src/ts/eventBus"
import { nextTick, App } from "vue"
import * as index from "../../../src/index"
type Unpacked<T> = T extends (infer U)[]
? U
: T extends (...args: unknown[]) => infer U
? U
: T extends Promise<infer U>
? U
: T
describe("ToastInterface", () => {
let wrappers: Unpacked<ReturnType<typeof loadPlugin>>
let toast: ToastInterface
const eventBus = new EventBus()
const eventsEmmited = Object.values(EVENTS).reduce((agg, eventName) => {
const handler = jest.fn()
eventBus.on(eventName, handler)
return { ...agg, [eventName]: handler }
}, {} as { [eventName in EVENTS]: jest.Mock })
beforeEach(async () => {
wrappers = await loadPlugin({ eventBus })
toast = wrappers.toastInterface
jest.clearAllMocks()
jest.restoreAllMocks()
})
it("calls onMounted", async () => {
const onMounted = jest.fn()
expect(onMounted).not.toHaveBeenCalled()
toast = buildInterface({ onMounted })
await nextTick()
expect(onMounted).toHaveBeenCalledWith(expect.anything(), expect.anything())
})
it("does not call onMounted", () => {
const onMounted = jest.fn()
toast = buildInterface()
expect(onMounted).not.toHaveBeenCalled()
})
it("mounts if mountContainer is true", async () => {
const createAppSpy = jest.spyOn(vue, "createApp")
expect(createAppSpy).not.toHaveBeenCalled()
toast = buildInterface({}, true)
await nextTick()
expect(createAppSpy).toHaveBeenCalled()
})
it("does not mount if mountContainer is false", async () => {
const createAppSpy = jest.spyOn(vue, "createApp")
expect(createAppSpy).not.toHaveBeenCalled()
toast = buildInterface({}, false)
await nextTick()
expect(createAppSpy).not.toHaveBeenCalled()
})
it("Shares app context if shareAppContext", async () => {
// Create a base app
const baseApp = vue.createApp({ template: "<div>app</div>" })
// App starts off empty
expect(baseApp._context.components).toEqual({})
expect(baseApp._context.directives).toEqual({})
expect(baseApp._context.mixins.length).toEqual(0)
expect(baseApp._context.provides).toEqual({})
expect(baseApp.config.globalProperties).toEqual({})
// Add a plugin that sets globalProps
baseApp.use(App => {
App.config.globalProperties.newProp = "text"
})
// A custom componrnt
baseApp.component("CustomApp", { template: "<div></div>" })
// A custom directive
baseApp.directive("customDir", {})
// Provide some data
baseApp.provide("provideKey", "value")
// And a custom mixin
baseApp.mixin({
setup() {
return { stuff: 123 }
},
})
// Confirm that app has all values
expect(baseApp._context.components).not.toEqual({})
expect(baseApp._context.directives).not.toEqual({})
expect(baseApp._context.mixins.length).not.toEqual(0)
expect(baseApp._context.provides).not.toEqual({})
expect(baseApp.config.globalProperties).not.toEqual({})
let toastApp: App | undefined = undefined
const pluginOptions: index.PluginOptions = {
onMounted: (_, app) => {
toastApp = app
},
shareAppContext: true,
}
baseApp.use(index.default, pluginOptions)
await nextTick()
toastApp = toastApp as unknown as App
// toast app should share configs with app
expect(toastApp).toBeDefined()
expect(toastApp._context.components).toBe(baseApp._context.components)
expect(toastApp._context.directives).toBe(baseApp._context.directives)
expect(toastApp._context.mixins).toBe(baseApp._context.mixins)
expect(toastApp._context.provides).toBe(baseApp._context.provides)
expect(toastApp.config.globalProperties).toBe(
baseApp.config.globalProperties
)
})
it("Does not share app context if shareAppContext = true", async () => {
// Create a base app
const baseApp = vue.createApp({ template: "<div>app</div>" })
// App starts off empty
expect(baseApp._context.components).toEqual({})
expect(baseApp._context.directives).toEqual({})
expect(baseApp._context.mixins.length).toEqual(0)
expect(baseApp._context.provides).toEqual({})
expect(baseApp.config.globalProperties).toEqual({})
// Add a plugin that sets globalProps
baseApp.use(App => {
App.config.globalProperties.newProp = "text"
})
// A custom componrnt
baseApp.component("CustomApp", { template: "<div></div>" })
// A custom directive
baseApp.directive("customDir", {})
// Provide some data
baseApp.provide("provideKey", "value")
// And a custom mixin
baseApp.mixin({
setup() {
return { stuff: 123 }
},
})
// Confirm that app has all values
expect(baseApp._context.components).not.toEqual({})
expect(baseApp._context.directives).not.toEqual({})
expect(baseApp._context.mixins.length).not.toEqual(0)
expect(baseApp._context.provides).not.toEqual({})
expect(baseApp.config.globalProperties).not.toEqual({})
let toastApp: App | undefined = undefined
const pluginOptions: index.PluginOptions = {
onMounted: (_, app) => {
toastApp = app
},
}
baseApp.use(index.default, pluginOptions)
await nextTick()
toastApp = toastApp as unknown as App
// toast app should share configs with app
expect(toastApp).toBeDefined()
expect(toastApp._context.components).toEqual({})
expect(toastApp._context.directives).toEqual({})
expect(toastApp._context.mixins.length).toEqual(0)
expect(toastApp._context.provides).toEqual({})
expect(toastApp.config.globalProperties).toEqual({})
})
it("warns if shareAppContext = true in buildInterface", async () => {
const consoleSpy = jest.spyOn(console, "warn").mockImplementation()
expect(consoleSpy).toHaveBeenCalledTimes(0)
buildInterface({ shareAppContext: true }, true)
await nextTick()
expect(consoleSpy).toHaveBeenCalledTimes(1)
})
it("calls regular toast function with defaults", () => {
expect(eventsEmmited.add).not.toHaveBeenCalled()
const content = "content"
const id = toast(content)
expect(eventsEmmited.add).toHaveBeenCalledTimes(1)
expect(eventsEmmited.add).toBeCalledWith({
id: expect.any(Number),
type: TYPE.DEFAULT,
content,
})
expect(typeof id).toBe("number")
})
it("calls regular toast function with extra values", () => {
expect(eventsEmmited.add).not.toHaveBeenCalled()
const content = "content"
const options: ToastOptions = { timeout: 1000 }
const id = toast(content, options)
expect(eventsEmmited.add).toHaveBeenCalledTimes(1)
expect(eventsEmmited.add).toBeCalledWith({
id: expect.any(Number),
type: TYPE.DEFAULT,
content,
...options,
})
expect(typeof id).toBe("number")
})
it("calls clear", () => {
expect(eventsEmmited.clear).not.toHaveBeenCalled()
toast.clear()
expect(eventsEmmited.clear).toHaveBeenCalledTimes(1)
})
it("calls updateDefaults", () => {
expect(eventsEmmited.update_defaults).not.toHaveBeenCalled()
toast.updateDefaults({ timeout: 1000 })
expect(eventsEmmited.update_defaults).toHaveBeenCalledTimes(1)
expect(eventsEmmited.update_defaults).toBeCalledWith({ timeout: 1000 })
})
it("calls dismiss", () => {
expect(eventsEmmited.dismiss).not.toHaveBeenCalled()
toast.dismiss(10)
expect(eventsEmmited.dismiss).toHaveBeenCalledTimes(1)
expect(eventsEmmited.dismiss).toBeCalledWith(10)
})
it("calls update with content", () => {
expect(eventsEmmited.update).not.toHaveBeenCalled()
const id = 10
const content = "content"
toast.update(id, { content })
expect(eventsEmmited.update).toHaveBeenCalledTimes(1)
expect(eventsEmmited.update).toBeCalledWith({
id,
options: { content },
create: false,
})
})
it("calls update with options", () => {
expect(eventsEmmited.update).not.toHaveBeenCalled()
const id = 10
const options: ToastOptions = { timeout: 1000 }
toast.update(id, { options })
expect(eventsEmmited.update).toHaveBeenCalledTimes(1)
expect(eventsEmmited.update).toBeCalledWith({
id,
options: { ...options, content: undefined },
create: false,
})
})
it("calls update with create", () => {
expect(eventsEmmited.update).not.toHaveBeenCalled()
const id = 10
const content = "abc"
toast.update(id, { content }, true)
expect(eventsEmmited.update).toHaveBeenCalledTimes(1)
expect(eventsEmmited.update).toBeCalledWith({
id,
options: { content },
create: true,
})
})
it("calls success", () => {
expect(eventsEmmited.add).not.toHaveBeenCalled()
const content = "abc"
toast.success(content)
expect(eventsEmmited.add).toHaveBeenCalledTimes(1)
expect(eventsEmmited.add).toBeCalledWith({
id: expect.any(Number),
type: TYPE.SUCCESS,
content,
})
})
it("calls info", () => {
expect(eventsEmmited.add).not.toHaveBeenCalled()
const content = "abc"
toast.info(content)
expect(eventsEmmited.add).toHaveBeenCalledTimes(1)
expect(eventsEmmited.add).toBeCalledWith({
id: expect.any(Number),
type: TYPE.INFO,
content,
})
})
it("calls error", () => {
expect(eventsEmmited.add).not.toHaveBeenCalled()
const content = "abc"
toast.error(content)
expect(eventsEmmited.add).toHaveBeenCalledTimes(1)
expect(eventsEmmited.add).toBeCalledWith({
id: expect.any(Number),
type: TYPE.ERROR,
content,
})
})
it("calls warning", () => {
expect(eventsEmmited.add).not.toHaveBeenCalled()
const content = "abc"
toast.warning(content)
expect(eventsEmmited.add).toHaveBeenCalledTimes(1)
expect(eventsEmmited.add).toBeCalledWith({
id: expect.any(Number),
type: TYPE.WARNING,
content,
})
})
}) | the_stack |
import Component from '../component';
import Util from '../util.js';
interface IProps {
element: HTMLElement|string; // the element must exist
container?: HTMLElement|HTMLDocument|string;
toggle?: boolean;
setupContainer?: boolean;
closableKeyCodes?: [
27 // Escape
];
aside?: {
md: false,
lg: true,
xl: true,
};
}
interface IMediaSize {
name: string;
media: MediaQueryList;
}
export default class OffCanvas extends Component {
public static attachDOM(): void {
const className = 'offcanvas';
Util.Observer.subscribe({
componentClass: className,
onAdded(element, create) {
create(new OffCanvas({ element }));
},
onRemoved(element, remove) {
remove('OffCanvas', element);
},
});
document.addEventListener(Util.Event.CLICK, (event: Event) => {
const target: HTMLElement|null = event.target as HTMLElement;
if (!target) {
return;
}
const toggleEl = Util.Selector.closest(target, `[data-toggle="${className}"]`);
if (toggleEl) {
const selector: string|null = toggleEl.getAttribute('data-target');
if (!selector) {
return;
}
const offCanvas: HTMLElement|null = document.querySelector(selector);
if (!offCanvas) {
return;
}
const offCanvasComponent = Util.Observer.getComponent(className, { element: offCanvas });
if (!offCanvasComponent) {
return;
}
// remove the focus state of the trigger
target.blur();
offCanvasComponent.toggle();
}
});
}
private currentWidthName: string|null = null;
private animate: boolean = true;
private showAside: boolean = false;
private directions: string[] = ['left', 'right'];
private direction: string|null = null;
private sizes: IMediaSize[] = [];
private backdropSelector: string = 'offcanvas-backdrop';
/**
*
* @param props
*/
constructor(props: IProps) {
super('off-canvas', {
toggle: false,
closableKeyCodes: [27],
container: document.body,
setupContainer: true,
aside: {
md: false,
lg: true,
xl: true,
},
}, props);
// no-template: off-canvas is not a dynamic component
const sm = { name: 'sm', media: window.matchMedia('(min-width: 1px)') };
const md = { name: 'md', media: window.matchMedia('(min-width: 768px)') };
const lg = { name: 'lg', media: window.matchMedia('(min-width: 992px)') };
const xl = { name: 'xl', media: window.matchMedia('(min-width: 1200px)') };
this.sizes = [sm, md, lg, xl].reverse();
this.checkDirection();
if (this.getProp('setupContainer')) {
this.checkWidth();
}
const toggle = this.getProp('toggle');
if (toggle) {
this.toggle();
}
window.addEventListener('resize', () => this.checkWidth(), false);
}
public checkDirection(): void {
const element = this.getElement();
this.directions.every((direction) => {
if (element.classList.contains(`offcanvas-${direction}`)) {
this.direction = direction;
return false;
}
return true;
});
}
public checkWidth(): void {
if (!('matchMedia' in window)) {
return;
}
const size: IMediaSize|undefined = this.sizes.find((s: IMediaSize) => {
const mediaQuery = s.media;
const match = mediaQuery.media.match(/[a-z]?-width:\s?([0-9]+)/);
return match && mediaQuery.matches ? true : false;
});
if (!size) {
return;
}
this.setAside(size.name);
}
public setAside(sizeName: string): void {
const container = this.getContainer();
if (this.currentWidthName === sizeName || !container) {
return;
}
this.currentWidthName = sizeName;
const aside = this.getProp('aside');
this.showAside = aside[sizeName] === true;
if (aside[sizeName] === true) {
if (!container.classList.contains(`offcanvas-aside-${this.direction}`)) {
container.classList.add(`offcanvas-aside-${this.direction}`);
}
// avoid animation by setting animate to false
this.animate = false;
// remove previous backdrop
if (this.getBackdrop()) {
this.removeBackdrop();
}
const containerShowClass = this.getShowClass();
if (this.isVisible() && !container.classList.contains(containerShowClass)) {
container.classList.add(containerShowClass);
} else if (!this.isVisible() && container.classList.contains(containerShowClass)) {
container.classList.remove(containerShowClass);
}
} else {
if (container.classList.contains(`offcanvas-aside-${this.direction}`)) {
container.classList.remove(`offcanvas-aside-${this.direction}`);
}
this.animate = true;
// force hide
this.hide();
}
}
public onElementEvent(event: KeyboardEvent): void {
const closableKeyCodes = this.getProp('closableKeyCodes');
if (event.type === 'keyup' && !closableKeyCodes.find(k => k === event.keyCode)) {
return;
}
// hide the offcanvas
this.hide();
}
public isVisible(): boolean {
return this.getElement().classList.contains('show');
}
/**
* Shows the off-canvas
* @returns {Boolean}
*/
public show(): boolean {
if (this.getElement().classList.contains('show')) {
return false;
}
this.triggerEvent(Util.Event.SHOW);
if (!this.showAside) {
this.createBackdrop();
}
// add a timeout so that the CSS animation works
(async () => {
await Util.sleep(20);
// attach event
this.attachEvents();
const onShown = () => {
this.triggerEvent(Util.Event.SHOWN);
if (this.animate) {
const element = this.getElement();
element.removeEventListener(Util.Event.TRANSITION_END, onShown);
element.classList.remove('animate');
}
};
if (this.showAside) {
const container = this.getContainer();
const containerShowClass = this.getShowClass();
if (container && !container.classList.contains(containerShowClass)) {
container.classList.add(containerShowClass);
}
}
const el = this.getElement();
if (this.animate) {
el.addEventListener(Util.Event.TRANSITION_END, onShown);
el.classList.add('animate');
} else {
// directly trigger the onShown
onShown();
}
el.classList.add('show');
})();
return true;
}
/**
* Hides the off-canvas
* @returns {Boolean}
*/
public hide(): boolean {
const element = this.getElement();
if (!element.classList.contains('show')) {
return false;
}
this.triggerEvent(Util.Event.HIDE);
this.detachEvents();
if (this.animate) {
element.classList.add('animate');
}
element.classList.remove('show');
if (this.showAside) {
const container = this.getContainer();
const containerShowClass = this.getShowClass();
if (container && container.classList.contains(containerShowClass)) {
container.classList.remove(containerShowClass);
}
}
if (!this.showAside) {
const backdrop = this.getBackdrop();
if (!backdrop) {
return true;
}
const onHidden = () => {
if (this.animate) {
element.classList.remove('animate');
}
backdrop.removeEventListener(Util.Event.TRANSITION_END, onHidden);
this.triggerEvent(Util.Event.HIDDEN);
this.removeBackdrop();
};
if (backdrop) {
backdrop.addEventListener(Util.Event.TRANSITION_END, onHidden);
backdrop.classList.add('fadeout');
}
}
return true;
}
public toggle(): boolean {
if (this.isVisible()) {
return this.hide();
}
return this.show();
}
public createBackdrop(): void {
const backdrop = document.createElement('div');
const id: string|null = this.getId();
if (id) {
backdrop.setAttribute('data-id', id);
}
backdrop.classList.add(this.backdropSelector);
const container = this.getContainer();
if (container) {
container.appendChild(backdrop);
}
}
public getBackdrop(): HTMLElement|null {
return document.querySelector(`.${this.backdropSelector}[data-id="${this.getId()}"]`);
}
public removeBackdrop(): void {
const backdrop = this.getBackdrop();
if (backdrop && backdrop.parentNode) {
backdrop.parentNode.removeChild(backdrop);
}
}
public attachEvents(): void {
const element = this.getElement();
Array.from(element.querySelectorAll('[data-dismiss]') || [])
.forEach(button => this.registerElement({
target: button as HTMLElement,
event: Util.Event.CLICK,
}));
const backdrop = this.getBackdrop();
if (!this.showAside && backdrop) {
this.registerElement({ target: backdrop as HTMLElement, event: Util.Event.START });
}
this.registerElement({ target: document, event: 'keyup' });
}
public detachEvents(): void {
const element = this.getElement();
const dismissButtons = element.querySelectorAll('[data-dismiss]');
if (dismissButtons) {
Array
.from(dismissButtons)
.forEach(button => this.unregisterElement({
target: button as HTMLElement,
event: Util.Event.CLICK,
}));
}
const backdrop = this.getBackdrop();
if (!this.showAside && backdrop) {
this.unregisterElement({ target: backdrop as HTMLElement, event: Util.Event.START });
}
this.unregisterElement({ target: document, event: 'keyup' });
}
private getContainer(): HTMLElement|null {
let container = this.getProp('container');
if (typeof container === 'string') {
container = document.querySelector(container);
}
return container;
}
// For the container
private getShowClass(): string {
return `show-${this.direction}`;
}
}
// static boot
OffCanvas.attachDOM(); | the_stack |
import {ClientScope} from 'app/client/components/ClientScope';
import {guessTimezone} from 'app/client/lib/guessTimezone';
import {HomePluginManager} from 'app/client/lib/HomePluginManager';
import {ImportSourceElement} from 'app/client/lib/ImportSourceElement';
import {localStorageObs} from 'app/client/lib/localStorageObs';
import {AppModel, reportError} from 'app/client/models/AppModel';
import {reportMessage, UserError} from 'app/client/models/errors';
import {urlState} from 'app/client/models/gristUrlState';
import {ownerName} from 'app/client/models/WorkspaceInfo';
import {IHomePage} from 'app/common/gristUrls';
import {isLongerThan} from 'app/common/gutil';
import {SortPref, UserOrgPrefs, ViewPref} from 'app/common/Prefs';
import * as roles from 'app/common/roles';
import {Document, Organization, Workspace} from 'app/common/UserAPI';
import {bundleChanges, Computed, Disposable, Observable, subscribe} from 'grainjs';
import * as moment from 'moment';
import flatten = require('lodash/flatten');
import sortBy = require('lodash/sortBy');
const DELAY_BEFORE_SPINNER_MS = 500;
// Given a UTC Date ISO 8601 string (the doc updatedAt string), gives a reader-friendly
// relative time to now - e.g. 'yesterday', '2 days ago'.
export function getTimeFromNow(utcDateISO: string): string {
const time = moment.utc(utcDateISO);
const now = moment();
const diff = now.diff(time, 's');
if (diff < 0 && diff > -60) {
// If the time appears to be in the future, but less than a minute
// in the future, chalk it up to a difference in time
// synchronization and don't claim the resource will be changed in
// the future. For larger differences, just report them
// literally, there's a more serious problem or lack of
// synchronization.
return now.fromNow();
}
return time.fromNow();
}
export interface HomeModel {
// PageType value, one of the discriminated union values used by AppModel.
pageType: "home";
app: AppModel;
currentPage: Observable<IHomePage>;
currentWSId: Observable<number|undefined>; // should be set when currentPage is 'workspace'
// Note that Workspace contains its documents in .docs.
workspaces: Observable<Workspace[]>;
loading: Observable<boolean|"slow">; // Set to "slow" when loading for a while.
available: Observable<boolean>; // set if workspaces loaded correctly.
showIntro: Observable<boolean>; // set if no docs and we should show intro.
singleWorkspace: Observable<boolean>; // set if workspace name should be hidden.
trashWorkspaces: Observable<Workspace[]>; // only set when viewing trash
templateWorkspaces: Observable<Workspace[]>; // Only set when viewing templates or all documents.
// currentWS is undefined when currentPage is not "workspace" or if currentWSId doesn't exist.
currentWS: Observable<Workspace|undefined>;
// List of pinned docs to show for currentWS.
currentWSPinnedDocs: Observable<Document[]>;
// List of featured templates from templateWorkspaces.
featuredTemplates: Observable<Document[]>;
// List of other sites (orgs) user can access. Only populated on All Documents, and only when
// the current org is a personal org, or the current org is view access only.
otherSites: Observable<Organization[]>;
currentSort: Observable<SortPref>;
currentView: Observable<ViewPref>;
importSources: Observable<ImportSourceElement[]>;
// The workspace for new docs, or "unsaved" to only allow unsaved-doc creation, or null if the
// user isn't allowed to create a doc.
newDocWorkspace: Observable<Workspace|null|"unsaved">;
createWorkspace(name: string): Promise<void>;
renameWorkspace(id: number, name: string): Promise<void>;
deleteWorkspace(id: number, forever: boolean): Promise<void>;
restoreWorkspace(ws: Workspace): Promise<void>;
createDoc(name: string, workspaceId: number|"unsaved"): Promise<string>;
renameDoc(docId: string, name: string): Promise<void>;
deleteDoc(docId: string, forever: boolean): Promise<void>;
restoreDoc(doc: Document): Promise<void>;
pinUnpinDoc(docId: string, pin: boolean): Promise<void>;
moveDoc(docId: string, workspaceId: number): Promise<void>;
}
export interface ViewSettings {
currentSort: Observable<SortPref>;
currentView: Observable<ViewPref>;
}
export class HomeModelImpl extends Disposable implements HomeModel, ViewSettings {
public readonly pageType = "home";
public readonly currentPage = Computed.create(this, urlState().state, (use, s) =>
s.homePage || (s.ws !== undefined ? "workspace" : "all"));
public readonly currentWSId = Computed.create(this, urlState().state, (use, s) => s.ws);
public readonly workspaces = Observable.create<Workspace[]>(this, []);
public readonly loading = Observable.create<boolean|"slow">(this, true);
public readonly available = Observable.create(this, false);
public readonly singleWorkspace = Observable.create(this, true);
public readonly trashWorkspaces = Observable.create<Workspace[]>(this, []);
public readonly templateWorkspaces = Observable.create<Workspace[]>(this, []);
public readonly importSources = Observable.create<ImportSourceElement[]>(this, []);
// Get the workspace details for the workspace with id of currentWSId.
public readonly currentWS = Computed.create(this, (use) =>
use(this.workspaces).find(ws => (ws.id === use(this.currentWSId))));
public readonly currentWSPinnedDocs = Computed.create(this, this.currentPage, this.currentWS, (use, page, ws) => {
const docs = (page === 'all') ?
flatten((use(this.workspaces).map(w => w.docs))) :
(ws ? ws.docs : []);
return sortBy(docs.filter(doc => doc.isPinned), (doc) => doc.name.toLowerCase());
});
public readonly featuredTemplates = Computed.create(this, this.templateWorkspaces, (_use, templates) => {
const featuredTemplates = flatten((templates).map(t => t.docs)).filter(t => t.isPinned);
return sortBy(featuredTemplates, (t) => t.name.toLowerCase());
});
public readonly otherSites = Computed.create(this, this.currentPage, this.app.topAppModel.orgs,
(_use, page, orgs) => {
if (page !== 'all') { return []; }
const currentOrg = this._app.currentOrg;
if (!currentOrg) { return []; }
const isPersonalOrg = currentOrg.owner;
if (!isPersonalOrg && (currentOrg.access !== 'viewers' || !currentOrg.public)) {
return [];
}
return orgs.filter(org => org.id !== currentOrg.id);
});
public readonly currentSort: Observable<SortPref>;
public readonly currentView: Observable<ViewPref>;
// The workspace for new docs, or "unsaved" to only allow unsaved-doc creation, or null if the
// user isn't allowed to create a doc.
public readonly newDocWorkspace = Computed.create(this, this.currentPage, this.currentWS, (use, page, ws) => {
// Anonymous user can create docs, but in unsaved mode.
if (!this.app.currentValidUser) { return "unsaved"; }
if (page === 'trash') { return null; }
const destWS = (['all', 'templates'].includes(page)) ? (use(this.workspaces)[0] || null) : ws;
return destWS && roles.canEdit(destWS.access) ? destWS : null;
});
// Whether to show intro: no docs (other than examples) and user may create docs.
public readonly showIntro = Computed.create(this, this.workspaces, (use, wss) => (
wss.every((ws) => ws.isSupportWorkspace || ws.docs.length === 0) &&
Boolean(use(this.newDocWorkspace))));
private _userOrgPrefs = Observable.create<UserOrgPrefs|undefined>(this, this._app.currentOrg?.userOrgPrefs);
constructor(private _app: AppModel, clientScope: ClientScope) {
super();
if (!this.app.currentValidUser) {
// For the anonymous user, use local settings, don't attempt to save anything to the server.
const viewSettings = makeLocalViewSettings(null, 'all');
this.currentSort = viewSettings.currentSort;
this.currentView = viewSettings.currentView;
} else {
// Preference for sorting. Defaults to 'name'. Saved to server on write.
this.currentSort = Computed.create(this, this._userOrgPrefs,
(use, prefs) => SortPref.parse(prefs?.docMenuSort) || 'name')
.onWrite(s => this._saveUserOrgPref("docMenuSort", s));
// Preference for view mode. The default is somewhat complicated. Saved to server on write.
this.currentView = Computed.create(this, this._userOrgPrefs,
(use, prefs) => ViewPref.parse(prefs?.docMenuView) || getViewPrefDefault(use(this.workspaces)))
.onWrite(s => this._saveUserOrgPref("docMenuView", s));
}
this.autoDispose(subscribe(this.currentPage, this.currentWSId, (use) =>
this._updateWorkspaces().catch(reportError)));
// Defer home plugin initialization
const pluginManager = new HomePluginManager(
_app.topAppModel.plugins,
_app.topAppModel.getUntrustedContentOrigin()!,
clientScope);
const importSources = ImportSourceElement.fromArray(pluginManager.pluginsList);
this.importSources.set(importSources);
}
// Accessor for the AppModel containing this HomeModel.
public get app(): AppModel { return this._app; }
public async createWorkspace(name: string) {
const org = this._app.currentOrg;
if (!org) { return; }
this._checkForDuplicates(name);
await this._app.api.newWorkspace({name}, org.id);
await this._updateWorkspaces();
}
public async renameWorkspace(id: number, name: string) {
this._checkForDuplicates(name);
await this._app.api.renameWorkspace(id, name);
await this._updateWorkspaces();
}
public async deleteWorkspace(id: number, forever: boolean) {
// TODO: Prevent the last workspace from being removed.
await (forever ? this._app.api.deleteWorkspace(id) : this._app.api.softDeleteWorkspace(id));
await this._updateWorkspaces();
}
public async restoreWorkspace(ws: Workspace) {
await this._app.api.undeleteWorkspace(ws.id);
await this._updateWorkspaces();
reportMessage(`Workspace "${ws.name}" restored`);
}
// Creates a new doc by calling the API, and returns its docId.
public async createDoc(name: string, workspaceId: number|"unsaved"): Promise<string> {
if (workspaceId === "unsaved") {
const timezone = await guessTimezone();
return await this._app.api.newUnsavedDoc({timezone});
}
const id = await this._app.api.newDoc({name}, workspaceId);
await this._updateWorkspaces();
return id;
}
public async renameDoc(docId: string, name: string): Promise<void> {
await this._app.api.renameDoc(docId, name);
await this._updateWorkspaces();
}
public async deleteDoc(docId: string, forever: boolean): Promise<void> {
await (forever ? this._app.api.deleteDoc(docId) : this._app.api.softDeleteDoc(docId));
await this._updateWorkspaces();
}
public async restoreDoc(doc: Document): Promise<void> {
await this._app.api.undeleteDoc(doc.id);
await this._updateWorkspaces();
reportMessage(`Document "${doc.name}" restored`);
}
public async pinUnpinDoc(docId: string, pin: boolean): Promise<void> {
await (pin ? this._app.api.pinDoc(docId) : this._app.api.unpinDoc(docId));
await this._updateWorkspaces();
}
public async moveDoc(docId: string, workspaceId: number): Promise<void> {
await this._app.api.moveDoc(docId, workspaceId);
await this._updateWorkspaces();
}
private _checkForDuplicates(name: string): void {
if (this.workspaces.get().find(ws => ws.name === name)) {
throw new UserError('Name already exists. Please choose a different name.');
}
}
// Fetches and updates workspaces, which include contained docs as well.
private async _updateWorkspaces() {
const org = this._app.currentOrg;
if (!org) {
this.workspaces.set([]);
this.trashWorkspaces.set([]);
this.templateWorkspaces.set([]);
return;
}
this.loading.set(true);
const currentPage = this.currentPage.get();
const promises = [
this._fetchWorkspaces(org.id, false).catch(reportError),
currentPage === 'trash' ? this._fetchWorkspaces(org.id, true).catch(reportError) : null,
this._maybeFetchTemplates(),
] as const;
const promise = Promise.all(promises);
if (await isLongerThan(promise, DELAY_BEFORE_SPINNER_MS)) {
this.loading.set("slow");
}
const [wss, trashWss, templateWss] = await promise;
// bundleChanges defers computeds' evaluations until all changes have been applied.
bundleChanges(() => {
this.workspaces.set(wss || []);
this.trashWorkspaces.set(trashWss || []);
this.templateWorkspaces.set(templateWss || []);
this.loading.set(false);
this.available.set(!!wss);
// Hide workspace name if we are showing a single (non-support) workspace, and active
// product doesn't allow adding workspaces. It is important to check both conditions because:
// * A personal org, where workspaces can't be added, can still have multiple
// workspaces via documents shared by other users.
// * An org with workspace support might happen to just have one workspace right
// now, but it is good to show names to highlight the possibility of adding more.
const nonSupportWss = Array.isArray(wss) ? wss.filter(ws => !ws.isSupportWorkspace) : null;
this.singleWorkspace.set(
!!nonSupportWss && nonSupportWss.length === 1 && _isSingleWorkspaceMode(this._app)
);
});
}
private async _fetchWorkspaces(orgId: number, forRemoved: boolean) {
let api = this._app.api;
if (forRemoved) {
api = api.forRemoved();
}
const wss = await api.getOrgWorkspaces(orgId);
if (this.isDisposed()) { return null; }
for (const ws of wss) {
ws.docs = sortBy(ws.docs, (doc) => doc.name.toLowerCase());
// Populate doc.removedAt for soft-deleted docs even when deleted along with a workspace.
if (forRemoved) {
for (const doc of ws.docs) {
doc.removedAt = doc.removedAt || ws.removedAt;
}
}
// Populate doc.workspace, which is used by DocMenu/PinnedDocs and
// is useful in cases where there are multiple workspaces containing
// pinned documents that need to be sorted in alphabetical order.
for (const doc of ws.docs) {
doc.workspace = doc.workspace ?? ws;
}
}
// Sort workspaces such that workspaces from the personal orgs of others
// come after workspaces from our own personal org; workspaces from personal
// orgs are grouped by personal org and the groups are ordered alphabetically
// by owner name; and all else being equal workspaces are ordered alphabetically
// by their name. All alphabetical ordering is case-insensitive.
// Workspaces shared from support account (e.g. samples) are put last.
return sortBy(wss, (ws) => [ws.isSupportWorkspace,
ownerName(this._app, ws).toLowerCase(),
ws.name.toLowerCase()]);
}
/**
* Fetches templates if on the Templates or All Documents page.
*
* Only fetches featured (pinned) templates on the All Documents page.
*/
private async _maybeFetchTemplates(): Promise<Workspace[] | null> {
const currentPage = this.currentPage.get();
const shouldFetchTemplates = ['all', 'templates'].includes(currentPage);
if (!shouldFetchTemplates) { return null; }
let templateWss: Workspace[] = [];
try {
const onlyFeatured = currentPage === 'all';
templateWss = await this._app.api.getTemplates(onlyFeatured);
} catch {
// If the org doesn't exist (404), return nothing and don't report error to user.
return null;
}
if (this.isDisposed()) { return null; }
for (const ws of templateWss) {
for (const doc of ws.docs) {
// Populate doc.workspace, which is used by DocMenu/PinnedDocs and
// is useful in cases where there are multiple workspaces containing
// pinned documents that need to be sorted in alphabetical order.
doc.workspace = doc.workspace ?? ws;
}
ws.docs = sortBy(ws.docs, (doc) => doc.name.toLowerCase());
}
return templateWss;
}
private async _saveUserOrgPref<K extends keyof UserOrgPrefs>(key: K, value: UserOrgPrefs[K]) {
const org = this._app.currentOrg;
if (org) {
org.userOrgPrefs = {...org.userOrgPrefs, [key]: value};
this._userOrgPrefs.set(org.userOrgPrefs);
await this._app.api.updateOrg('current', {userOrgPrefs: org.userOrgPrefs});
}
}
}
// Check if active product allows just a single workspace.
function _isSingleWorkspaceMode(app: AppModel): boolean {
return app.currentFeatures.maxWorkspacesPerOrg === 1;
}
// Returns a default view mode preference. We used to show 'list' for everyone. We now default to
// 'icons' for new or light users. But if a user has more than 4 docs or any pinned docs, we'll
// switch to 'list'. This will also avoid annoying existing users who may prefer a list.
function getViewPrefDefault(workspaces: Workspace[]): ViewPref {
const userWorkspaces = workspaces.filter(ws => !ws.isSupportWorkspace);
const numDocs = userWorkspaces.reduce((sum, ws) => sum + ws.docs.length, 0);
const pinnedDocs = userWorkspaces.some((ws) => ws.docs.some(doc => doc.isPinned));
return (numDocs > 4 || pinnedDocs) ? 'list' : 'icons';
}
/**
* Create observables for per-workspace view settings which default to org-wide settings, but can
* be changed independently and persisted in localStorage.
*/
export function makeLocalViewSettings(home: HomeModel|null, wsId: number|'trash'|'all'|'templates'): ViewSettings {
const userId = home?.app.currentUser?.id || 0;
const sort = localStorageObs(`u=${userId}:ws=${wsId}:sort`);
const view = localStorageObs(`u=${userId}:ws=${wsId}:view`);
return {
currentSort: Computed.create(null,
// If no value in localStorage, use sort of All Documents.
(use) => SortPref.parse(use(sort)) || (home ? use(home.currentSort) : 'name'))
.onWrite((val) => sort.set(val)),
currentView: Computed.create(null,
// If no value in localStorage, use mode of All Documents, except Trash which defaults to 'list'.
(use) => ViewPref.parse(use(view)) || (wsId === 'trash' ? 'list' : (home ? use(home.currentView) : 'icons')))
.onWrite((val) => view.set(val)),
};
} | the_stack |
window.addEventListener('WebComponentsReady', () => {
const testPath = 'testpath';
describe('<file-browser>', () => {
let testFixture: FileBrowserElement;
const startuppath = new DatalabFileId(testPath, FileManagerType.MOCK);
const mockFiles = [
new MockFile('file1'),
new MockFile('file2'),
new MockFile('file3'),
];
const mockFileManager = new MockFileManager();
const alwaysEnabledButtonIds = [
'newNotebookButton',
'newFileButton',
'newFolderButton',
'uploadButton',
];
const singleSelectionEnabledButtonIds = [
'editAsTextButton',
'copyButton',
'moveButton',
'renameButton',
];
const multiSelectionEnabledButtonIds = [
'deleteButton',
];
function assertEnabledState(id: string, enabled: boolean) {
const button = testFixture.$[id] as HTMLElement;
assert(button.hasAttribute('disabled') === !enabled,
id + ' is expected to be ' + enabled ? 'enabled' : 'disabled');
}
before(() => {
SettingsManager.getUserSettingsAsync = (forceRefresh: boolean) => {
assert(forceRefresh === true, 'file-browser should refresh settings on load');
const mockSettings: common.UserSettings = {
idleTimeoutInterval: '',
idleTimeoutShutdownCommand: '',
startuppath: startuppath.path,
theme: 'light',
};
return Promise.resolve(mockSettings);
};
ApiManager.getBasePath = () => {
return Promise.resolve('');
};
SessionManager.listSessionsAsync = () => {
return Promise.resolve([]);
};
mockFileManager.list = () => {
return Promise.resolve(mockFiles);
};
FileManagerFactory.getInstance = () => mockFileManager;
FileManagerFactory.getInstanceForType = (_) => mockFileManager;
});
beforeEach((done: () => any) => {
testFixture = fixture('files-fixture');
testFixture.ready()
.then(() => {
Polymer.dom.flush();
done();
});
});
it('gets the startup path correctly', () => {
assert(JSON.stringify(testFixture.currentFile.id) === JSON.stringify(startuppath),
'incorrect startup path');
});
it('displays list of files correctly', () => {
const files: ItemListElement = testFixture.$.files;
assert(files.rows.length === 3, 'should have three files');
mockFiles.forEach((file: DatalabFile, i: number) => {
assert(files.rows[i].columns[0] === file.name,
'mock file ' + i + 'name not shown in first column');
assert(files.rows[i].columns[1] === file.type.toString(),
'mock file ' + i + 'type not shown in second column');
assert(files.rows[i].icon === file.icon, 'mock file ' + i + ' type not shown as icon');
});
});
it('shows column names returned from the file manager in header', () => {
const files: ItemListElement = testFixture.$.files;
const columns = files.$.header.querySelectorAll('.column');
assert(columns.length === 2, 'exactly two columns are expected');
assert(columns[0].innerText.trim() === 'Name', 'Name column missing');
assert(columns[1].innerText.trim() === 'Type', 'Type column missing');
});
it('starts up with no files selected, and no files running', () => {
const files: ItemListElement = testFixture.$.files;
files.rows.forEach((row: ItemListRow, i: number) => {
assert(!row.selected, 'file ' + i + ' should not be selected');
});
});
it('shows new notebook dialog', async () => {
// Make sure no dialogs are shown
assert(document.querySelector('input-dialog') === null,
'no input dialogs should be shown before clicking new');
testFixture.$.newNotebookButton.click();
const dialog = TestUtils.getDialog(NewNotebookDialogElement);
assert(!!dialog, 'an input dialog should show after clicking new notebook');
assert(dialog.$.dialogTitle.innerText === 'New ' + Utils.constants.notebook,
'dialog text should include type of new entity');
// Force update items in the dropdown instead of waiting on the event
Polymer.dom.flush();
dialog.$.dropdownItems.forceSynchronousItemUpdate();
await TestUtils.closeDialog(dialog, false);
});
it('shows new file dialog', async () => {
// Make sure no dialogs are shown
assert(document.querySelector('input-dialog') === null,
'no input dialogs should be shown before clicking new');
testFixture.$.newFileButton.click();
const dialog = TestUtils.getDialog(InputDialogElement);
assert(!!dialog, 'an input dialog should show after clicking new file');
assert(dialog.$.dialogTitle.innerText === 'New ' + Utils.constants.file,
'dialog text should include type of new entity');
await TestUtils.closeDialog(dialog, false);
});
it('shows new folder dialog', async () => {
// Make sure no dialogs are shown
assert(document.querySelector('input-dialog') === null,
'no input dialogs should be shown before clicking new');
testFixture.$.newFolderButton.click();
const dialog = TestUtils.getDialog(InputDialogElement);
assert(!!dialog, 'an input dialog should show after clicking new folder');
assert(dialog.$.dialogTitle.innerText === 'New ' + Utils.constants.directory,
'dialog text should include type of new entity');
await TestUtils.closeDialog(dialog, false);
});
it('enables always-enabled buttons, disables the rest when no file is selected', () => {
const files: ItemListElement = testFixture.$.files;
files._unselectAll();
alwaysEnabledButtonIds.forEach((id) => assertEnabledState(id, true));
singleSelectionEnabledButtonIds.forEach((id) => assertEnabledState(id, false));
multiSelectionEnabledButtonIds.forEach((id) => assertEnabledState(id, false));
});
it('enables all buttons when one file is selected', () => {
const files: ItemListElement = testFixture.$.files;
files._unselectAll();
files._selectItemByDisplayIndex(0);
alwaysEnabledButtonIds.forEach((id) => assertEnabledState(id, true));
singleSelectionEnabledButtonIds.forEach((id) => assertEnabledState(id, true));
multiSelectionEnabledButtonIds.forEach((id) => assertEnabledState(id, true));
});
it(`enables always enabled and multi-selection enabled buttons, and
disables the rest when two files are selected`, () => {
const files: ItemListElement = testFixture.$.files;
files._unselectAll();
files._selectItemByDisplayIndex(0);
files._selectItemByDisplayIndex(1);
alwaysEnabledButtonIds.forEach((id) => assertEnabledState(id, true));
singleSelectionEnabledButtonIds.forEach((id) => assertEnabledState(id, false));
multiSelectionEnabledButtonIds.forEach((id) => assertEnabledState(id, true));
});
describe('creating new notebook', () => {
const notebookName = 'newMockNotebook';
let dialog: NewNotebookDialogElement;
const specs = [{
display_name: 'Kernel 1',
language: 'kernel1Lang',
name: 'kernel1',
}, {
display_name: 'Kernel 2',
language: 'kernel2Lang',
name: 'kernel2',
}];
KernelManager.getAllKernelSpecs = () => specs;
beforeEach(async () => {
// Validate window.open is called with the correct url
sinon.stub(window, 'open');
testFixture.$.newNotebookButton.click();
dialog = TestUtils.getDialog(NewNotebookDialogElement) as NewNotebookDialogElement;
dialog.$.inputBox.value = notebookName;
// Force update items in the dropdown instead of waiting on the event
Polymer.dom.flush();
dialog.$.dropdownItems.forceSynchronousItemUpdate();
});
afterEach(() => {
(window.open as sinon.SinonStub).restore();
});
it('shows a list of supported kernel names in new notebook dialog', async () => {
assert(dialog.$.dropdownItems.items.length === 2, 'two kernels should be listed');
dialog.$.dropdownItems.items.forEach((item: any, i: number) => {
assert(item.innerText.trim() === specs[i].display_name,
'the kernel\'s display name should be shown in the list');
assert(item.value.trim() === specs[i].name,
'the kernel\'s name should be stored in the value attribute');
});
await TestUtils.closeDialog(dialog, false);
});
it('correctly opens new tab to create a notebook using the default kernel', async () => {
await TestUtils.closeDialog(dialog, true);
const result = await TestUtils.waitUntilTrue(() =>
(window.open as sinon.SinonStub).called, 5000);
assert(!!result, 'create should be called when create button clicked');
assert((window.open as sinon.SinonStub).calledWithExactly(
location.origin + '/notebook/new/mock/' + testPath +
'?fileName=' + notebookName + '.ipynb&templateName=newNotebook' +
'&kernel=' + specs[0].name, '_blank'),
'window.open should be created with the newNotebook template');
});
it('uses the selected kernel name when creating a new notebook', async () => {
dialog.$.dropdownItems.selected = 1;
await TestUtils.closeDialog(dialog, true);
const result = await TestUtils.waitUntilTrue(() =>
(window.open as sinon.SinonStub).called, 5000);
assert(!!result, 'create should be called when create button clicked');
assert((window.open as sinon.SinonStub).calledWithExactly(
location.origin + '/notebook/new/mock/' + testPath +
'?fileName=' + notebookName + '.ipynb&templateName=newNotebook' +
'&kernel=' + specs[1].name, '_blank'),
'window.open should be created with the newNotebook template');
});
});
it('calls FileManager.create correctly to create a new file', async () => {
const fileName = 'newMockFile';
sinon.stub(mockFileManager, 'create');
testFixture.$.newFileButton.click();
const dialog = TestUtils.getDialog(InputDialogElement) as InputDialogElement;
dialog.$.inputBox.value = fileName;
await TestUtils.closeDialog(dialog, true);
const result = await TestUtils.waitUntilTrue(() =>
(mockFileManager.create as sinon.SinonStub).called, 5000);
assert(!!result, 'create should be called when create button clicked');
assert((mockFileManager.create as sinon.SinonStub).calledWithExactly(
DatalabFileType.FILE, testFixture.currentFile.id, fileName),
'filemanager.create should be created with the new file args');
(mockFileManager.create as sinon.SinonStub).restore();
});
it('calls FileManager.create correctly to create a new directory', async () => {
const folderName = 'newMockDirectory';
sinon.stub(mockFileManager, 'create');
testFixture.$.newFolderButton.click();
const dialog = TestUtils.getDialog(InputDialogElement) as InputDialogElement;
dialog.$.inputBox.value = folderName;
await TestUtils.closeDialog(dialog, true);
const result = await TestUtils.waitUntilTrue(() =>
(mockFileManager.create as sinon.SinonStub).called, 5000);
assert(!!result, 'create should be called when create button clicked');
assert((mockFileManager.create as sinon.SinonStub).calledWithExactly(
DatalabFileType.DIRECTORY, testFixture.currentFile.id, folderName),
'filemanager.create should be created with the new folder args');
(mockFileManager.create as sinon.SinonStub).restore();
});
});
}); | the_stack |
export const INTERNAL_LAYER_PREFIX: string;
/**
* Symbol properties containing external resources
*/
export const RESOURCE_PROPERTIES: string[];
/**
* Corresponding size properties for the above resource properties
*/
export const RESOURCE_SIZE_PROPERTIES: Array<Array<string | null>>;
/**
* numeric symbol properties
*/
export const NUMERICAL_PROPERTIES: object;
/**
* color symbol properties
*/
export const COLOR_PROPERTIES: string[];
export interface MapOptions {
center: Coordinate | number[] | undefined;
zoom: number | undefined;
spatialReference?: object | undefined;
baseLayer?: Layer | undefined;
layers?: Layer[] | undefined;
attribution?: boolean | control.AttributionOptions | undefined;
// allow map to drag pitching, true by default
dragPitch?: boolean | undefined;
// allow map to drag rotating, true by default
dragRotate?: boolean | undefined;
// enable map to drag pitching and rotating at the same time, false by default
dragRotatePitch?: boolean | undefined;
dragPan?: boolean | undefined;
pitch?: number | undefined;
zoomControl?: boolean | object | undefined;
scaleControl?: boolean | object | undefined;
overviewControl?: boolean | undefined;
centerCross?: boolean | undefined;
minZoom?: number | undefined;
maxZoom?: number | undefined;
draggable?: boolean | undefined; // disable draggble
scrollWheelZoom?: boolean | undefined; // disable scroll wheel zoom
dblClickZoom?: boolean | undefined; // disable doubleclick
touchZoom?: boolean | undefined;
doubleClickZoom?: boolean | undefined;
layerSwitcherControl?: object | undefined;
}
export interface MapJsonOptions {
baseLayer?: any;
layers?: any;
}
export interface LayerOptions {
attribution?: string | undefined;
minZoom?: number | undefined;
maxZoom?: number | undefined;
visible?: boolean | undefined;
opacity?: number | undefined;
zindex?: number | undefined;
hitDetect?: boolean | undefined;
renderer?: string | undefined;
// context.globalCompositeOperation, 'source-over' in default
globalCompositeOperation?: string | undefined;
debugOutline?: string | undefined;
cssFilter?: string | null | undefined;
forceRenderOnMoving?: boolean | undefined;
forceRenderOnZooming?: boolean | undefined;
forceRenderOnRotating?: boolean | undefined;
style?: any;
}
export type urlTemplateFun = (...param: any[]) => string;
export interface TileLayerOptions extends LayerOptions {
urlTemplate: string | urlTemplateFun;
subdomains?: string[] | number[] | undefined;
spatialReference?: object | undefined;
tileSize?: number[] | undefined;
offset?: number[] | undefined;
tileSystem?: number[] | undefined;
maxAvailableZoom?: number | undefined;
repeatWorld?: boolean | undefined;
background?: boolean | undefined;
backgroundZoomDiff?: number | undefined;
placeholder?: boolean | undefined;
fragmentShader?: string | undefined;
crossOrigin?: string | undefined;
fadeAnimation?: boolean | undefined;
debug?: boolean | undefined;
maxCacheSize?: number | undefined;
cascadeTiles?: boolean | undefined;
zoomOffset?: number | undefined;
tileRetryCount?: number | undefined;
}
export interface WMSTileLayerOptions extends TileLayerOptions {
service?: string | undefined;
layers: string;
styles?: string | undefined;
format?: string | undefined;
transparent?: boolean | undefined;
version?: string | undefined;
crs?: string | undefined;
uppercase?: boolean | undefined;
detectRetina?: string | undefined;
}
export interface VectorLayerOptions extends LayerOptions {
debug?: boolean | undefined;
enableSimplify?: boolean | undefined;
cursor?: string | undefined;
geometryEvents?: boolean | undefined;
defaultIconSize?: boolean | undefined;
enableAltitude?: boolean | undefined;
altitudeProperty?: string | undefined;
drawAltitude?: object | undefined;
altitude?: number | undefined;
drawImmediate?: boolean | undefined;
}
export interface CanvasLayerOptions extends LayerOptions {
doubleBuffer?: boolean | undefined;
animation?: boolean | undefined;
fps?: boolean | undefined;
}
export interface ImageLayerOptions extends LayerOptions {
crossOrigin?: string | undefined;
renderer?: string | undefined;
}
export interface GeometryOptions {
id?: string | number | undefined;
visible?: boolean | undefined;
editable?: boolean | undefined;
interactive?: boolean | undefined;
cursor?: string | null | undefined;
measure?: string | undefined;
draggable?: boolean | undefined;
dragShadow?: boolean | undefined;
drawOnAxis?: string | null | undefined;
zIndex?: number | undefined;
properties?: object | undefined;
symbol?: object | undefined;
shadowBlur?: number | undefined;
shadowColor?: string | undefined;
}
export interface PathOptions extends GeometryOptions {
smoothness?: number | undefined;
enableSimplify?: boolean | undefined;
simplifyTolerance?: number | undefined;
enableClip?: boolean | undefined;
symbol?: object | undefined;
}
export interface MarkerOptions extends GeometryOptions {
hitTestForEvent?: boolean | undefined;
}
export interface LabelOptions extends GeometryOptions {
boxStyle?: object | undefined;
textSymbol?: object | undefined;
hitTestForEvent?: string | undefined;
}
export interface TextBoxOptions extends GeometryOptions {
textStyle?: object | undefined;
boxSymbol?: object | undefined;
hitTestForEvent?: string | undefined;
}
export interface LineStringOptions extends PathOptions {
arrowStyle?: string | number[] | null | undefined;
arrowPlacement?: string | undefined;
}
export interface ArcCurveOptions extends LineStringOptions {
arcDegree?: number | undefined;
}
export interface ConnectorLineOptions extends LineStringOptions {
showOn?: string | undefined;
}
export interface ArcConnectorLineOptions extends ConnectorLineOptions, ArcCurveOptions {}
export interface EllipseOptions extends PathOptions {
numberOfShellPoints?: number | undefined;
}
export interface DrawToolOptions {
// doubleClickZoom?: boolean;
// ignoreMouseleave?: boolean
mode?: string | undefined;
symbol?: object | undefined;
once?: boolean | undefined;
autoPanAtEdge?: boolean | undefined;
}
export interface DrawToolModeActionOptions {
action: object;
create: object;
update: object;
generate: object;
}
export interface DistanceToolOptions extends DrawToolOptions {
language?: string | undefined;
metric?: boolean | undefined;
imperial?: boolean | undefined;
vertexSymbol?: object | undefined;
labelOptions?: object | undefined;
clearButtonSymbol?: any[] | undefined;
}
export namespace control {
interface ZoomOptions {
position?: string | object | undefined;
slider?: boolean | undefined;
zoomLevel?: boolean | undefined;
}
interface LayerSwitcherOptions {
position?: string | object | undefined;
baseTitle?: string | object | undefined;
overlayTitle?: string | object | undefined;
excludeLayers?: any[] | undefined;
containerClass?: string | object | undefined;
}
interface AttributionOptions {
position?: string | object | undefined;
content?: string | undefined;
}
interface ScaleOptions {
position?: string | object | undefined;
maxWidth?: number | undefined;
metric?: boolean | undefined;
imperial?: boolean | undefined;
containerClass?: string | object | null | undefined;
}
interface PanelOptions {
position?: string | object | undefined;
draggable?: boolean | undefined;
custom?: boolean | undefined;
content?: string | HTMLElement | undefined;
closeButton?: boolean | undefined;
}
interface ToolbarOptions {
position?: string | object | undefined;
vertical?: boolean | undefined;
reverseMenu?: boolean | undefined;
items: any[];
}
interface OverviewOptions {
position?: string | object | undefined;
level?: number | undefined;
maximize?: boolean | undefined;
size?: object | undefined;
symbol?: object | undefined;
containerClass?: string | undefined;
buttonClass?: string | undefined;
}
abstract class Control extends Eventable {
// new(options?: object): Control
/**
* Adds the control to a map.
* @param map
* @returns this
* @fires control.Control#add
*/
addTo(map: Map): this;
/**
* update control container
* @return this
*/
update(): this;
/**
* Get the map that the control is added to.
* @return
*/
getMap(): Map;
/**
* Get the position of the control
* @return
*/
getPosition(): object;
/**
* update the control's position
* @param position - can be one of 'top-left', 'top-right', 'bottom-left', 'bottom-right' or a position object like {'top': 40,'left': 60}
* @return this
* @fires control.Control#positionchange
*/
setPosition(position: string | object): this;
/**
* Get the container point of the control.
* @return
*/
getContainerPoint(): Point;
/**
* Get the control's container.
* Container is a div element wrapping the control's dom and decides the control's position and display.
* @return
*/
getContainer(): HTMLElement;
/**
* Get html dom element of the control
* @return
*/
getDOM(): HTMLElement;
/**
* Show
* @return this
*/
show(): this;
/**
* Hide
* @return this
*/
hide(): this;
/**
* Whether the control is visible
* @return
*/
isVisible(): boolean;
/**
* Remove itself from the map
* @return this
* @fires control.Control#remove
*/
remove(): this;
}
class Zoom extends Control {
constructor(options: ZoomOptions);
/**
* method to build DOM of the control
* @param map map to build on
* @return
*/
buildOn(map: Map): HTMLElement;
}
class LayerSwitcher extends Control {
constructor(options: LayerSwitcherOptions);
/**
* method to build DOM of the control
* @return
*/
buildOn(): HTMLElement;
}
class Attribution extends Control {
constructor(options: AttributionOptions);
}
class Scale extends Control {
constructor(options: ScaleOptions);
/**
* method to build DOM of the control
* @param map map to build on
* @return
*/
buildOn(map: Map): HTMLElement;
}
class Panel extends Control {
constructor(options: PanelOptions);
/**
* method to build DOM of the control
* @param map map to build on
* @return
*/
buildOn(map: Map): HTMLElement;
/**
* update control container
* @return this
*/
update(): this;
/**
* Set the content of the Panel.
* @param content - content of the infowindow.
* return this
* @fires Panel#contentchange
*/
setContent(content: string | HTMLElement): this;
/**
* Get content of the infowindow.
* @return - content of the infowindow
*/
getContent(): string | HTMLElement;
}
class Toolbar extends Control {
constructor(options: ToolbarOptions);
/**
* method to build DOM of the control
* @param map map to build on
* @return
*/
buildOn(map: Map): HTMLElement;
}
class Overview extends Control {
constructor(options: OverviewOptions);
/**
* method to build DOM of the control
* @param map map to build on
* @return
*/
buildOn(map: Map): HTMLElement;
/**
* Maximize overview control
* @returns
*/
maxmize(): this;
/**
* Minimize overview control
* @returns
*/
minimize(): this;
/**
* Return overview's map object
* @returns
*/
getOverviewMap(): Map;
}
}
export namespace ui {
interface UIComponentOptions {
eventsPropagation?: boolean | undefined;
eventsToStop?: boolean | undefined;
dx?: number | undefined;
dy?: number | undefined;
autoPan?: boolean | undefined;
autoPanDuration?: boolean | undefined;
single?: boolean | undefined;
animation?: string | undefined;
animationDuration?: number | undefined;
pitchWithMap?: boolean | undefined;
rotateWithMap?: boolean | undefined;
}
interface UIMarkerOptions extends UIComponentOptions {
draggable?: boolean | undefined;
content: string | HTMLElement;
}
interface ToolTipOptions extends UIComponentOptions {
width?: number | undefined;
height?: number | undefined;
cssName?: string | undefined;
showTimeout?: number | undefined;
}
interface MenuOptions extends UIComponentOptions {
width?: number | undefined;
maxHeight?: number | undefined;
custom?: string | HTMLElement | undefined;
items?: object[] | string | HTMLElement | undefined;
}
abstract class UIComponent extends Eventable {
_coordinate: Coordinate;
_flashTimeout: number;
/**
* Adds the UI Component to a geometry or a map
* @param owner - geometry or map to addto.
* @returns this
* @fires ui.UIComponent#add
*/
addTo(owner: Geometry | Map): this;
/**
* Get the map it added to
* @return map instance
*/
getMap(): Map;
/**
* Show the UI Component, if it is a global single one, it will close previous one.
* @param [coordinate=null] - coordinate to show, default is owner's center
* @return this
* @fires ui.UIComponent#showstart
* @fires ui.UIComponent#showend
*/
show(coordinate?: Coordinate): this;
/**
* Hide the UI Component.
* @return this
* @fires ui.UIComponent#hide
*/
hide(): this;
/**
* Decide whether the ui component is open
* @returns true|false
*/
isVisible(): boolean;
/**
* Remove the UI Component
* @return this
* @fires ui.UIComponent#hide
* @fires ui.UIComponent#remove
*/
remove(): this;
/**
* Get pixel size of the UI Component.
* @return size
*/
getSize(): Size;
}
class InfoWindow extends UIComponent {
constructor(options: UIComponentOptions | object);
/**
* Adds the UI Component to a geometry or a map
* @param owner - geometry or map to addto.
* @returns this
* @fires UIComponent#add
*/
addTo(owner: Geometry | Map): this;
/**
* Set the content of the infowindow.
* @param content - content of the infowindow.
* return {InfoWindow} this
* @fires InfoWindow#contentchange
*/
setContent(content: string | HTMLElement): this;
/**
* Get content of the infowindow.
* @return - content of the infowindow
*/
getContent(): string | HTMLElement;
/**
* Set the title of the infowindow.
* @param title - title of the infowindow.
* return {InfoWindow} this
* @fires InfoWindow#titlechange
*/
setTitle(title: string | HTMLElement): this;
/**
* Get title of the infowindow.
* @return - content of the infowindow
*/
getTitle(): string | HTMLElement;
/**
* Gets InfoWindow's transform origin for animation transform
*
* @return transform origin
*/
getTransformOrigin(): Point;
}
class Menuable {
/**
* Set a context menu
* @param options - menu options
* @return this
* @example
* foo.setMenu({
* 'width' : 160,
* 'custom' : false,
* 'items' : [
* // return false to prevent event propagation
* {'item': 'Query', 'click': function() {alert('Query Clicked!'); return false;}},
* '-',
* {'item': 'Edit', 'click': function() {alert('Edit Clicked!')}},
* {'item': 'About', 'click': function() {alert('About Clicked!')}}
* ]
* });
*/
setMenu(options: object): this;
/**
* Open the context menu, default on the center of the geometry or map.
* @param [coordinate=null] - coordinate to open the context menu
* @return this
*/
openMenu(coordinate?: Coordinate): this;
/**
* Set menu items to the context menu
* @param items - menu items
* @return this
*/
setMenuItems(items: object[]): this;
/**
* Get the context menu items
* @return
*/
getMenuItems(): object[];
/**
* Close the contexnt menu
* @return this
*/
closeMenu(): this;
/**
* Remove the context menu
* @return this
*/
removeMenu(): this;
}
type flashCallbackFun = (...param: any[]) => any;
class UIMarker extends UIComponent {
constructor(coordinate: Coordinate | number[], options: UIMarkerOptions);
/**
* Sets the coordinates
* @param coordinates - UIMarker's coordinate
* @returns this
* @fires UIMarker#positionchange
*/
setCoordinates(coordinates: Coordinate): this;
/**
* Gets the coordinates
* @return coordinates
*/
getCoordinates(): Coordinate;
/**
* Sets the content of the UIMarker
* @param content - UIMarker's content
* @returns this
* @fires UIMarker#contentchange
*/
setContent(content: string | HTMLElement): this;
/**
* Gets the content of the UIMarker
* @return content
*/
getContent(): string | HTMLElement;
/**
* Show the UIMarker
* @returns this
* @fires UIMarker#showstart
* @fires UIMarker#showend
*/
show(): this;
/**
* Flash the UIMarker, show and hide by certain internal for times of count.
*
* @param [interval=100] - interval of flash, in millisecond (ms)
* @param [count=4] - flash times
* @param [cb=null] - callback function when flash ended
* @param context - callback context
* @return this
*/
flash(interval?: number, count?: number, cb?: flashCallbackFun, context?: any): this;
/**
* A callback method to build UIMarker's HTMLElement
*
* @param map - map to be built on
* @return UIMarker's HTMLElement
*/
buildOn(): HTMLElement;
/**
* Gets UIMarker's HTMLElement's position offset, it's caculated dynamically accordiing to its actual size.
*
* @return offset
*/
getOffset(): Point;
/**
* Gets UIMarker's transform origin for animation transform
*
* @return transform origin
*/
getTransformOrigin(): Point;
/**
* Whether the uimarker is being dragged.
* @returns
*/
isDragging(): boolean;
}
class ToolTip extends UIComponent {
constructor(content: string, options: ToolTipOptions);
/**
* Adds the UI Component to a geometry UIMarker Other graphic elements
* @param owner - geometry to add.
* @returns this
* @fires UIComponent#add
*/
addTo(owner: Geometry): this;
/**
* set ToolTip's content's css class name.
* @param css class name - set for ToolTip's content.
*/
setStyle(cssName: string): this;
/**
* get ToolTip's content's css class name
* @returns css class name - set for ToolTip's content.
*/
getStyle(): string;
/**
* get the UI Component's content
* @returns tooltip's content
*/
getContent(): string;
/**
* remove the tooltip, this method will be called by 'this.remove()'
*/
onRemove(): void;
/**
* override UIComponent method
* ignore altitude calculation
*/
_getViewPoint(): Coordinate | Point;
}
class Menu extends UIComponent {
defaultOptions: MenuOptions;
constructor(options: MenuOptions);
/**
* Set the items of the menu.
* @param items - items of the menu
* return {ui.Menu} this
* @example
* menu.setItems([
* // return false to prevent event propagation
* {'item': 'Query', 'click': function() {alert('Query Clicked!'); return false;}},
* '-',
* {'item': 'Edit', 'click': function() {alert('Edit Clicked!')}},
* {'item': 'About', 'click': function() {alert('About Clicked!')}}
* ]);
*/
setItems(items: object[] | string | HTMLElement): this;
/**
* Get items of the menu.
* @return - items of the menu
*/
getItems(): object[] | string | HTMLElement;
/**
* Create the menu DOM.
*
* @return menu's DOM
*/
buildOn(): HTMLElement;
}
}
export namespace animation {
interface AnimationOptions {
easing?: object | undefined;
}
interface Easing {
/**
* Start slow and speed up.
* @param t Input between 0 and 1.
* @return Output between 0 and 1.
*/
in(t: number): number;
/**
* Start fast and slow down.
* @param t Input between 0 and 1.
* @return Output between 0 and 1.
*/
out(t: number): number;
/**
* Start slow, speed up, and then slow down again.
* @param t Input between 0 and 1.
* @return Output between 0 and 1.
*/
inAndOut(t: number): number;
/**
* Maintain a constant speed over time.
* @param t Input between 0 and 1.
* @return Output between 0 and 1.
*/
linear(t: number): number;
/**
* Start slow, speed up, and at the very end slow down again. This has the
* same general behavior as {@link inAndOut}, but the final slowdown
* is delayed.
* @param t Input between 0 and 1.
* @return Output between 0 and 1.
*/
upAndDown(t: number): number;
}
class Frame {
state: any;
styles: any;
}
type PlayerAnimationFun = (elapsed: number, duration: number) => Frame;
type FrameStepFun = (frame: Frame, ...params: any[]) => void;
class Player {
/**
* Create an animation player
* @param animation - animation [framing]{@link framing} function
* @param options - animation options
* @param onFrame - callback function for animation steps
*/
constructor(animation: PlayerAnimationFun, options: object, onFrame: FrameStepFun);
/**
* Start or resume the animation
* @return this
*/
play(): this;
/**
* Pause the animation
* @return this
*/
pause(): this;
/**
* Cancel the animation play and ready to play again
* @return this
*/
cancel(): this;
/**
* Finish the animation play, and can't be played any more.
* @return this
*/
finish(): this;
}
interface Animation {
speed: {
slow: number;
normal: number;
fast: number;
};
/**
* Generate a framing function
* @param styles - animation style group
* @param [options=null] - options
* @param [options.easing=null] - animation easing
* @return framing function helps to generate animation frames.
*/
framing(styles: object[], options?: AnimationOptions): PlayerAnimationFun;
/**
* Create an animation player
* @param styles - styles to animate
* @param options - animation options
* @param step - callback function for animation steps
* @return player
*/
animate(styles: object, options: object, step: FrameStepFun): Player;
}
const Animation: Animation;
}
export namespace measurer {
interface Common {
/**
* Measure length between coordinate c1 and coordinate c2
* @param c1 coordinate
* @param c2 coordinate
* @return length
* measurer.Common.measureLength
*/
measureLength(c1: Coordinate, c2: Coordinate): number;
}
const Common: Common;
interface Identity extends Common {
measure: string;
_rotate: (c: Coordinate, pivot: Coordinate, angle: number) => Coordinate;
/**
* Measure the length between 2 coordinates.
* @param c1
* @param c2
* @return
*/
measureLenBetween(c1: Coordinate, c2: Coordinate): number;
/**
* Measure the area closed by the given coordinates.
* @param coordinates
* @return
*/
measureArea(coordinates: Coordinate[]): number;
/**
* Locate a coordinate from the given source coordinate with a x-axis distance and a y-axis distance.
* @param c - source coordinate
* @param xDist - x-axis distance
* @param yDist - y-axis distance
* @return
*/
_locate(c: Coordinate, xDist: number, yDist: number): Coordinate;
}
const Identity: Identity;
interface Measurer {
/**
* Get a measurer instance.
* @param name - code of the measurer: 'EPSG:4326', 'Identity', 'BAIDU'
* @return a measurer object
* measurer.Measurer.getInstance
*/
getInstance(name: string): object;
}
const Measurer: Measurer;
interface WGS84Sphere extends Common {
/**
* Measure the length between 2 coordinates.
* @param c1
* @param c2
* @return
*/
measureLenBetween(c1: Coordinate, c2: Coordinate): number;
/**
* Measure the area closed by the given coordinates.
* @param coordinates
* @return
*/
measureArea(coordinates: Coordinate[]): number;
/**
* Locate a coordinate from the given source coordinate with a x-axis distance and a y-axis distance.
* @param c - source coordinate
* @param xDist - x-axis distance
* @param yDist - y-axis distance
* @return
*/
locate(c: Coordinate, xDist: number, yDist: number): Coordinate;
/**
* Rotate a coordinate of given angle around pivot
* @param c - source coordinate
* @param pivot - pivot
* @param angle - angle in degree
* @return
*/
rotate(c: Coordinate, pivot: Coordinate, angle: number): Coordinate;
}
const WGS84Sphere: WGS84Sphere;
interface DEFAULT extends WGS84Sphere {
_default: string;
}
const DEFAULT: DEFAULT;
interface BaiduSphere extends Common {
/**
* Measure the length between 2 coordinates.
* @param c1
* @param c2
* @return
*/
measureLenBetween(c1: Coordinate, c2: Coordinate): number;
/**
* Measure the area closed by the given coordinates.
* @param coordinates
* @return
*/
measureArea(coordinates: Coordinate[]): number;
/**
* Locate a coordinate from the given source coordinate with a x-axis distance and a y-axis distance.
* @param c - source coordinate
* @param xDist - x-axis distance
* @param yDist - y-axis distance
*/
locate(c: Coordinate, xDist: number, yDist: number): Coordinate;
/**
* Rotate a coordinate of given angle around pivot
* @param c - source coordinate
* @param pivot - pivot
* @param angle - angle in degree
* @return
*/
rotate(c: Coordinate, pivot: Coordinate, angle: number): Coordinate;
}
const BaiduSphere: BaiduSphere;
}
export namespace projection {
interface Common {
/**
* Project a geographical coordinate to a projected coordinate (2d coordinate)
* @param p - coordinate to project
* @return
* projection.Common.project
*/
project(p: Coordinate): Coordinate;
/**
* Unproject a projected coordinate to a geographical coordinate (2d coordinate)
* @param p - coordinate to project
* @return
* projection.Common.unproject
*/
unproject(p: Coordinate): Coordinate;
/**
* Project a group of geographical coordinates to projected coordinates.
* @param coordinates - coordinates to project
* @return
* projection.Common.projectCoords
*/
projectCoords(
coordinates: Coordinate[] | Coordinate[][] | Coordinate[][][],
): Coordinate[] | Coordinate[][] | Coordinate[][][];
/**
* Unproject a group of projected coordinates to geographical coordinates.
* @param projCoords - projected coordinates to unproject
* @return
* projection.Common.unprojectCoords
*/
unprojectCoords(
projCoords: Coordinate[] | Coordinate[][] | Coordinate[][][],
): Coordinate[] | Coordinate[][] | Coordinate[][][];
/**
* Whether the projection is spherical
* @return
*/
isSphere(): boolean;
/**
* If the projected coord out of the sphere
* @param pcoord projected coord
* @return
*/
isOutSphere(pcoord: Coordinate): boolean;
/**
* Wrap the projected coord in the sphere
* @param pcoord projected coord
* @return wrapped projected coord
*/
wrapCoord(pcoord: Coordinate): Coordinate;
}
const Common: Common;
interface EPSG3857 extends Common, measurer.WGS84Sphere {
code: string;
}
const EPSG3857: EPSG3857;
interface DEFAULT extends EPSG3857 {
_default: string;
}
const DEFAULT: DEFAULT;
interface BAIDU extends Common, measurer.BaiduSphere {
code: string;
}
const BAIDU: BAIDU;
interface EPSG4326 extends Common, measurer.WGS84Sphere {
code: string;
}
const EPSG4326: EPSG4326;
interface EPSG4490 extends EPSG4326, measurer.WGS84Sphere {
code: string;
}
const EPSG4490: EPSG4490;
interface DIDENTITY extends Common, measurer.Identity {
code: string;
}
const IDENTITY: DIDENTITY;
}
export namespace renderer {
abstract class CanvasRenderer extends Class {
layer: any;
canvas: HTMLCanvasElement;
context: CanvasRenderingContext2D;
constructor(layer: Layer);
/**
* Render the layer.
* Call checkResources
*/
render(): void;
/**
* Check if has any external resources to load
* If yes, load the resources before calling draw method
*
* checkResources
*
* @returns an array of resource arrays [ [url1, width, height], [url2, width, height], [url3, width, height] .. ]
* renderer.CanvasRenderer
*/
checkResources(): Array<Array<[]>>;
/**
* a required abstract method to implement
* draw the layer when map is not interacting
*
*
* draw
* renderer.CanvasRenderer
*/
draw(): void;
/**
* an optional abstract method to implement
* draw the layer when map is interacting (moving/zooming/dragrotating)
*
*
* drawOnInteracting
* @param eventParam event parameters
* renderer.CanvasRenderer
*/
drawOnInteracting(eventParam: object): void;
/**
* Ask whether the layer renderer needs to redraw
* @return
*/
needToRedraw(): boolean;
/**
* A callback for overriding when drawOnInteracting is skipped due to low fps
*/
onSkipDrawOnInteracting(): void;
/**
* Whether must call render instead of drawOnInteracting when map is interacting
*/
mustRenderOnInteracting(): void;
/**
* Set to redraw, ask map to call draw/drawOnInteracting to redraw the layer
*/
setToRedraw(): void;
/**
* Mark layer's canvas updated
*/
setCanvasUpdated(): void;
/**
* Only called by map's renderer to check whether the layer's canvas is updated
*
* @return
*/
isCanvasUpdated(): boolean;
/**
* Remove the renderer, will be called when layer is removed
*/
remove(): void;
/**
* Get map
* @return
*/
getMap(): Map;
/**
* Get renderer's Canvas image object
* @return
*/
getCanvasImage(): HTMLCanvasElement;
/**
* Clear canvas
*/
clear(): void;
/**
* A method to help improve performance.
* If you are sure that layer's canvas is blank, returns true to save unnecessary layer works of maps.
* @return
*/
isBlank(): boolean;
/**
* Show the layer
*/
show(): void;
/**
* Hide the layer
*/
hide(): void;
/**
* Set z-index of layer
*/
setZIndex(): /*z*/ void;
/**
* Detect if there is anything painted on the given point
* @param point containerPoint
* @return
*/
hitDetect(point: Point): boolean;
/**
* loadResource from resourceUrls
* @param resourceUrls - Array of urls to load
* @param onComplete - callback after loading complete
* @param context - callback's context
* @returns
*/
loadResources(
resourceUrls: string[],
onComplete?: (...param: any) => void,
context?: object,
): Array<Promise<any>>;
/**
* Create renderer's Canvas
*/
createCanvas(): void;
/**
* Resize the canvas
* @param canvasSize the size resizing to
*/
resizeCanvas(canvasSize: Size): void;
/**
* Clear the canvas to blank
*/
clearCanvas(): void;
/**
* Prepare the canvas for rendering. <br>
* 1. Clear the canvas to blank. <br>
* 2. Clip the canvas by mask if there is any and return the mask's extent
* @return mask's extent of current zoom's 2d point.
*/
prepareCanvas(): PointExtent;
/**
* Get renderer's current view extent in 2d point
* @return view.extent, view.maskExtent, view.zoom, view.southWest
*/
getViewExtent(): object;
/**
* call when rendering completes, this will fire necessary events and call setCanvasUpdated
*/
completeRender(): void;
/**
* Get renderer's event map registered on the map
* @return events
*/
getEvents(): object;
/**
* onZoomStart
* @param param event parameters
*/
onZoomStart(param: object): void;
/**
* onZoomEnd
* @param param event parameters
*/
onZoomEnd(param: object): void;
/**
* onZooming
* @param param event parameters
*/
onZooming(param: object): void;
/**
* onMoveStart
* @param param event parameters
*/
onMoveStart(param: object): void;
/**
* onMoving
* @param param event parameters
*/
onMoving(param: object): void;
/**
* onMoveEnd
* @param param event parameters
*/
onMoveEnd(param: object): void;
/**
* onResize
* @param param event parameters
*/
onResize(param: object): void;
/**
* onDragRotateStart
* @param param event parameters
*/
onDragRotateStart(param: object): void;
/**
* onDragRotating
* @param param event parameters
*/
onDragRotating(param: object): void;
/**
* onDragRotateEnd
* @param param event parameters
*/
onDragRotateEnd(param: object): void;
/**
* onSpatialReferenceChange
* @param param event parameters
*/
onSpatialReferenceChange(param: object): void;
/**
* Get ellapsed time of previous drawing
* @return
*/
getDrawTime(): number;
}
}
export type AjaxCallbackFun = (err: any, data: any) => void;
export interface Ajax {
/**
* Get JSON data by jsonp
* from https:// gist.github.com/gf3/132080/110d1b68d7328d7bfe7e36617f7df85679a08968
* @param url - resource url
* @param cb - callback function when completed
*/
jsonp(url: string, callback: AjaxCallbackFun): Ajax;
/**
* Fetch remote resource by HTTP "GET" method
* @param url - resource url
* @param [options=null] - request options
* @param [options.headers=null] - HTTP headers
* @param [options.responseType=null] - responseType
* @param [options.credentials=null] - if with credentials, set it to "include"
* @param cb - callback function when completed
* @return Ajax
* @example
* maptalks.Ajax.get(
* 'url/to/resource',
* (err, data) => {
* if (err) {
* throw new Error(err);
* }
* // do things with data
* }
* );
*/
get(url: string, cb: AjaxCallbackFun, options?: object): Ajax;
/**
* Fetch remote resource by HTTP "POST" method
* @param url - resource url
* @param options - request options
* @param options.postData - post data
* @param [options.headers=null] - HTTP headers
* @param cb - callback function when completed
* @return Ajax
* @example
* maptalks.Ajax.post(
* 'url/to/post',
* {
* postData : {
* 'param0' : 'val0',
* 'param1' : 1
* }
* },
* (err, data) => {
* if (err) {
* throw new Error(err);
* }
* // do things with data
* }
* );
*/
post(url: string, options: object, cb: AjaxCallbackFun): Ajax;
/**
* Fetch resource as arraybuffer.
* @param url - url
* @param [options=null] - options, same as Ajax.get
* @param cb - callback function when completed.
* @example
* maptalks.Ajax.getArrayBuffer(
* 'url/to/resource.bin',
* (err, data) => {
* if (err) {
* throw new Error(err);
* }
* // data is a binary array
* }
* );
*/
getArrayBuffer(url: string, options?: object, cb?: AjaxCallbackFun): Ajax;
/**
* Fetch resource as a JSON Object.
* @param url - json's url
* @param [options=null] - optional options
* @param [options.jsonp=false] - fetch by jsonp, false by default
* @param cb - callback function when completed.
* @example
* maptalks.Ajax.getJSON(
* 'url/to/resource.json',
* { jsonp : true },
* (err, json) => {
* if (err) {
* throw new Error(err);
* }
* // json is a JSON Object
* console.log(json.foo);
* }
* );
*
*/
getJSON(url: string, options?: object, cb?: AjaxCallbackFun): Ajax;
}
export const Ajax: Ajax;
export class MapboxUtil {}
export namespace Util {
const emptyImageUrl: string;
/**
* Merges the properties of sources into destination object.
* @param dest - object to extend
* @param src - sources
* @return
* Util
*/
function extend(dest: object, ...src: object[]): object;
/**
* Whether the object is null or undefined.
* @param obj - object
* @return
* Util
*/
function isNil(obj: object): boolean;
/**
* Whether val is a number and not a NaN.
* @param val - val
* @return
* Util
*/
function isNumber(val: object): boolean;
/**
* Whether a number is an integer
* @param n
* @return
* Util
*/
function isInteger(n: number): boolean;
/**
* Whether the obj is a javascript object.
* @param obj - object
* @return
* Util
*/
function isObject(obj: object): boolean;
/**
* Check whether the object is a string
* @param obj
* @return
* Util
*/
function isString(obj: object): boolean;
/**
* Check whether the object is a function
* @param obj
* @return const
*/
function isFunction(obj: object): boolean;
/**
* Check whether the object owns the property.
* @param obj - object
* @param key - property
* @return
* Util
*/
function hasOwn(obj: object, key: string): boolean;
/**
* Determine if an object has any properties.
* @param object The object to check.
* @returns The object is empty
*/
function isEmpty(val: object): boolean;
/**
* caculate the distance from a point to a segment.
* @param p
* @param p1
* @param p2
* @return distance from p to (p1, p2)
* Util
*/
function distanceToSegment(p: Point, p1: Point, p2: Point): number;
/**
* Whether the coordinate is inside the polygon
* @param - polygon
* @param - coordinate
* @return
* Util
*/
function pointInsidePolygon(p: Polygon, points: Coordinate): boolean;
/**
* Translate symbol properties to SVG properties
* @param s - object with symbol properties
* @return object with SVG properties
* Util
*/
function translateToSVGStyles(s: object): object;
/**
* Get SVG Base64 String from a marker symbol with (markerType : path)
* @param symbol - symbol with markerType of path
* @return SVG Base64 String
* Util
*/
function getMarkerPathBase64(symbol: object): string;
/**
* Get external resources from the given symbol
* @param symbol - symbol
* @param toAbsolute - whether convert url to aboslute
* @return - resource urls
* Util
*/
function getExternalResources(symbol: object, toAbsolute: boolean): string[];
/**
* Whether the color is a gradient
* @param g - color to test
* @return
* Util
*/
function isGradient(g: object): boolean;
/**
* Get stamp of a gradient color object.
* @param g gradient color object
* @return gradient stamp
* Util
*/
function getGradientStamp(g: object): string;
/**
* Get stamp of a symbol
* @param symbol symbol
* @return symbol's stamp
* Util
*/
function getSymbolStamp(symbol: object | object[]): string;
/**
* Reduce opacity of the color by ratio
* @param symbol symbols to set
* @param ratio ratio of opacity to reduce
* @return new symbol or symbols
* Util
*/
function lowerSymbolOpacity(symbol: object | object[], ratio: number): object | object[];
/**
* Merges the properties of sources into the symbol. <br>
* @param symbol symbol to extend
* @param src - sources
* @return merged symbol
* Util
*/
function extendSymbol(symbol: object | object[]): object | object[];
/**
* Polyfill of RequestAnimationFrame
* @param fn callback
* @return request id
* Util
*/
function requestAnimFrame(fn: (...params: any[]) => void): number;
/**
* Polyfill of cancelAnimationFrame
* @param request id
* Util
*/
function cancelAnimFrame(id: number): void;
/**
* Parse a JSON string to a object
* @param str - a JSON string
* @return
* Util
*/
function parseJSON(str: string): object;
/**
* Compute degree bewteen 2 points.
* @param p1 point 1
* @param p2 point 2
* @return degree between 2 points
* Util
*/
function computeDegree(p1: Point, p2: Point): number;
}
export type DomEventHandlerFun = (context: HTMLElement | object, e: Event) => void;
export namespace DomUtil {
/**
* Vendor-prefixed fransform style name (e.g. `'webkitTransform'` for WebKit).
* TRANSFORM
* DomUtil
*
*/
const TRANSFORM: string;
/**
* Vendor-prefixed tfransform-origin name (e.g. `'webkitTransformOrigin'` for WebKit).
* TRANSFORMORIGIN
* DomUtil
*
*/
const TRANSFORMORIGIN: string;
/**
* Vendor-prefixed transition name (e.g. `'WebkitTransition'` for WebKit).
* TRANSITION
* DomUtil
*
*/
const TRANSITION: string;
/**
* Vendor-prefixed filter name (e.g. `'WebkitFilter'` for WebKit).
* FILTER
* DomUtil
*
*/
const CSSFILTER: string;
function createEl(tagName: string, className: string): HTMLElement;
/**
* Create a html element on the specified container
* @param tagName
* @param style - css styles
* @param container
* @return
* DomUtil
*/
function createElOn(tagName: string, style: string, container: HTMLElement): HTMLElement;
/**
* Adds a event listener to the dom element.
* @param obj - dom element to listen on
* @param typeArr - event types, seperated by space
* @param handler - listener function
* @param context - function context
* DomUtil
*/
function addDomEvent(obj: HTMLElement, typeArr: string, handler: DomEventHandlerFun, context: object): void;
/**
* Removes event listener from a dom element
* @param obj - dom element
* @param typeArr - event types, separated by space
* @param handler - listening function
* DomUtil
*/
function removeDomEvent(obj: HTMLElement, typeArr: string, handler: DomEventHandlerFun): void;
/**
* Check if event type of the dom is listened by the handler
* @param obj - dom element to check
* @param typeArr - event
* @param handler - the listening function
* @return - the handler's index in the listener chain, returns -1 if not.
* DomUtil
*/
function listensDomEvent(obj: HTMLElement, typeArr: string, handler: DomEventHandlerFun): number;
/**
* Prevent default behavior of the browser. <br/>
* preventDefault Cancels the event if it is cancelable, without stopping further propagation of the event.
* @param const event - browser event
* DomUtil
*/
function preventDefault(event: Event): void;
/**
* Stop browser event propagation
* @param const e - browser event.
* DomUtil
*/
function stopPropagation(e: Event): void;
/**
* Get the dom element's current position or offset its position by offset
* @param dom - HTMLElement
* @param [offset=null] - position to set.
* @return - dom element's current position if offset is null.
* DomUtil
*/
function offsetDom(dom: HTMLElement, offset: Point): Point;
/**
* Compute dom's position
* @param dom
* @return
* DomUtil
*/
function computeDomPosition(dom: HTMLElement): number[];
/**
* Get event's position from the top-left corner of the dom container
* @param const ev event
* @return
* DomUtil
*/
function getEventContainerPoint(ev: Event): Point;
/**
* set css style to the dom element
* @param dom dom element
* @param strCss css text
* DomUtil
*/
function setStyle(dom: HTMLElement, strCss: string): void;
/**
* Whether the dom has the given css class.
* @param el HTML Element
* @param name css class
* DomUtil
*/
function hasClass(el: HTMLElement, name: string): void;
/**
* add css class to dom element
* @param el HTML Element
* @param name css class
* DomUtil
*/
function addClass(el: HTMLElement, name: string): void;
/**
* Set dom's css class
* @param el HTML Element
* @param name css class
* DomUtil
*/
function setClass(el: HTMLElement, name: string): void;
/**
* Get dom's css class
* @param name css class
* @retrun {String} class字符串
* DomUtil
*/
function getClass(el: string): string;
/**
* Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
* @param el
* @param offset
* DomUtil
*/
function setTransform(el: HTMLElement, offset: Point): void;
}
export namespace StringUtil {
/**
* Trim the string
* @param str
* @return
* StringUtil
*/
function trim(str: string): string;
/**
* Escape special characters from string.
* Including: \b \t \r \v \f
* @param str string to escape
* @return
* StringUtil
*/
function escapeSpecialChars(str: string): string;
/**
* Split string by specified char
* @param chr - char to split
* @return
* StringUtil
*/
function splitWords(chr: string): string[];
/**
* Gets width of the text with a certain font.
* More performant than stringLength.
* @param text - text to measure
* @param font - font of the text, same as the CSS font.
* @return
* StringUtil
*/
function stringWidth(text: string, font: string): number;
// const fontHeight = {};
/**
* Gets size in pixel of the text with a certain font.
* @param text - text to measure
* @param font - font of the text, same as the CSS font.
* @return
* StringUtil
*/
function stringLength(text: string, font: string, size?: Size): Size;
/**
* Split text content by dom.
* @param content - content to split
* @param font - font of the text, same as the CSS font.
* @return wrapWidth - width to wrap
* @return
* StringUtil
*/
function splitContent(content: string, font: string, wrapWidth: number): string[];
/**
* Replace variables wrapped by square brackets ({foo}) with actual values in props.
* @example
* // will returns 'John is awesome'
* const actual = replaceVariable('{foo} is awesome', {'foo' : 'John'});
* @param str - string to replace
* @param props - variable value properties
* @return
* StringUtil
*/
function replaceVariable(str: string, props: object): string;
/**
* Gets text's align point according to the horizontalAlignment and verticalAlignment
* @param size - text size
* @param horizontalAlignment - horizontalAlignment: left/middle/right
* @param verticalAlignment - verticalAlignment: top/middle/bottom
* @return
* StringUtil
*/
function getAlignPoint(size: Size, horizontalAlignment: string, verticalAlignment: string): Point;
/**
* Returns CSS Font from a symbol with text styles.
* @param style symbol with text styles
* @return CSS Font String
* StringUtil
*/
function getFont(style: object): string;
/**
* Split a text to multiple rows according to the style.
* @param text - text to split
* @param style - text style
* @return the object's structure: { rowNum: rowNum, textSize: textSize, rows: textRows, rawSize : rawSize }
* StringUtil
*/
function splitTextToRow(text: string, style: object): object[];
}
/**
* This library uses ES2015 class system. <br />
* Class is the root class of class hierachy. <br />
* It provides utility methods to make it easier to manage configration options, merge mixins and add init hooks.
* @example
* var defaultOptions = {
* 'foo' : 'bar'
* };
* class Foo extends maptalks.Class {
* constructor(id, options) {
* super(options);
* this.setId(id);
* }
*
* setId(id) {
* this.id = id;
* }
*
* whenCreated() {
* // .....
* }
* }
*
* Foo.mergeOptions(defaultOptions);
*
* Foo.addInitHook('whenCreated');
* @category core
*
*/
export abstract class Class {
id: string | number;
options: any;
/**
* Create an object, set options if given and call all the init hooks.<br />
* Options is where the object manages its configuration. Options passed to the object will be merged with parent's instead of overriding it.
*
* @param options - options to set
*/
constructor(options?: any);
/**
* Create an object, set options if given and call all the init hooks.<br />
* Options is where the object manages its configuration. Options passed to the object will be merged with parent's instead of overriding it.
*
* @param options - options to set
*/
constructor(id: string | number, options?: any);
/**
* Visit and call all the init hooks defined on Class and its parents.
* @return this
*/
callInitHooks(): this;
/**
* Merges options with the default options of the object.
* @param options - options to set
* @return this
*/
setOptions(options: object): this;
/**
* 1. Return object's options if no parameter is provided. <br/>
*
* 2. update an option and enable/disable the handler if a handler with the same name existed.
* @example
* // Get marker's options;
* var options = marker.config();
* // Set map's option "draggable" to false and disable map's draggable handler.
* map.config('draggable', false);
* // You can update more than one options like this:
* map.config({
* 'scrollWheelZoom' : false,
* 'doubleClickZoom' : false
* });
* @param conf - config to update
* @return this
*/
config(...conf: any[]): this;
/**
* Default callback when config is called
*/
onConfig(): /*conf*/ void;
/**
* Add an init hook, which will be called when the object is initiated. <br>
* It is useful in plugin developing to do things when creating objects without changing class's constructor.
* @param fn - a hook function or name of the hook function
* @param args - arguments for the init hook function
*/
static addInitHook(fn: (...param: any) => void, ...args: any[]): void;
/**
* Mixin the specified objects into the class as prototype properties or methods.
* @param sources - objects to mixin
*/
static include(...sources: object[]): void;
/**
* Mixin options with the class's default options. <br />
* @param options - options to merge.
*/
static mergeOptions(options: object): void;
}
/** Common methods for classes can be rendered, e.g. Map, Layers */
export class Renderable extends Class {
/**
* Register a renderer class with the given name.
* @param name - renderer's register key
* @param clazz - renderer's class, a function (not necessarily a [Class]{@link Class}).
* @return this
* Renderable.registerRenderer
*/
static registerRenderer(name: string, clazz: object): any;
/**
* Get the registered renderer class by the given name
* @param name - renderer's register key
* @return renderer's class
* Renderable.getRendererClass
*/
static getRendererClass(name: string): any;
}
export type EvenableHandlerFun = (...params: any[]) => void;
/** This provides methods used for event handling. It's a mixin and not meant to be used directly. */
export class Eventable extends Renderable {
/**
* Register a handler function to be called whenever this event is fired.
*
* @param eventsOn - event types to register, seperated by space if more than one.
* @param handler - handler function to be called
* @param [context=null] - the context of the handler
* @return this
* Eventable.on
* @example
* foo.on('mousedown mousemove mouseup', onMouseEvent, foo);
*/
on(eventsOn: string, handler: EvenableHandlerFun, context?: object): this;
/**
* Alias for [on]{@link Eventable.on}
*
* @param eventTypes - event types to register, seperated by space if more than one.
* @param handler - handler function to be called
* @param [context=null] - the context of the handler
* @return this
* Eventable.addEventListener
*/
addEventListener(eventTypes: string, handler: EvenableHandlerFun, context?: object): this;
/**
* Same as on, except the listener will only get fired once and then removed.
*
* @param eventTypes - event types to register, seperated by space if more than one.
* @param handler - listener handler
* @param [context=null] - the context of the handler
* @return this
* @example
* foo.once('mousedown mousemove mouseup', onMouseEvent, foo);
* Eventable.once
*/
once(eventTypes: string, handler: EvenableHandlerFun, context?: object): this;
/**
* Unregister the event handler for the specified event types.
*
* @param eventsOff - event types to unregister, seperated by space if more than one.
* @param handler - listener handler
* @param [context=null] - the context of the handler
* @return this
* @example
* foo.off('mousedown mousemove mouseup', onMouseEvent, foo);
* Eventable.off
*/
off(eventsOff: string, handler: EvenableHandlerFun, context?: object): this;
/**
* Alias for [off]{@link Eventable.off}
*
* @param eventTypes - event types to unregister, seperated by space if more than one.
* @param handler - listener handler
* @param [context=null] - the context of the handler
* @return this
* Eventable.removeEventListener
*/
removeEventListener(eventTypes: string, handler: EvenableHandlerFun, context?: object): this;
/**
* Returns listener's count registered for the event type.
*
* @param eventType - an event type
* @param [hanlder=null] - listener function
* @param [context=null] - the context of the handler
* @return
* Eventable.listens
*/
listens(eventType: string, handler: EvenableHandlerFun, context?: object): number;
/**
* Get all the listening event types
*
* @returns events
*/
getListeningEvents(): string[];
/**
* Copy all the event listener to the target object
* @param target - target object to copy to.
* @return this
* Eventable.copyEventListeners
*/
copyEventListeners(target: object): this;
/**
* Fire an event, causing all handlers for that event name to run.
*
* @param eventType - an event type to fire
* @param param - parameters for the listener function.
* @return this
* Eventable.fire
*/
fire(eventType: string, param: object): this;
}
/** Common methods for classes can be rendered, e.g. Map, Layers */
export class Handlerable extends Eventable {}
export interface JSONAble {
/**
* It is a static method. <br>
* Register layer for JSON serialization and assign a JSON type.
* @param type - JSON type
* JSONAble.registerJSONType
*/
registerJSONType(type: string): void;
/**
* It is a static method. <br>
* Get class of input JSON type
* @param type - JSON type
* @return Class
* JSONAble.getJSONClass
*/
getJSONClass(type: string): Class;
/**
* Get object's JSON Type
* @return
* JSONAble.getJSONType
*/
getJSONType(): string;
}
export interface TextEditable {
/**
* Start to edit the text, editing will be ended automatically whenever map is clicked.
*
* @return this
* @fires TextMarker#edittextstart
*/
startEditText(): this;
/**
* End text edit.
*
* @return this
* @fires TextMarker#edittextend
*/
endEditText(): this;
/**
* Whether the text is being edited.
*
* @return
*/
isEditingText(): boolean;
/**
* Get the text editor which is an [ui.UIMarker]{@link ui.UIMarker}
* @return text editor
*/
getTextEditor(): ui.UIMarker;
}
export interface CenterAble {
/**
* Get geometry's center
* @return - center of the geometry
* CenterAble.getCoordinates
*/
getCoordinates(): Coordinate;
/**
* Set a new center to the geometry
* @param coordinates - new center
* @return this
* @fires Geometry#positionchange
* CenterAble.setCoordinates
*/
setCoordinates(coordinates: any): this;
}
/** The central class of the library, to create a map on a container */
export interface Map extends Handlerable, ui.Menuable {
/** Version of librar */
VERSION: string;
/** Version of the JSON schema */
JSON_VERSION: string;
/** Add hooks for additional codes when map's loading complete, useful for plugin developping. Note that it can only be called before the map is created. */
addOnLoadHook(fn: () => void): Map;
/** Reproduce a map from map's profile JSON. */
fromJSON(container: string | HTMLElement, mapJSON: object, options?: MapJsonOptions): Map;
/** Whether the map is loaded or not. */
isLoaded(): boolean;
/** Get map's container */
getContainer(): HTMLElement;
/** Get the spatial reference of the Map. */
getSpatialReference(): SpatialReference;
/** Change the spatial reference of the map. */
setSpatialReference(spatialReference: SpatialReference): this;
/** Get the projection of the map. */
getProjection(): any;
/** Get map's full extent, which is defined in map's spatial reference. */
getFullExtent(): Extent;
/** Set map's cursor style, cursor style is same with CSS. */
setCursor(cursor: string): this;
/** Reset map's cursor style. */
resetCursor(): this;
/** Get center of the map. */
getCenter(): Coordinate;
/** Set a new center to the map. */
setCenter(center: Coordinate): this;
/** Get map's size (width and height) in pixel. */
getSize(): Size;
/** Get container extent of the map */
getContainerExtent(): PointExtent;
/** Get the geographical extent of map's current view extent. */
getExtent(): Extent;
/** Get the projected geographical extent of map's current view extent. */
getProjExtent(): Extent;
/** Alias for getProjExtent */
getPrjExtent(): Extent;
/** Get the max extent that the map is restricted to. */
getMaxExtent(): Extent;
/** Sets the max extent that the map is restricted to. */
setMaxExtent(extent: Extent): this;
/** Get map's current zoom. */
getZoom(): number;
/** Caculate the target zoom if scaling from "fromZoom" by "scale" */
getZoomForScale(scale: number, fromZoom: number, isFraction: boolean): number;
/** Sets zoom of the map */
setZoom(zoom: number, options?: object): this;
/** Get the max zoom that the map can be zoom to. */
getMaxZoom(): number;
/** Sets the max zoom that the map can be zoom to. */
setMaxZoom(maxZoom: number): this;
/** Get the min zoom that the map can be zoom to. */
getMinZoom(): number;
/** Sets the min zoom that the map can be zoom to. */
setMinZoom(minZoom: number): this;
/** Maximum zoom the map has */
getMaxNativeZoom(): number;
/** Zoom for world point in WebGL context */
getGLZoom(): number;
/** Caculate scale from gl zoom to given zoom (default by current zoom) */
getGLScale(zoom?: number): number;
/** zoom in */
zoomIn(): this;
/** zoom out */
zoomOut(): this;
/** Whether the map is zooming */
isZooming(): boolean;
/** Whether the map is being interacted */
isInteracting(): boolean;
/** Sets the center and zoom at the same time. */
setCenterAndZoom(center: Coordinate, zoom: number): this;
/** Caculate the zoom level that contains the given extent with the maximum zoom level possible. */
getFitZoom(extent: Extent, isFraction: boolean): number;
/** Get map's current view (center/zoom/pitch/bearing) */
getView(): object;
/** Set map's center/zoom/pitch/bearing at one time */
setView(view: object): void;
/** Get map's resolution */
getResolution(zoom: number): number;
/** Get scale of resolutions from zoom to max zoom */
getScale(zoom: number): number;
/** Set the map to be fit for the given extent with the max zoom level possible */
fitExtent(extent: Extent, zoomOffset: number): this;
/** Get the base layer of the map. */
getBaseLayer(): Layer;
/** Sets a new base layer to the map. */
setBaseLayer(baseLayer: Layer): this;
/** Remove the base layer from the map */
removeBaseLayer(): this;
/** Get the layers of the map, except base layer (which should be by getBaseLayer). */
getLayers(filter?: (layer: Layer) => Layer[]): Layer[];
/** Get the layer with the given id. */
getLayer(id: string): Layer;
/** Add a new layer on the top of the map. */
addLayer(layer: Layer | Layer[]): this;
/** Remove a layer from the map */
removeLayer(layer: string | string[] | Layer | Layer[]): this;
/** Sort layers according to the order provided, the last will be on the top. */
sortLayers(layers: string[] | Layer[]): this;
/** Exports image from the map's canvas. */
toDataURL(options?: object): string;
/** shorter alias for coordinateToPoint */
coordToPoint(coordinate: Coordinate, zoom?: number, out?: Point): Point;
/** shorter alias for pointToCoordinate */
pointToCoord(point: Point, zoom: number, out?: Coordinate): Coordinate;
/** shorter alias for coordinateToViewPoint */
coordToViewPoint(coordinate: Coordinate, out?: Point): Point;
/** shorter alias for viewPointToCoordinate */
viewPointToCoord(viewPoint: Point, out?: Coordinate): Coordinate;
/** shorter alias for coordinateToContainerPoint */
coordToContainerPoint(zoom?: number, out?: Point): Point;
/** shorter alias for containerPointToCoordinate */
containerPointToCoord(out?: Coordinate): Coordinate;
/** Converts a container point to the view point. Usually used in plugin development. */
containerPointToViewPoint(containerPoint: Point, out?: Point): Point;
/** Converts a view point to the container point. Usually used in plugin development. */
viewPointToContainerPoint(viewPoint: Point, out?: Point): Point;
/** Checks if the map container size changed and updates the map if so. */
checkSize(): this;
/** Computes the coordinate from the given meter distance. */
locate(coordinate: Coordinate, dx: number, dy: number): Coordinate;
/** Return map's main panel */
getMainPanel(): HTMLElement;
/** Returns map panels. */
getPanels(): object;
/** Remove the map */
remove(): this;
/** whether the map is removed */
isRemoved(): this;
/** Whether the map is moving */
isMoving(): this;
/** Get device's devicePixelRatio, you can override it by setting devicePixelRatio in options. */
getDevicePixelRatio(): number;
/** Gets map panel's current view point. */
offsetPlatform(): Point;
/** Get map's view point, adding in frame offset */
getViewPoint(): Point;
/** Converts a coordinate to the 2D point in current zoom or in the specific zoom. */
coordinateToPoint(coordinate: Coordinate, zoom?: number, out?: Point): Point;
/** Converts a 2D point in current zoom or a specific zoom to a coordinate. Usually used in plugin development. */
pointToCoordinate(point: Point, zoom: number, out?: Coordinate): Coordinate;
/** Converts a geographical coordinate to view point. */
coordinateToViewPoint(coordinate: Coordinate, out?: Point): Point;
/** Converts a view point to the geographical coordinate. Usually used in plugin development. */
viewPointToCoordinate(viewPoint: Point, out?: Coordinate): Coordinate;
/** Convert a geographical coordinate to the container point. */
coordinateToContainerPoint(coordinate: Coordinate, zoom?: number, out?: Point): Point;
/** Converts a container point to geographical coordinate. */
containerPointToCoordinate(point: Point, out?: Coordinate): Coordinate;
/** Converts a container point extent to the geographic extent. */
containerToExtent(containerExtent: PointExtent): Extent;
/** Converts geographical distances to the pixel length. */
distanceToPixel(xDist: number, yDist: number): Size;
/** Converts geographical distances to the 2d point length. */
distanceToPoint(xDist: number, yDist: number, zoom: number): Point;
/** Converts pixel size to geographical distance. */
pixelToDistance(width: number, height: number): number;
/** Converts 2d point distances to geographic length. */
pointToDistance(dx: number, dy: number, zoom: number): number;
/** Computes the coordinate from the given pixel distance. */
locateByPoint(coordinate: Coordinate, px: number, py: number): Coordinate;
/** Update map's view with animation. */
animateTo(view: object, options?: object, step?: animation.FrameStepFun): this;
/** Whether the map is animating with .animateTo */
isAnimating(): boolean;
/** Get map's fov (field of view); */
getFov(): number;
/** Set a new fov to map */
setFov(fov: number): this;
/** Get map's bearing */
getBearing(): number;
/** Set a new bearing to map */
setBearing(bearing: number): this;
/** Get map's pitch */
getPitch(): number;
/** Set a new pitch to map */
setPitch(pitch: number): this;
/** Element is currently in fullscreen. */
isFullScreen(): boolean;
/** Request for the full screen */
requestFullScreen(): this;
/** Cancel full screen */
cancelFullScreen(): this;
/** Pan to the given coordinate */
panTo(coordinate: Coordinate, options?: object): this;
/** Pan the map by the give point */
panBy(point: Point | number[], options?: object): this;
/** Export the map's json, a snapshot of the map in JSON format. */
toJSON(options?: object): object;
/** Caculate distance of two coordinates. */
computeLength(coord1: number[] | Coordinate, coord2: number[] | Coordinate): number;
/** Caculate a geometry's length. */
computeGeometryLength(geometry: Geometry): number;
/** Caculate a geometry's area. */
computeGeometryArea(geometry: Geometry): number;
/** Identify the geometries on the given coordinate. */
identify(opts: object, callback: (his: any[]) => void): this;
/** Zoom to the previous map view in view history */
zoomToPreviousView(): object;
/** Whether has more previous view */
hasPreviousView(): boolean;
/** Zoom to the next view in view history */
zoomToNextView(): object;
/** Whether has more next view */
hasNextView(): boolean;
/** Get map view history */
getViewHistory(): object[];
/** Add a control on the map. */
addControl(control: control.Control): this;
/** Remove a control from the map. */
removeControl(control: control.Control): this;
getRenderer(): any;
}
export interface MapStatic {
new (container: string | HTMLElement, opts?: MapOptions): Map;
}
export const Map: MapStatic;
export abstract class Layer extends Eventable implements JSONAble {
// new(id: string | number, options: LayerOptions): Layer
// new(options?: any): Layer
/** Reproduce a Layer from layer's JSON. */
fromJSON(layerJSON: object): Layer;
/**
* load the tile layer, can't be overrided by sub-classes
*/
load(): this;
/**
* Get the layer id
* @returns id
*/
getId(): string;
/**
* Set a new id to the layer
* @param id - new layer id
* @return this
* @fires Layer#idchange
*/
setId(id: string): this;
/**
* Adds itself to a map.
* @param map - map added to
* @return this
*/
addTo(map: Map): this;
/**
* Set a z-index to the layer
* @param zIndex - layer's z-index
* @return this
*/
setZIndex(zIndex: number): this;
/**
* Get the layer's z-index
* @return
*/
getZIndex(): number;
/**
* Get Layer's minZoom to display
* @return
*/
getMinZoom(): number;
/**
* Get Layer's maxZoom to display
* @return
*/
getMaxZoom(): number;
/**
* Get layer's opacity
* @returns
*/
getOpacity(): number;
/**
* Set opacity to the layer
* @param opacity - layer's opacity
* @return this
*/
setOpacity(op: number): this;
/**
* If the layer is rendered by HTML5 Canvas.
* @return
*
*/
isCanvasRender(): boolean;
/**
* Get the map that the layer added to
* @returns
*/
getMap(): Map;
/**
* Get projection of layer's map
* @returns
*/
getProjection(): object;
/**
* Brings the layer to the top of all the layers
* @returns this
*/
bringToFront(): Layer;
/**
* Brings the layer under the bottom of all the layers
* @returns this
*/
bringToBack(): Layer;
/**
* Show the layer
* @returns this
*/
show(): Layer;
/**
* Hide the layer
* @returns this
*/
hide(): Layer;
/**
* Whether the layer is visible now.
* @return
*/
isVisible(): boolean;
/**
* Remove itself from the map added to.
* @returns this
*/
remove(): Layer;
/**
* Get the mask geometry of the layer
* @return
*/
getMask(): Geometry;
/**
* Set a mask geometry on the layer, only the area in the mask will be displayed.
* @param mask - mask geometry, can only be a Marker with vector symbol, a Polygon or a MultiPolygon
* @returns this
*/
setMask(mask: Geometry): Layer;
/**
* Remove the mask
* @returns this
*/
removeMask(): Layer;
/**
* Prepare Layer's loading, this is a method intended to be overrided by subclasses.
* @return true to continue loading, false to cease.
*/
onLoad(): boolean;
/**
* Whether the layer is loaded
* @return
*/
isLoaded(): boolean;
getRenderer(): any;
/**
* It is a static method. <br>
* Register layer for JSON serialization and assign a JSON type.
* @param type - JSON type
* JSONAble.registerJSONType
*/
registerJSONType(type: string): void;
/**
* It is a static method. <br>
* Get class of input JSON type
* @param type - JSON type
* @return Class
* JSONAble.getJSONClass
*/
getJSONClass(type: string): Class;
/**
* Get object's JSON Type
* @return
* JSONAble.getJSONType
*/
getJSONType(): string;
}
// export const Layer:Layer
export interface TileSystem {
"web-mercator": TileSystem;
"tms-global-mercator": TileSystem;
"tms-global-geodetic": TileSystem;
baidu: TileSystem;
/**
* Get the default tile system's code for the projection.
* @param projection - a projection object
* @return tile system code
*/
getDefault(projection: object): string;
}
export interface TileSystemStatic {
new (sx: number, sy: number, ox: number, oy: number): TileSystem;
new (sx: number[]): TileSystem;
}
export const TileSystem: TileSystemStatic;
export interface TileLayer extends Layer {
/**
* Reproduce a TileLayer from layer's profile JSON.
* @param layerJSON - layer's profile JSON
* @return
*
*
*
*/
fromJSON(layerJSON: object): TileLayer;
/**
* Get tile size of the tile layer
* @return
*/
getTileSize(): Size;
/**
* Get tiles at zoom z (or current zoom)
* @param z - zoom
* @return tile descriptors
*/
getTiles(z: number, parentLayer?: Layer): object[];
/**
* Get tile's url
* @param x
* @param y
* @param z
* @returns url
*/
getTileUrl(x: number, y: number, z: number): string;
/**
* Clear the layer
* @return this
*/
clear(): TileLayer;
/**
* Export the tile layer's profile json. <br>
* Layer's profile is a snapshot of the layer in JSON format. <br>
* It can be used to reproduce the instance by [fromJSON]{@link Layer#fromJSON} method
* @return layer's profile JSON
*/
toJSON(): object;
/**
* Get tilelayer's spatial reference.
* @returns spatial reference
*/
getSpatialReference(): SpatialReference;
}
export interface TileLayerInstanceStatic {
new (id: string | number, options?: TileLayerOptions): TileLayer;
}
export const TileLayer: TileLayerInstanceStatic;
export interface GroupTileLayer extends TileLayer {
/**
* Get children TileLayer
* @returns
*/
getLayers(): TileLayer[];
}
export interface GroupTileLayerStatic {
new (id: string | number, layers: TileLayer[], options?: TileLayerOptions): GroupTileLayer;
}
export const GroupTileLayer: GroupTileLayerStatic;
export interface WMSTileLayer extends TileLayer {
_placeholder: string;
}
export interface WMSTileLayerStatic {
new (id: string | number, options?: WMSTileLayerOptions): WMSTileLayer;
}
export const WMSTileLayer: WMSTileLayerStatic;
export interface CanvasTileLayer extends TileLayer {
/**
* The interface method to draw on canvsa tile
* @param canvas canvas to draw on
* @param options current options
* @param options current options
*/
drawTile(canvas: HTMLCanvasElement, ...options: any[] /*canvas, options*/): void;
}
export interface CanvasTileLayerStatic {
new (id: string | number, options?: TileLayerOptions): CanvasTileLayer;
}
export const CanvasTileLayer: CanvasTileLayerStatic;
export interface OverlayLayer extends Layer {
/**
* Get a geometry by its id
* @param id - id of the geometry
* @return
*/
getGeometryById(id: string | number): Geometry;
/**
* Get all the geometries or the ones filtered if a filter function is provided.
* @param [filter=undefined] - a function to filter the geometries
* @param [context=undefined] - context of the filter function, value to use as this when executing filter.
* @return
*/
getGeometries(filter?: (geometry: Geometry, context?: any) => boolean, context?: object): Geometry[];
/**
* Get the first geometry, the geometry at the bottom.
* @return first geometry
*/
getFirstGeometry(): Geometry;
/**
* Get the last geometry, the geometry on the top
* @return last geometry
*/
getLastGeometry(): Geometry;
/**
* Get count of the geometries
* @return count
*/
getCount(): number;
/**
* Get extent of all the geometries in the layer, return null if the layer is empty.
* @return - extent of the layer
*/
getExtent(): Extent;
/**
* Executes the provided callback once for each geometry present in the layer in order.
* @param fn - a callback function
* @param context - callback's context, value to use as this when executing callback.
* @return this
*/
forEach(fn: (geometry: Geometry, idx: number, context?: any) => void, context?: any): OverlayLayer;
/**
* Creates a GeometryCollection with all the geometries that pass the test implemented by the provided function.
* @param fn - Function to test each geometry
* @param context - Function's context, value to use as this when executing function.
* @return A GeometryCollection with all the geometries that pass the test
*/
filter(fn: (geometry: Geometry, context?: any) => boolean, context?: any): GeometryCollection;
/**
* Whether the layer is empty.
* @return
*/
isEmpty(): boolean;
/**
* Adds one or more geometries to the layer
* @param geometries - one or more geometries
* @param [fitView=false] - automatically set the map to a fit center and zoom for the geometries
* @param [fitView.easing=out] - default animation type
* @param [fitView.duration=map.options.zoomAnimationDuration] - default animation time
* @param [fitView.step=null] - step function during animation, animation frame as the parameter
* @return this
*/
addGeometry(geometries: Geometry | Geometry[], fitView?: boolean | object): OverlayLayer;
/**
* Get minimum zindex of geometries
*/
getGeoMinZIndex(): number;
/**
* Get maximum zindex of geometries
*/
getGeoMaxZIndex(): number;
/**
* Removes one or more geometries from the layer
* @param geometries - geometry ids or geometries to remove
* @returns this
*/
removeGeometry(geometries: string | string[] | Geometry | Geometry[]): OverlayLayer;
/**
* Clear all geometries in this layer
* @returns this
*/
clear(): OverlayLayer;
/**
* Called when geometry is being removed to clear the context concerned.
* @param geometry - the geometry instance to remove
*
*/
onRemoveGeometry(geometry: Geometry): Geometry;
/**
* Gets layer's style.
* @return layer's style
*/
getStyle(): object | object[];
/**
* Sets style to the layer, styling the geometries satisfying the condition with style's symbol. <br>
* Based on filter type in [mapbox-gl-js's style specification]{https:// www.mapbox.com/mapbox-gl-js/style-spec/#types-filter}.
* @param style - layer's style
* @returns this
* @fires VectorLayer#setstyle
* @example
*/
setStyle(style: any): this;
/**
* Removes layers' style
* @returns this
* @fires VectorLayer#removestyle
*/
removeStyle(): this;
}
export interface VectorLayer extends OverlayLayer {
/**
* Identify the geometries on the given coordinate
* @param coordinate - coordinate to identify
* @param [options=null] - options
* @param [options.tolerance=0] - identify tolerance in pixel
* @param [options.count=null] - result count
* @return geometries identified
*/
identify(coordinate: Coordinate, options?: object): Geometry[];
/**
* Export the VectorLayer's JSON. <br>
* @param [options=null] - export options
* @param [options.geometries=null] - If not null and the layer is a [OverlayerLayer]{@link OverlayLayer},
* the layer's geometries will be exported with the given "options.geometries" as a parameter of geometry's toJSON.
* @param [options.clipExtent=null] - if set, only the geometries intersectes with the extent will be exported.
* @return layer's JSON
*/
toJSON(options?: object): object;
}
export interface VectorLayerStatic {
new (id: string | number, geometries?: Geometry | Geometry[] | null, options?: VectorLayerOptions): VectorLayer;
}
export const VectorLayer: VectorLayerStatic;
export interface CanvasLayer extends Layer {
/**
* An optional interface function called only once before the first draw, useful for preparing your canvas operations.
* @param context - CanvasRenderingContext2D of the layer canvas.
* @return objects that will be passed to function draw(context, ..) as parameters.
*/
prepareToDraw(context?: CanvasRenderingContext2D): any[];
/**
* The required interface function to draw things on the layer canvas.
* @param context - CanvasRenderingContext2D of the layer canvas.
* @param params - parameters returned by function prepareToDraw(context).
*/
draw(context: CanvasRenderingContext2D, ...params: any[]): void;
/**
* An optional interface function to draw while map is interacting.
* By default, it will call draw method instead.
* You can override this method if you are clear with what to draw when interacting to improve performance.
* @param context - CanvasRenderingContext2D of the layer canvas.
* @param params - parameters returned by function prepareToDraw(context).
*/
drawOnInteracting(context: CanvasRenderingContext2D, ...params: any[]): void;
/**
* Redraw the layer
* @return this
*/
redraw(): this;
/**
* Start animation
* @return this
*/
play(): this;
/**
* Pause the animation
* @return this
*/
pause(): this;
/**
* If the animation is playing
* @return
*/
isPlaying(): boolean;
/**
* Clear layer's canvas
* @return this
*/
clearCanvas(): this;
/**
* Ask the map to redraw the layer canvas without firing any event.
* @return this
*/
requestMapToRender(): this;
/**
* Ask the map to redraw the layer canvas and fire layerload event
* @return this
*/
completeRender(): this;
/**
* Callback function when layer's canvas is created. <br>
* Override it to do anything needed.
*/
onCanvasCreate(): this;
/**
* The event callback for map's zoomstart event.
* @param param - event parameter
*/
onZoomStart(param?: object): void;
/**
* The event callback for map's zooming event.
* @param param - event parameter
*/
onZooming(param?: object): void;
/**
* The event callback for map's zoomend event.
* @param param - event parameter
*/
onZoomEnd(param?: object): void;
/**
* The event callback for map's movestart event.
* @param param - event parameter
*/
onMoveStart(param?: object): void;
/**
* The event callback for map's moving event.
* @param param - event parameter
*/
onMoving(param?: object): void;
/**
* The event callback for map's moveend event.
* @param param - event parameter
*/
onMoveEnd(param?: object): void;
/**
* The event callback for map's resize event.
* @param param - event parameter
*/
onResize(param?: object): void;
/**
* The callback function to double buffer. <br>
* In default, it just draws and return, and you can override it if you need to process the canvas image before drawn.
* @param bufferContext CanvasRenderingContext2D of double buffer of the layer canvas.
* @param context CanvasRenderingContext2D of the layer canvas.
*/
doubleBuffer(bufferContext: CanvasRenderingContext2D, context: CanvasRenderingContext2D /*, context*/): this;
}
export interface CanvasLayerStatic {
new (id: string | number, options: CanvasLayerOptions): CanvasLayer;
}
export const CanvasLayer: CanvasLayerStatic;
export interface ParticleLayer extends CanvasLayer {
/**
* Interface method to get particles's position at time t.
* @param t - current time in milliseconds
*/
getParticles(t?: number): void;
}
export interface ParticleLayerStatic {
new (id: string, options?: CanvasLayerOptions): ParticleLayer;
}
export const ParticleLayer: ParticleLayerStatic;
export interface ImageLayer extends Layer {
/**
* Set images and redraw
* @param images - new images
* @return this
*/
setImages(images: object[]): this;
/**
* Get images
* @return
*/
getImages(): object[];
}
export interface ImageLayerStatic {
new (id: string | number, images?: object[], options?: ImageLayerOptions): ImageLayer;
}
export const ImageLayer: ImageLayerStatic;
export interface SpatialReference {
_placeholder: string;
}
export class Extent {
xmin: number;
xmax: number;
ymin: number;
ymax: number;
constructor(p1: number, p2: number, p3: number, p4: number);
constructor(x: Coordinate | Point, y: Coordinate | Point);
constructor(json: object | Extent);
/**
* Add the extent with a coordinate or a point.
* @param p - point or coordinate to add
* @returns a new extent
*/
add(p: Coordinate | Point): Extent;
/**
* Substract the extent with a coordinate or a point.
* @param p - point or coordinate to substract
* @returns a new extent
*/
sub(p: Coordinate | Point): Extent;
/**
* Round the extent
* @return rounded extent
*/
round(): Extent;
/**
* Alias for sub
* @param p - point or coordinate to substract
* @returns a new extent
*/
substract(p: Coordinate | Point): Extent;
/**
* Get the minimum point
* @params {Coorindate} [out=undefined] - optional point to receive result
* @return
*/
getMin(out?: Coordinate): Coordinate;
/**
* Get the maximum point
* @params {Coorindate} [out=undefined] - optional point to receive result
* @return
*/
getMax(out?: Coordinate): Coordinate;
/**
* Get center of the extent.
* @params {Coorindate} [out=undefined] - optional point to receive result
* @return
*/
getCenter(out?: Coordinate): Coordinate;
/**
* Whether the extent is valid
*
* @return
*/
isValid(): boolean;
/**
* Compare with another extent to see whether they are equal.
* @param ext2 - extent to compare
* @return
*/
equals(ext2: Extent): boolean;
/**
* Whether it intersects with another extent
* @param ext2 - another extent
* @return
*/
intersects(ext2: Extent): boolean;
/**
* Whether the extent is within another extent
* @param ext2 - another extent
* @returns
*/
within(extent: Extent): boolean;
/**
* Whether the extent contains the input point.
* @param coordinate - input point
* @returns
*/
contains(c: Coordinate | number[]): boolean;
/**
* Get the width of the Extent
* @return
*/
getWidth(): number;
/**
* Get the height of the Extent
* @return
*/
getHeight(): number;
/**
* Get size of the Extent
* @return
*/
getSize(): Size;
/**
* Combine it with another extent to a larger extent.
* @param extent - extent/coordinate/point to combine into
* @returns extent combined
*/
combine(extent: Extent | Coordinate | Point): Extent;
/**
* Gets the intersection extent of this and another extent.
* @param extent - another extent
* @return intersection extent
*/
intersection(extent: Extent): Extent;
/**
* Expand the extent by distance
* @param distance - distance to expand
* @returns a new extent expanded from
*/
expand(distance: Size | number): Extent;
/**
* Get extent's JSON object.
* @return jsonObject
* @example
* // {xmin : 100, ymin: 10, xmax: 120, ymax:20}
* var json = extent.toJSON();
*/
toJSON(): object;
/**
* Get a coordinate array of extent's rectangle area, containing 5 coordinates in which the first equals with the last.
* @return coordinates array
*/
toArray(): Coordinate[];
/**
* Get a copy of the extent.
* @return copy
*/
copy(): Extent;
/**
* Convert to a new extent
* @param fn convert function on each point
* @return
*/
convertTo(fn: (coord: Coordinate | Point) => Extent): Extent;
}
export class PointExtent extends Extent {}
export class Size {
width: number;
height: number;
constructor(width: number, height: number);
/**
* Returns a copy of the size
* @return copy
*/
copy(): Size;
/**
* Returns the result of addition of another size.
* @param size - size to add
* @return result
*/
add(size: Size): Size;
/**
* Returns the result of addition of another size.
* @param x - size to add
* @param y - size to add
* @return result
*/
add(x: number, y: number): Size;
/**
* Compare with another size to see whether they are equal.
* @param size - size to compare
* @return
*/
equals(size: Size): boolean;
/**
* Returns the result of multiplication of the current size by the given number.
* @param ratio - ratio to multi
* @return result
*/
multi(ratio: number): Size;
/**
* Converts the size object to a [Point]
* @return point
*/
toPoint(): Point;
/**
* Converts the size object to an array [width, height]
* @return
*/
toArray(): number[];
/**
* Convert the size object to a json object {width : .., height : ..}
* @return json
*/
toJSON(): object;
}
export abstract class Position {
x: number;
y: number;
constructor(x: number, y: number);
constructor(points: number[] | object);
/**
* Set point or coordinate's x, y value
* @params x - x value
* @params y - y value
* @return this
*/
set(x: number, y: number): Coordinate | Point;
/**
* Return abs value of the point
* @return abs point
*/
abs(): Coordinate | Point;
/**
* Like math.round, rounding the point's xy.
* @return rounded point
*/
round(): Coordinate | Point;
/**
* Returns the distance between the current and the given point.
* @param point - another point
* @return distance
*/
distanceTo(point: Coordinate | Point): number;
/**
* Returns a copy of the coordinate
* @return copy
*/
copy(): Coordinate | Point;
/**
* Returns the result of addition of another coordinate.
* @param x - coordinate to add
* @param [y=undefined] - optional, coordinate to add
* @return result
*/
add(x: Coordinate | Point | any[] | number, y?: number): Coordinate | Point;
/**
* Returns the result of subtraction of another coordinate.
* @param x - coordinate to add
* @param [y=undefined] - optional, coordinate to add
* @return result
*/
sub(x: Coordinate | Point | any[] | number, y?: number): Coordinate | Point;
/**
* Alias for sub
* @param x - coordinate to add
* @param [y=undefined] - optional, coordinate to add
* @return result
*/
substract(x: Coordinate | Point | any[] | number, y?: number): Coordinate | Point;
/**
* Returns the result of multiplication of the current coordinate by the given number.
* @param ratio - ratio to multi
* @return result
*/
multi(ratio: number): Coordinate | Point;
/**
* Returns the result of division of the current point by the given number.
* @param n - number to div
* @return result
*/
div(n: number): Coordinate | Point;
/**
* Compare with another coordinate to see whether they are equal.
* @param c - coordinate to compare
* @return
*/
equals(c: Coordinate | Point): boolean;
/**
* Whether the coordinate/point is zero
*/
isZero(): boolean;
/**
* Convert to a number array [x, y]
* @return number array
*/
toArray(): number[];
/**
* Formats coordinate number using fixed-point notation.
* @param n The number of digits to appear after the decimal point
* @return fixed coordinate
*/
toFixed(n: number): Coordinate;
/**
* Convert to a json object {x : .., y : ..}
* @return json
*/
toJSON(): object;
}
export class Coordinate extends Position {
/**
* Convert one or more Coordinate objects to GeoJSON style coordinates
* @param coordinates - coordinates to convert
* @return
* @example
* // result is [[100,0], [101,1]]
* var numCoords = Coordinate.toNumberArrays([new Coordinate(100,0), new Coordinate(101,1)]);
*/
static toNumberArrays(coordinates: Coordinate | Coordinate[]): number[] | number[][];
/**
* Convert one or more GeoJSON style coordiantes to Coordinate objects
* @param coordinates - coordinates to convert
* @return
* @example
* var coordinates = Coordinate.toCoordinates([[100,0], [101,1]]);
*/
static toCoordinates(coordinates: number[] | number[][]): Coordinate | Coordinate[];
}
export class Point extends Position {
constructor(x: number, y: number);
constructor(points: number[] | object);
/**
* Compare with another point with a delta
* @param p
* @param delta
* @return
*/
closeTo(p: Point, delta: number): boolean;
/**
* Return the magitude of this point: this is the Euclidean
* distance from the 0, 0 coordinate to this point's x and y
* coordinates.
* @return magnitude
*/
mag(): number;
/**
* Calculate this point but as a unit vector from 0, 0, meaning
* that the distance from the resulting point to the 0, 0
* coordinate will be equal to 1 and the angle from the resulting
* point to the 0, 0 coordinate will be the same as before.
* @return unit vector point
*/
unit(): Point;
/**
* Compute a perpendicular point, where the new y coordinate
* is the old x coordinate and the new x coordinate is the old y
* coordinate multiplied by -1
* @return perpendicular point
*/
perp(): Point;
/**
* Get the angle between this point and another point, in radians
* from mapbox/point-geometry
* @param b the other point
* @return angle
*/
angleWith(b: Point): number;
/**
* Find the angle of the two vectors, solving the formula for
* the cross product a x b = |a||b|sin(θ) for θ.
* from mapbox/point-geometry
*
* @param x the x-coordinate
* @param y the y-coordinate
* @return the angle in radians
*/
angleWithSep(x: number, y: number): number;
/**
* Rotate this point around the 0, 0 origin by an angle a,
* given in radians
* from mapbox/point-geometry
*
* @param a angle to rotate around, in radians
* @return output point
*/
rotate(a: number): Point;
}
export interface Geometry extends Handlerable, JSONAble, ui.Menuable {
/**
* Returns the first coordinate of the geometry.
*
* @return First Coordinate
*/
getFirstCoordinate(): Coordinate;
/**
* Returns the last coordinate of the geometry.
*
* @return Last Coordinate
*/
getLastCoordinate(): Coordinate;
/**
* Adds the geometry to a layer
* @param layer - layer add to
* @param [fitview=false] - automatically set the map to a fit center and zoom for the geometry
* @return this
* @fires Geometry#add
*/
addTo(layer: Layer | Map, fitview?: boolean): this;
/**
* Get the layer which this geometry added to.
* @returns - layer added to
*/
getLayer(): Layer;
/**
* Get the map which this geometry added to
* @returns - map added to
*/
getMap(): Map;
/**
* Gets geometry's id. Id is set by setId or constructor options.
* @returns geometry的id
*/
getId(): string | number;
/**
* Set geometry's id.
* @param id - new id
* @returns this
* @fires Geometry#idchange
*/
setId(id: string): this;
/**
* Get geometry's properties. Defined by GeoJSON as [feature's properties]{@link http:// geojson.org/geojson-spec.html#feature-objects}.
*
* @returns properties
*/
getProperties(): object;
/**
* Set a new properties to geometry.
* @param properties - new properties
* @returns this
* @fires Geometry#propertieschange
*/
setProperties(properties: object): this;
/**
* Get type of the geometry, e.g. "Point", "LineString"
* @returns type of the geometry
*/
getType(): string;
/**
* Get symbol of the geometry
* @returns geometry's symbol
*/
getSymbol(): object;
/**
* Set a new symbol to style the geometry.
* @param symbol - new symbol
* @see {@tutorial symbol Style a geometry with symbols}
* @return this
* @fires Geometry#symbolchange
*/
setSymbol(symbol: object): this;
/**
* Get symbol's hash code
* @return
*/
getSymbolHash(): string;
/**
* Update geometry's current symbol.
*
* @param props - symbol properties to update
* @return this
* @fires Geometry#symbolchange
* @example
* var marker = new Marker([0, 0], {
* symbol : {
* markerType : 'ellipse',
* markerWidth : 20,
* markerHeight : 30
* }
* });
* // update symbol's markerWidth to 40
* marker.updateSymbol({
* markerWidth : 40
* });
*/
updateSymbol(props: object | any[]): this;
/**
* Get the geographical center of the geometry.
*
* @returns
*/
getCenter(): Coordinate;
/**
* Get the geometry's geographical extent
*
* @returns geometry's extent
*/
getExtent(): Extent;
/**
* Get geometry's screen extent in pixel
* @returns
*/
getContainerExtent(out?: PointExtent): PointExtent;
/**
* Get pixel size of the geometry, which may vary in different zoom levels.
*
* @returns
*/
getSize(): Size;
/**
* Whehter the geometry contains the input container point.
*
* @param point - input container point or coordinate
* @param [t=undefined] - tolerance in pixel
* @return
* @example
* var circle = new Circle([0, 0], 1000)
* .addTo(layer);
* var contains = circle.containsPoint(new maptalks.Point(400, 300));
*/
containsPoint(containerPoint: Point | Coordinate, t?: number): boolean;
/**
* Show the geometry.
*
* @return this
* @fires Geometry#show
*/
show(): this;
/**
* Hide the geometry
*
* @return this
* @fires Geometry#hide
*/
hide(): this;
/**
* Whether the geometry is visible
*
* @returns
*/
isVisible(): boolean;
/**
* Get zIndex of the geometry, default is 0
* @return zIndex
*/
getZIndex(): number;
/**
* Set a new zIndex to Geometry and fire zindexchange event (will cause layer to sort geometries and render)
* @param zIndex - new zIndex
* @return this
* @fires Geometry#zindexchange
*/
setZIndex(zIndex: number): this;
/**
* Only set a new zIndex to Geometry without firing zindexchange event. <br>
* Can be useful to improve perf when a lot of geometries' zIndex need to be updated. <br>
* When updated N geometries, You can use setZIndexSilently with (N-1) geometries and use setZIndex with the last geometry for layer to sort and render.
* @param zIndex - new zIndex
* @return this
*/
setZIndexSilently(zIndex: number): this;
/**
* Bring the geometry on the top
* @return this
* @fires Geometry#zindexchange
*/
bringToFront(): this;
/**
* Bring the geometry to the back
* @return this
* @fires Geometry#zindexchange
*/
bringToBack(): this;
/**
* Translate or move the geometry by the given offset.
*
* @param x - x offset
* @param y - y offset
* @return this
* @fires Geometry#positionchange
* @fires Geometry#shapechange
*/
translate(x: number, y: number): this;
/**
* Translate or move the geometry by the given offset.
*
* @param x - x offset
* @return this
* @fires Geometry#positionchange
* @fires Geometry#shapechange
*/
translate(x: number[]): this;
/**
* Flash the geometry, show and hide by certain internal for times of count.
*
* @param [interval=100] - interval of flash, in millisecond (ms)
* @param [count=4] - flash times
* @param [cb=null] - callback function when flash ended
* @param context - callback context
* @return this
*/
flash(interval?: number, count?: number, cb?: (context?: any) => void, context?: any): this;
/**
* Returns a copy of the geometry without the event listeners.
* @returns copy
*/
copy(): this;
/**
* remove itself from the layer if any.
* @returns this
* @fires Geometry#removestart
* @fires Geometry#remove
*/
remove(): this;
/**
* Exports [geometry]{@link http:// geojson.org/geojson-spec.html#feature-objects} out of a GeoJSON feature.
* @return GeoJSON Geometry
*/
toGeoJSONGeometry(): object;
/**
* Exports a GeoJSON feature.
* @param [opts=null] - export options
* @param [opts.geometry=true] - whether export geometry
* @param [opts.properties=true] - whether export properties
* @returns GeoJSON Feature
*/
toGeoJSON(opts?: object): object;
/**
* Get the geographic length of the geometry.
* @returns geographic length, unit is meter
*/
getLength(): number;
/**
* Get the geographic area of the geometry.
* @returns geographic area, unit is sq.meter
*/
getArea(): number;
/**
* Rotate the geometry of given angle around a pivot point
* @param angle - angle to rotate in degree
* @param [pivot=null] - optional, will be the geometry's center by default
* @returns this
*/
rotate(angle: number, pivot?: Coordinate): this;
/**
* Start to edit
* @param [options=null] - edit options
* @param [options.symbol=null] - symbol for the geometry during editing
* @param [options.fixAspectRatio=false] - fix outline's aspect ratio when resizing
* @param [options.centerHandleSymbol=null] - symbol of center handle
* @param [options.vertexHandleSymbol=null] - symbol of vertex handle
* @param [options.newVertexHandleSymbol=null] - symbol of new vertex handle
* @param [options.removeVertexOn=contextmenu] - event to remove a vertex from line or polygon, contextmenu by default
* @return this
*/
startEdit(opts?: object): this;
/**
* End editing.
* @return this
*/
endEdit(): this;
/**
* Redo the edit
* @return this
*/
redoEdit(): this;
/**
* Undo the edit
* @return this
*/
undoEdit(): this;
/**
* cancel the edit
* @return this
*/
cancelEdit(): this;
/**
* Whether the geometry is being edited.
* @return
*/
isEditing(): boolean;
/**
* Whether the geometry is being dragged.
* @reutrn
*/
isDragging(): boolean;
/**
* Animate the geometry
*
* @param styles - styles to animate
* @param [options=null] - animation options
* @param [options.duration=1000] - duration
* @param [options.startTime=null] - time to start animation in ms
* @param [options.easing=linear] - animation easing: in, out, inAndOut, linear, upAndDown
* @param [options.repeat=false] - repeat animation
* @param [step=null] - step function during animation, animation frame as the parameter
* @return animation player
* @example
* var player = marker.animate({
* 'symbol': {
* 'markerHeight': 82
* }
* }, {
* 'duration': 2000
* }, function (frame) {
* if (frame.state.playState === 'finished') {
* console.log('animation finished');
* }
* });
* player.pause();
*/
animate(styles: object, options?: object, step?: animation.FrameStepFun): animation.Player;
/**
* Set an InfoWindow to the geometry
* @param options - construct [options]{@link ui.InfoWindow#options} for the InfoWindow
* @return this
* @example
* geometry.setInfoWindow({
* title : 'This is a title',
* content : '<div style="color:#f00">This is content of the InfoWindow</div>'
* });
*/
setInfoWindow(options: object): this;
/**
* Get the InfoWindow instance.
* @return
*/
getInfoWindow(): ui.InfoWindow;
/**
* Open the InfoWindow, default on the center of the geometry.
* @param [coordinate=null] - coordinate to open the InfoWindow
* @return this
*/
openInfoWindow(coordinate?: Coordinate): this;
/**
* Close the InfoWindow
* @return this
*/
closeInfoWindow(): this;
/**
* Remove the InfoWindow
* @return this
*/
removeInfoWindow(): this;
/**
* Produce a geometry from one or more [JSON]{@link Geometry#toJSON} or GeoJSON.
* @param json - a geometry's JSON or a geojson
* @return geometry
*/
fromJSON(json: any): Geometry;
/**
* Export a profile json out of the geometry. <br>
* Besides exporting the feature object, a profile json also contains symbol, construct options and infowindow info.<br>
* The profile json can be stored somewhere else and be used to reproduce the geometry later.<br>
* Due to the problem of serialization for functions, event listeners and contextmenu are not included in profile json.
* @param [options=null] - export options
* @param [opts.geometry=true] - whether export feature's geometry
* @param [opts.properties=true] - whether export feature's properties
* @param [opts.options=true] - whether export construct options
* @param [opts.symbol=true] - whether export symbol
* @param [opts.infoWindow=true] - whether export infowindow
* @return profile json object
*/
toJSON(options?: object): any;
}
export const Geometry: Geometry;
export interface Path extends Geometry {
/**
* Show the linestring with animation
* @param [options=null] animation options
* @param [options.duration=1000] duration
* @param [options.easing=out] animation easing
* @param [cb=null] callback function in animation, function parameters: frame, currentCoord
* @example
* line.animateShow({
* duration : 2000,
* easing : 'linear'
* }, function (frame, currentCoord) {
* // frame is the animation frame
* // currentCoord is current coordinate of animation
* });
* @return this
*/
animateShow(options?: object, cb?: animation.FrameStepFun): this;
}
export interface Marker extends Geometry, CenterAble {}
export interface MarkerStatic {
new (coordinates: Coordinate | number[], options?: MarkerOptions): Marker;
}
export const Marker: MarkerStatic;
export interface TextMarker extends Marker {
/**
* Get text content of the label
* @returns
*/
getContent(): string;
/**
* Set a new text content to the label
* @return const this
* @fires Label#contentchange
*/
setContent(): this;
}
export interface Label extends TextMarker, TextEditable {
/**
* Get label's box style
* @return
*/
getBoxStyle(): object;
/**
* Set a new box style to the label
* @param
* @returns const this
*/
setBoxStyle(style: object): this;
/**
* Get label's text symbol
* @return
*/
getTextSymbol(): object;
/**
* Set a new text symbol to the label
* @param symbol
* @returns const this
*/
setTextSymbol(symbol: object): this;
}
export interface LabelStatic {
new (contetn: string, coordinates: Coordinate | number[], options?: LabelOptions): Label;
}
export const Label: LabelStatic;
export interface TextBox extends TextMarker, TextEditable {
/**
* Get textbox's width
* @return
*/
getWidth(): number;
/**
* Set new width to textbox
* @param width
* returns {TextBox} this
*/
setWidth(width: number): this;
/**
* Get textbox's height
* @return
*/
getHeight(): number;
/**
* Set new height to textbox
* @param height
* returns {TextBox} this
*/
setHeight(height: number): this;
/**
* Get textbox's boxSymbol
* @return boxsymbol
*/
getBoxSymbol(): object;
/**
* Set a new box symbol to textbox
* @param symbol
* returns {TextBox} this
*/
setBoxSymbol(symbol: object): this;
/**
* Get textbox's text style
* @return
*/
getTextStyle(): object;
/**
* Set a new text style to the textbox
* @param style new text style
* returns {TextBox} this
*/
setTextStyle(style: object): this;
}
export interface TextBoxStatic {
new (
content: string,
coordinates: Coordinate | number[],
width: number,
height: number,
options?: TextBoxOptions,
): TextBox;
}
export const TextBox: TextBoxStatic;
export interface Polygon extends Path {
/**
* Set coordinates to the polygon
*
* @param coordinates - new coordinates
* @return this
* @fires Polygon#shapechange
*/
setCoordinates(coordinates: any): this;
/**
* Gets polygons's coordinates
*
* @returns
*/
getCoordinates(): Coordinate[][];
/**
* Get center of linestring's intersection with give extent
* @example
* const extent = map.getExtent();
* const center = line.getCenterInExtent(extent);
* @param extent
* @return center, null if line doesn't intersect with extent
*/
getCenterInExtent(extent: Extent): Coordinate;
/**
* Gets shell's coordinates of the polygon
*
* @returns
*/
getShell(): Coordinate[];
/**
* Gets holes' coordinates of the polygon if it has.
* @returns
*/
getHoles(): Coordinate[][];
/**
* Whether the polygon has any holes inside.
*
* @returns
*/
hasHoles(): boolean;
}
export interface PolygonStatic {
new (coordinates: number[][] | number[][][] | Coordinate[] | Coordinate[][], options?: PathOptions): Polygon;
}
export const Polygon: PolygonStatic;
export interface LineString extends Path {
/**
* Set new coordinates to the line string
* @param coordinates - new coordinates
* @fires LineString#shapechange
* @return this
*/
setCoordinates(coordinates: Coordinate[] | number[][]): this;
/**
* Get coordinates of the line string
* @return coordinates
*/
getCoordinates(): Coordinate[] | number[][];
/**
* Get center of linestring's intersection with give extent
* @example
* const extent = map.getExtent();
* const center = line.getCenterInExtent(extent);
* @param extent
* @return center, null if line doesn't intersect with extent
*/
getCenterInExtent(extent: Extent): Coordinate;
}
export interface LineStringStatic {
new (coordinates: Coordinate[] | number[][] | any[], options?: LineStringOptions): LineString;
}
export const LineString: LineStringStatic;
export interface Curve extends LineString {
_curve: string;
}
export interface ArcCurve extends Curve {
_arcCurve: string;
}
export interface ArcCurveStatic {
new (coordinates: Coordinate[] | number[][], options?: ArcCurveOptions): ArcCurve;
}
export const ArcCurve: ArcCurveStatic;
export interface QuadBezierCurve extends Curve {
_quadBezierCurve: string;
}
export interface QuadBezierCurveStatic {
new (coordinates: Coordinate[] | number[][], options?: LineStringOptions): QuadBezierCurve;
}
export const QuadBezierCurve: QuadBezierCurveStatic;
export interface CubicBezierCurve extends Curve {
_cubicBezierCurve: string;
}
export interface CubicBezierCurveStatic {
new (coordinates: Coordinate[] | number[][], options?: LineStringOptions): CubicBezierCurve;
}
export const CubicBezierCurve: CubicBezierCurveStatic;
export interface Connectable {
/**
* Gets the source of the connector line.
* @return
* Connectable.getConnectSource
*/
getConnectSource(): Geometry | control.Control | ui.UIComponent;
/**
* Sets the source to the connector line.
* @param src
* @return this
* Connectable.setConnectSource
*/
setConnectSource(src: Geometry | control.Control | ui.UIComponent): this;
/**
* Gets the target of the connector line.
* @return
* Connectable.getConnectTarget
*/
getConnectTarget(): Geometry | control.Control | ui.UIComponent;
/**
* Sets the target to the connector line.
* @param target
* @return this
* Connectable.setConnectTarget
*/
setConnectTarget(target: Geometry | control.Control | ui.UIComponent): this;
}
export interface ConnectorLine extends Connectable, LineString {}
export interface ConnectorLineStatic {
new (
src: Geometry | control.Control | ui.UIComponent,
target: Geometry | control.Control | ui.UIComponent,
options?: ConnectorLineOptions,
): ConnectorLine;
}
export const ConnectorLine: ConnectorLineStatic;
export interface ArcConnectorLine extends Connectable, LineString {}
export interface ArcConnectorLineStatic {
new (
src: Geometry | control.Control | ui.UIComponent,
target: Geometry | control.Control | ui.UIComponent,
options?: ArcConnectorLineOptions,
): ArcConnectorLine;
}
export const ArcConnectorLine: ArcConnectorLineStatic;
export interface Ellipse extends Polygon, CenterAble {
/**
* Set a new center to the geometry
* @param coordinates - new center
* @return this
* @fires Geometry#positionchange
* CenterAble.setCoordinates
*/
setCoordinates(coordinates: Coordinate | number[]): this;
/**
* Get geometry's center
* @return - center of the geometry
*
*/
getCoordinates(): Coordinate;
/**
* Gets polygons's coordinates
*
* @returns
*/
getCoordinates(): Coordinate[][];
/**
* Get ellipse's width
* @return
*/
getWidth(): number;
/**
* Set new width to ellipse
* @param width - new width
* @fires Ellipse#shapechange
* @return this
*/
setWidth(width: number): this;
/**
* Get ellipse's height
* @return
*/
getHeight(): number;
/**
* Set new height to ellipse
* @param height - new height
* @fires Ellipse#shapechange
* @return this
*/
setHeight(height: number): number;
/**
* Gets the shell of the ellipse as a polygon, number of the shell points is decided by [options.numberOfShellPoints]{@link Circle#options}
* @return - shell coordinates
*/
getShell(): Coordinate[];
/**
* Ellipse won't have any holes, always returns null
* @return an empty array
*/
getHoles(): object[];
/**
* Gets holes' coordinates of the polygon if it has.
* @returns
*/
getHoles(): Coordinate[][];
}
export interface EllipseStatic {
new (center: Coordinate | number[], width: number, height: number, options?: EllipseOptions): Ellipse;
}
export const Ellipse: EllipseStatic;
export interface Circle extends Polygon, CenterAble {
/**
* Set a new center to the geometry
* @param coordinates - new center
* @return this
* @fires Geometry#positionchange
* CenterAble.setCoordinates
*/
setCoordinates(coordinates: Coordinate | number[]): this;
/**
* Get geometry's center
* @return - center of the geometry
*
*/
getCoordinates(): Coordinate;
/**
* Gets polygons's coordinates
*
* @returns
*/
getCoordinates(): Coordinate[][];
/**
* Gets the shell of the ellipse as a polygon, number of the shell points is decided by [options.numberOfShellPoints]{@link Circle#options}
* @return - shell coordinates
*/
getShell(): Coordinate[];
/**
* Ellipse won't have any holes, always returns null
* @return an empty array
*/
getHoles(): object[];
/**
* Gets holes' coordinates of the polygon if it has.
* @returns
*/
getHoles(): Coordinate[][];
/**
* Get radius of the circle
* @return
*/
getRadius(): number;
/**
* Set a new radius to the circle
* @param radius - new radius
* @return this
* @fires Circle#shapechange
*/
setRadius(radius: number): this;
}
export interface CircleStatic {
new (center: Coordinate | number[], radius: number, options?: EllipseOptions): Circle;
}
export const Circle: CircleStatic;
export interface Sector extends Circle {
/**
* Get the sector's start angle
* @return
*/
getStartAngle(): number;
/**
* Set a new start angle to the sector
* @param startAngle
* @return this
* @fires Sector#shapechange
*/
setStartAngle(startAngle: number): this;
/**
* Get the sector's end angle
* @return
*/
getEndAngle(): number;
/**
* Set a new end angle to the sector
* @param endAngle
* @return this
* @fires Sector#shapechange
*/
setEndAngle(endAngle: number): this;
/**
* Gets the shell of the sector as a polygon, number of the shell points is decided by [options.numberOfShellPoints]{@link Sector#options}
* @return - shell coordinates
*/
getShell(): Coordinate[];
}
export interface SectorStatic {
new (
center: Coordinate | number[],
radius: number,
startAngle: number,
endAngle: number,
options?: EllipseOptions,
): Sector;
}
export const Sector: SectorStatic;
export interface Rectangle extends Polygon {
/**
* Get coordinates of rectangle's northwest
* @return
*/
getCoordinates(): Coordinate;
/**
* Gets polygons's coordinates
*
* @returns
*/
getCoordinates(): Coordinate[][];
/**
* Get rectangle's width
* @return
*/
getWidth(): number;
/**
* Set new width to the rectangle
* @param width - new width
* @fires Rectangle#shapechange
* @return this
*/
setWidth(width: number): this;
/**
* Get rectangle's height
* @return
*/
getHeight(): number;
/**
* Set new height to rectangle
* @param height - new height
* @fires Rectangle#shapechange
* @return this
*/
setHeight(height: number): this;
/**
* Gets the shell of the rectangle as a polygon
* @return - shell coordinates
*/
getShell(): Coordinate[];
/**
* Rectangle won't have any holes, always returns null
* @return an empty array
*/
getHoles(): object[];
/**
* Gets holes' coordinates of the polygon if it has.
* @returns
*/
getHoles(): Coordinate[][];
}
export interface RectangleStatic {
new (coordinates: Coordinate | number[], width: number, height: number, options?: PathOptions): Rectangle;
}
export const Rectangle: RectangleStatic;
export interface GeometryCollection extends Geometry {
/**
* Set new geometries to the geometry collection
* @param geometries
* @return this
* @fires GeometryCollection#shapechange
*/
setGeometries(geometries: Geometry[]): this;
/**
* Get geometries of the geometry collection
* @return geometries
*/
getGeometries(): Geometry[];
/**
* Executes the provided callback once for each geometry present in the collection in order.
* @param fn - a callback function
* @param context - callback's context
* @return this
*/
forEach(fn: (geometry: Geometry, idx: number) => void, context?: any): this;
/**
* Creates a GeometryCollection with all elements that pass the test implemented by the provided function.
* @param fn - Function to test each geometry
* @param context - Function's context
* @return A GeometryCollection with all elements that pass the test
* @example
* var filtered = collection.filter(['==', 'foo', 'bar]);
* @example
* var filtered = collection.filter(geometry => geometry.getProperties().foo === 'bar');
*/
filter(fn: ((geometry: Geometry, context?: any) => boolean) | any[], context?: any): GeometryCollection;
/**
* Translate or move the geometry collection by the given offset.
* @param offset - translate offset
* @return this
*/
translate(offset: Coordinate | number[]): this;
/**
* Translate or move the geometry by the given offset.
*
* @param x - x offset
* @param y - y offset
* @return this
* @fires Geometry#positionchange
* @fires Geometry#shapechange
*/
translate(x: number, y: number): this;
/**
* Whether the geometry collection is empty
* @return
*/
isEmpty(): boolean;
}
export interface GeometryCollectionStatic {
/**
* @param geometries - GeometryCollection's geometries
* @param [options=null] - options defined in [nGeometryCollection]{@link GeometryCollection#options}
*/
new (geometries: Geometry[], options?: object): GeometryCollection;
}
export const GeometryCollection: GeometryCollectionStatic;
export interface MultiGeometry extends GeometryCollection {
/**
* Get coordinates of the collection
* @return coordinates
*/
getCoordinates(): Coordinate[] | Coordinate[][] | Coordinate[][][];
/**
* Set new coordinates to the collection
* @param coordinates
* @returns this
* @fires maptalk.Geometry#shapechange
*/
setCoordinates(coordinates: Coordinate[] | Coordinate[][] | Coordinate[][][]): this;
}
export interface MultiGeometryStatic {
new (geoType: Class, type: string, data: Geometry[], options?: GeometryOptions): any;
}
export const MultiGeometry: MultiGeometryStatic;
export interface MultiPoint extends MultiGeometry {
/**
* Find the closet point to the give coordinate
* @param coordinate coordinate
* @returns coordinate
*/
findClosest(coordinate: Coordinate): Coordinate;
}
export interface MultiPointStatic {
new (data: number[][] | Coordinate[] | Marker[], options?: GeometryOptions): MultiPoint;
}
export const MultiPoint: MultiPointStatic;
export interface MultiLineString extends MultiGeometry {
_multiLineString: string;
}
export interface MultiLineStringStatic {
new (data: number[][][] | Coordinate[][] | LineString[], options?: LineStringOptions): MultiLineString;
}
export const MultiLineString: MultiLineStringStatic;
export interface MultiPolygon extends MultiGeometry {
_multiPolygon: string;
}
export interface MultiPolygonStatic {
new (data: number[][][][] | Coordinate[][][] | Polygon[], options?: GeometryOptions): MultiPolygon;
}
export const MultiPolygon: MultiPolygonStatic;
export namespace GeoJSON {
/**
* Convert one or more GeoJSON objects to geometry
* @param geoJSON - GeoJSON objects or GeoJSON string
* @param [foreachFn=undefined] - callback function for each geometry
* @return a geometry array when input is a FeatureCollection
* @example
* var collection = {
* "type": "FeatureCollection",
* "features": [
* { "type": "Feature",
* "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
* "properties": {"prop0": "value0"}
* },
* { "type": "Feature",
* "geometry": {
* "type": "LineString",
* "coordinates": [
* [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
* ]
* },
* "properties": {
* "prop0": "value0",
* "prop1": 0.0
* }
* },
* { "type": "Feature",
* "geometry": {
* "type": "Polygon",
* "coordinates": [
* [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
* [100.0, 1.0], [100.0, 0.0] ]
* ]
* },
* "properties": {
* "prop0": "value0",
* "prop1": {"this": "that"}
* }
* }
* ]
* }
* // A geometry array.
* const geometries = GeoJSON.toGeometry(collection, geometry => { geometry.config('draggable', true); });
*/
function toGeometry(geoJSON: string | object | object[], foreachFn?: (geometry: Geometry) => void): Geometry;
}
export class MapTool extends Eventable {
_markerLayer: Layer;
/**
* Adds the map tool to a map.
* @param map
* @return this
* @fires MapTool#add
*/
addTo(map: Map): this;
/**
* Gets the map it added to.
* @return map
*/
getMap(): Map;
/**
* Enable the map tool.
* @return this
* @fires MapTool#enable
*/
enable(): this;
/**
* Disable the map tool
* @return this
* @fires MapTool#disable
*/
disable(): this;
/**
* Returns whether the tool is enabled
* @return true | false
*/
isEnabled(): boolean;
remove(): boolean;
}
export class DrawTool extends MapTool {
/**
* Register a new mode for DrawTool
* @param name mode name
* @param modeAction modeActions
* @param modeAction.action the action of DrawTool: click, mousedown, clickDblclick
* @param modeAction.create the create method of drawn geometry
* @param modeAction.update the update method of drawn geometry
* @param modeAction.generate the method to generate geometry at the end of drawing.
* @example
* Register "CubicBezierCurve" mode to draw Cubic Bezier Curves.
*/
static registerMode(name: string, modeAction: DrawToolModeActionOptions): void;
/**
* Get mode actions by mode name
* @param name DrawTool mode name
* @return mode actions
*/
static getRegisterMode(name: string): object;
constructor(options?: DrawToolOptions);
/**
* Get current mode of draw tool
* @return mode
*/
getMode(): string;
/**
* Set mode of the draw tool
* @param mode - mode of the draw tool
* @expose
*/
setMode(mode: string): this;
/**
* Get symbol of the draw tool
* @return symbol
*/
getSymbol(): object;
/**
* Set draw tool's symbol
* @param symbol - symbol set
* @returns this
*/
setSymbol(symbol: object): this;
/**
* Get geometry is currently drawing
* @return geometry currently drawing
*/
getCurrentGeometry(): Geometry;
/**
* Undo drawing, only applicable for click/dblclick mode
* @return this
*/
undo(): this;
/**
* Redo drawing, only applicable for click/dblclick mode
* @return this
*/
redo(): this;
/**
* End current draw
* @param [param=null] params of drawend event
* @returns this
*/
endDraw(param?: object): this;
}
export class DistanceTool extends DrawTool {
constructor(optinos?: DistanceToolOptions);
/**
* Clear the measurements
* @return this
*/
clear(): this;
/**
* Get the VectorLayers with the geometries drawn on the map during measuring.
* @return
*/
getMeasureLayers(): Layer[];
/**
* Get last measuring result
* @return
*/
getLastMeasure(): number;
}
export class AreaTool extends DistanceTool {}
export namespace CRS {
/**
* Predefined CRS of well-known WGS84 (aka EPSG:4326)
*/
const WGS84: CRS;
/**
* Alias for CRS.WGS84
*/
const EPSG4326: CRS;
/**
* Projected Coordinate System used by google maps that has the following alias: 'EPSG:3785', 'GOOGLE', 'EPSG:900913'
*/
const EPSG3857: CRS;
/**
* A CRS represents a simple Cartesian coordinate system. <br>
* Maps x, y directly, is useful for maps of flat surfaces (e.g. indoor maps, game maps).
*/
const IDENTITY: CRS;
/**
* Official coordinate system in China (aka EPSG:4490), in most cases, it can be considered the same with WGS84.
* @see {@link http:// spatialreference.org/ref/sr-org/7408/}
*/
const CGCS2000: CRS;
/**
* Alias for static CGCS2000
*/
const EPSG4490: CRS;
/**
* Projection used by [Baidu Map]{@link http:// map.baidu.com}, a popular web map service in China.
*/
const BD09LL: CRS;
/**
* A encrypted CRS usded in the most online map services in China..
*
* @see {@link https:// en.wikipedia.org/wiki/Restrictions_on_geographic_data_in_China}
*/
const GCJ02: CRS;
/**
* Create a [proj4]{@link https:// github.com/OSGeo/proj.4} style CRS used by maptalks <br>
* @example
* {
* "type" : "proj4",
* "properties" : {
* "proj" : "+proj=longlat +datum=WGS84 +no_defs"
* }
* }
* var crs_wgs84 = CRS.createProj4("+proj=longlat +datum=WGS84 +no_defs");
* @param proj - a proj4 projection string.
* @return
*/
function createProj4(proj: string): CRS;
}
export class CRS {
type: string;
properties: object;
constructor(type: string, properties: object);
}
/**
* Transformation between projected coordinates and base 2d point system.
* A core class used internally for mapping map's (usually geographical) coordinates to 2d points.<br>
*
* @category geo
*
*/
export interface Transformation {
/**
* Transform a projected coordinate to a 2d point. <br>
* Parameter scale in transform/untransform method is used to scale the result 2d points on map's different zoom levels.
* @param coordinates - projected coordinate to transform
* @param scale - transform scale
* @return 2d point.
*/
transform(coordinates: number[] | Coordinate, scale: number, out?: Point): Point;
/**
* Transform a 2d point to a projected coordinate.
* @param point - 2d point
* @param scale - transform scale
* @return projected coordinate.
*/
untransform(point: Point, scale: number, out?: Coordinate): Coordinate;
}
export interface TransformationStatic {
/**
* The base 2d point system is a fixed system that is consistent with HTML coordinate system: on X-Axis, left is smaller and right is larger; on Y-Axis, top is smaller and bottom is larger. <br>
* As map's coordinates may not be in the same order(e.g. on a mercator projected earth, top is larger and bottom is smaller), <br>
* transformation provides mapping functions to map arbitrary coordinates system to the fixed 2d point system. <br>
* How to transform is decided by the constructor parameters which is a 4 number array [a, b, c, d]:<br>
* a : the order scale of X-axis values 1 means right is larger and -1 means the reverse, left is larger;<br>
* b : the order scale of Y-axis values 1 means bottom is larger and -1 means the reverse, top is larger;<br>
* c : x of the origin point of the projected coordinate system <br>
* d : y of the origin point of the projected coordinate system <br>
* e.g.: Transformation parameters for Google map: [1, -1, -20037508.34, 20037508.34] <br>
* @param matrix transformation array
*/
new (matrix: number[]): Transformation;
}
export const Transformation: TransformationStatic;
export abstract class Handler {
/**
* Enables the handler
* @return this
*/
enable(): this;
/**
* Disablesthe handler
* @return this
*/
disable(): this;
/**
* Returns true if the handler is enabled.
* @return
*/
enabled(): boolean;
}
export abstract class DragHandler extends Handler {}
export namespace SpatialReference {
function getProjectionInstance(prjName: string): any;
function loadArcgis(url: string, cb: (err: any, spatialRef: any) => void, options?: object): void;
function loadWMTS(url: string, cb: (err: any, spatialRef: any) => void, options?: object): void;
} | the_stack |
import {Injectable} from '@angular/core';
import {TranslationFile} from './translation-file';
import {isNullOrUndefined} from '../common/util';
import {BackendServiceAPI} from './backend-service-api';
import {TranslationProject, WorkflowType} from './translation-project';
import {combineLatest, Observable, of} from 'rxjs';
import {AutoTranslateDisabledReasonKey, AutoTranslateServiceAPI} from './auto-translate-service-api';
import {AutoTranslateSummaryReport} from './auto-translate-summary-report';
import {TranslationUnit} from './translation-unit';
import {map, switchMap, tap} from 'rxjs/operators';
import {IFileDescription} from '../file-accessors/common/i-file-description';
import {FileStatus, ICommitData, IFileAccessService, IFileStats} from '../file-accessors/common/i-file-access-service';
import {FileAccessServiceFactoryService} from '../file-accessors/common/file-access-service-factory.service';
import {IFileAccessConfiguration} from '../file-accessors/common/i-file-access-configuration';
import {FileAccessorType} from '../file-accessors/common/file-accessor-type';
import {IFile} from '../file-accessors/common/i-file';
import {DownloadUploadConfiguration} from '../file-accessors/download-upload/download-upload-configuration';
@Injectable()
export class TinyTranslatorService {
/**
* List of projects for work.
*/
private _projects: TranslationProject[];
/**
* The current project.
*/
private _currentProject: TranslationProject;
constructor(private backendService: BackendServiceAPI,
private fileAccessServiceFactoryService: FileAccessServiceFactoryService,
private autoTranslateService: AutoTranslateServiceAPI) {
this._projects = this.backendService.projects();
const currentProjectId = this.backendService.currentProjectId();
if (currentProjectId) {
this._currentProject = this._projects.find((project) => project.id === currentProjectId);
}
const currentTransUnitId: string = this.backendService.currentTransUnitId();
if (currentTransUnitId && this.currentProject()) {
const transUnit = this.currentProject().translationFile.allTransUnits().find(tu => tu.id() === currentTransUnitId);
this.currentProject().translationFileView.selectTransUnit(transUnit);
}
this.autoTranslateService.setApiKey(this.backendService.autoTranslateApiKey());
}
/**
* Add a new project.
* @param project project
* @return list of errors found in file selection.
*/
public addProject(project: TranslationProject): string[] {
this._projects.push(project);
this.backendService.store(project);
// TODO error handling
return [];
}
/**
* Create a new project.
* (you must add it with addProject to use it).
* @param projectName projectName
* @param file selected xlf or xmb file to translate
* @param masterXmbFile in case of xmb the master file
* @param workflowType Type of workflow used in project (singleUser versus withReview).
* @return TranslationProject
*/
public createProject(projectName: string,
file: IFileDescription,
masterXmbFile?: IFileDescription,
workflowType?: WorkflowType): Observable<TranslationProject> {
if (isNullOrUndefined(file)) {
return of(new TranslationProject(projectName, null, workflowType));
}
const fileAccessService: IFileAccessService = this.fileAccessServiceFactoryService.getFileAccessService(file.configuration.type);
return combineLatest(fileAccessService.load(file), (masterXmbFile) ? fileAccessService.load(masterXmbFile) : of(null)).pipe(
map(contentArray => {
const loadedFile = contentArray[0];
const loadedMaster = contentArray[1];
return TranslationFile.fromFile(loadedFile as IFile, loadedMaster);
}),
map((translationFile: TranslationFile) => {
return new TranslationProject(projectName, translationFile, workflowType);
})
);
}
public setCurrentProject(project: TranslationProject) {
let id: string = null;
if (project) {
if (isNullOrUndefined(this._projects.find(p => p === project))) {
throw new Error('oops, selected project not in list');
}
id = project.id;
}
this._currentProject = project;
this.backendService.storeCurrentProjectId(id);
}
public currentProject(): TranslationProject {
return this._currentProject;
}
/**
* Select a TranslationUnit, if it is currently in the filtered list.
* If it is not, will do nothing.
* @param transUnit transUnit
*/
public selectTransUnit(transUnit: TranslationUnit) {
if (!this.currentProject()) {
return;
} else {
if (this.currentProject().translationFileView.selectTransUnit(transUnit)) {
this.backendService.storeCurrentTransUnitId(transUnit.id());
}
}
}
/**
* Navigate to next unit.
*/
public nextTransUnit() {
if (!this.currentProject()) {
return;
} else {
const transUnit = this.currentProject().translationFileView.nextTransUnit();
this.backendService.storeCurrentTransUnitId(transUnit.id());
}
}
/**
* Navigate to previous unit.
*/
public prevTransUnit() {
if (!this.currentProject()) {
return;
} else {
const transUnit = this.currentProject().translationFileView.prevTransUnit();
this.backendService.storeCurrentTransUnitId(transUnit.id());
}
}
public projects(): TranslationProject[] {
return this._projects;
}
public commitChanges(project: TranslationProject) {
this.backendService.store(project);
}
public downloadProject(project: TranslationProject) {
this.fileAccessServiceFactoryService.getFileAccessService(FileAccessorType.DOWNLOAD_UPLOAD)
.save(project.translationFile.editedFile());
project.translationFile.markExported();
this.commitChanges(project);
}
public publishProject(
project: TranslationProject,
saveAs: IFileDescription|null,
commitData: ICommitData,
confirmModifiedCallback: () => Observable<boolean>,
confirmOverrideCallback: () => Observable<boolean>): Observable<boolean> {
let fileToSave = project.translationFile.editedFile();
const isSavePositionChanged = !!saveAs && !saveAs.equals(fileToSave.description);
if (isSavePositionChanged) {
fileToSave = fileToSave.copyForNewDescription(saveAs);
}
const fileAccessService =
this.fileAccessServiceFactoryService.getFileAccessService(fileToSave.description.configuration.type);
return fileAccessService.stats(fileToSave).pipe(
switchMap((stats: IFileStats) => {
if (isSavePositionChanged && stats.status !== FileStatus.EXISTS_NOT) {
return confirmOverrideCallback().pipe(
tap(doSave => {commitData.override = doSave; })
);
}
if (!isSavePositionChanged && stats.status === FileStatus.CHANGED) {
return confirmModifiedCallback().pipe(
tap(doSave => {commitData.override = doSave; })
);
}
if (!isSavePositionChanged) {
commitData.override = true;
}
return of(true);
}),
switchMap((doSave: boolean) => {
if (doSave) {
return fileAccessService.save(fileToSave, commitData)
.pipe(
tap(() => {
if (!saveAs) {
project.translationFile.markExported();
this.commitChanges(project);
}
}),
map(() => {
return true;
})
);
} else {
return of(false);
}
})
);
}
public deleteProject(project: TranslationProject) {
this.backendService.deleteProject(project);
const index = this._projects.findIndex(p => p === project);
if (index >= 0) {
this._projects = this._projects.slice(0, index).concat(this._projects.slice(index + 1));
if (project === this.currentProject()) {
this.setCurrentProject(null);
}
}
}
/**
* Set an API key for Google Translate.
* Will be stored in local storage.
* @param key key
*/
public setAutoTranslateApiKey(key: string) {
this.autoTranslateService.setApiKey(key);
this.backendService.storeAutoTranslateApiKey(key);
}
/**
* Get the currently active Google Translate API key.
* @return api key
*/
public autoTranslateApiKey(): string {
return this.autoTranslateService.apiKey();
}
/**
* Test, wether auto translation is possible for current project.
* @return Observable<boolean>
*/
public canAutoTranslate(): Observable<boolean> {
if (isNullOrUndefined(this.currentProject()) || !this.currentProject().canTranslate()) {
return of(false);
}
return this.canAutoTranslateForLanguages(
this.currentProject().translationFile.sourceLanguage(),
this.currentProject().translationFile.targetLanguage());
}
/**
* Test, wether auto translation is possible for given languages.
* @param source Source Language
* @param target Target Language
* @return Observable<boolean>
*/
public canAutoTranslateForLanguages(source: string, target: string): Observable<boolean> {
return this.autoTranslateService.canAutoTranslate(source, target);
}
/**
* Reason, why auto translation is not possible for current project.
* @return Observable<string>
*/
public autoTranslateDisabledReason(): Observable<string> {
if (isNullOrUndefined(this.currentProject()) || !this.currentProject().canTranslate()) {
return of('no translatable project');
}
return this.autoTranslateDisabledReasonForLanguages(
this.currentProject().translationFile.sourceLanguage(),
this.currentProject().translationFile.targetLanguage());
}
/**
* Reason, why auto translation is not possible for given languages.
* @return Observable<string>
*/
public autoTranslateDisabledReasonForLanguages(source: string, target: string): Observable<string> {
return this.autoTranslateService.disabledReason(source, target).pipe(
map((reason) => {
if (isNullOrUndefined(reason)) {
return null; // means not disabled, everything is ok!
}
switch (reason.reason) {
case AutoTranslateDisabledReasonKey.NO_PROVIDER:
return 'no provider';
case AutoTranslateDisabledReasonKey.NO_KEY:
return 'no key';
case AutoTranslateDisabledReasonKey.INVALID_KEY:
return 'invalid key';
case AutoTranslateDisabledReasonKey.SOURCE_LANG_NOT_SUPPORTED:
return 'source language not supported';
case AutoTranslateDisabledReasonKey.TARGET_LANG_NOT_SUPPORTED:
return 'target language not supported';
case AutoTranslateDisabledReasonKey.CONNECT_PROBLEM:
return 'connection problem: ' + reason.details;
}
}
));
}
/**
* Test call the auto translate service.
* @param message message
* @param source source
* @param target target
* @return translated string
*/
public testAutoTranslate(message: string, source: string, target: string): Observable<string> {
return this.autoTranslateService.translate(message, source, target);
}
/**
* Auto translate all untranslated units.
*/
public autoTranslate(): Observable<AutoTranslateSummaryReport> {
if (this.currentProject() && this.currentProject().translationFile) {
return this.currentProject().translationFile.autoTranslateUsingService(this.autoTranslateService).pipe(
map((summary) => {
this.commitChanges(this.currentProject());
return summary;
}
));
} else {
return of(new AutoTranslateSummaryReport());
}
}
/**
* Get all available accessor configurations from backend.
*/
getFileAccessConfigurations(): Observable<IFileAccessConfiguration[]> {
return this.backendService.fileAccessConfigurations().pipe(
map(configs => [DownloadUploadConfiguration.singleInstance(), ...configs])
);
}
} | the_stack |
import * as React from 'react';
export const introspect = (mutationName, setFields, args) => {
const inputTypeName: string = mutationName + 'Input';
fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `query typeQuery($inputType: String!)
{
__type(name: $inputType) {
name
inputFields {
name
type {
name
kind
ofType {
name
kind
enumValues {
name
description
}
}
}
}
}
}`,
variables: {
inputType: inputTypeName,
},
}),
})
.then((res) => res.json())
.then(({data}) => {
if (!data) {
return console.error(
'ERROR at periqles: Failed to introspect. No data received.',
);
}
if (!data.__type) {
return console.error(
'ERROR at periqles: Failed to introspect. No __type property on received data.',
);
}
const typeSchema = data.__type;
// intuit fields off the schema
const fieldsArr: PeriqlesFieldInfo[] = fieldsArrayGenerator(typeSchema, args);
setFields(fieldsArr);
})
.catch((err) => {
console.error('ERROR at periqles: Failed to introspect.', err);
});
};
export const fieldsArrayGenerator: FieldsArrayGenerator = (inputType, args = {}) => {
if (!inputType || !inputType.inputFields) {
console.error('ERROR at PeriqlesForm: mutation input type is undefined.');
return [];
}
const fieldsArray: Array<PeriqlesFieldInfo> = [];
inputType.inputFields.forEach((field) => {
// exclude from the form any inputs accounted for by args
if (args[field.name]) return;
const fieldObj: PeriqlesFieldInfo = {
name: field.name,
};
//check the field.type.kind to see if the field is NON_NULL (required)
//if so, set fieldObj.required to true
fieldObj.required = field.type.kind === 'NON_NULL';
// the input field is a scalar, nullable type
if (field.type.name && field.type.kind === 'SCALAR') {
fieldObj.type = field.type.name;
}
// the input field is an enumerated type (whether or not wrapped in a NON_NULL type)
else if (field.type.kind === 'ENUM' || field.type.ofType?.kind === 'ENUM') {
fieldObj.type = 'Enum';
try {
const optionsArr =
field.type.enumValues || field.type.ofType?.enumValues || [];
// provide each option a type property
fieldObj.options = optionsArr.map((option: EnumValue) => {
let value, type;
switch (typeof option.name) {
case 'number':
case 'bigint':
value = option.name;
type = 'Int';
break;
case 'boolean':
// stringify booleans b/c HTML typing doesn't allow for boolean value attributes
value = `${option.name}`;
type = 'Boolean';
break;
default:
value = option.name;
type = 'String';
}
const mappedOption: PeriqlesFieldOption = {
name: `${option.name}`,
label: `${option.name}`,
value,
type,
};
return mappedOption;
});
} catch (err) {
console.error(
'ERROR at PeriqlesForm: Failure to assign enumerated field.',
err,
);
}
}
// the input field is a scalar wrapped in a NON_NULL type
else if (field.type.ofType?.name && field.type.ofType?.kind === 'SCALAR') {
// TODO
fieldObj.type = field.type.ofType.name;
}
// TODO: the input field is not a scalar or enum type
else {
console.warn(
`The '${field.name}' input field is of a complex type not currently supported by PeriqlesForm. It will default to a 'String'. Type:`,
field,
);
fieldObj.type = 'String';
}
fieldsArray.push(fieldObj);
});
return fieldsArray;
};
/* eslint-disable flowtype/no-types-missing-file-annotation */
/**
* Builds an HTML element to collect user input for a GraphQL mutation based on user-provided instructions.
* @param {Object} field An object representing an input field for a GraphQL mutation. Example: {name: "name", type: "String"}
* @param {Object} specs An object representing developer-specified information to use for an HTML element representing this field.
* @param {Function} handleChange
* @param {Object} formState
* @param {Function} setFormState
* @return Returns the specified HTML input element with the specified label and specified sub-options, if any.
*/
export const generateSpecifiedElement: GenerateSpecifiedElement = ({
field,
specs,
formState,
handleChange,
setFormState,
}) => {
if (specs.render) {
return specs.render({formState, setFormState, handleChange});
}
//If label isn't given, set it as field.name w/ spaces & 1st letter capitalized
if (!specs.label) {
specs.label = field.name.replace(/([a-z])([A-Z])/g, '$1 $2'); // put spaces before capital letters
specs.label = specs.label[0].toUpperCase() + specs.label.slice(1); // capitalize first letter
}
else field.label = specs.label;
switch (specs.element) {
case 'range':
return (
<label>
{specs.label}
<input
type="range"
className={field.name + '-range periqles-range'}
name={field.name}
min={specs.min || 0}
max={specs.max || Infinity}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}
/>
</label>
);
case 'image':
return (
<label>
{specs.label}
<input
type="image"
className={field.name + '-image periqles-image'}
name={field.name}
src={specs.src}
alt={specs.label}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}
/>
</label>
);
case 'radio':
if (!specs.options && !field.options) {
return (<label>
{specs.label}
<input
type="text"
className={`${field.name}-radio periqles-radio`}
name={field.name}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}></input>
</label>);
}
let radioOptions: Array<PeriqlesFieldOption> = [];
if (specs.options && field.options) {
specs.options.forEach((spec) => {
field.options?.forEach((option) => {
if (option.value === spec.value) {
const newOption: PeriqlesFieldOption = {
name: option.name,
label: spec.label,
value: option.value,
type: option.type,
};
return radioOptions.push(newOption);
}
});
});
} else if (specs.options && !field.options) {
// dev can constrain possible inputs on the frontend for fields that are not enumerated on the schema
specs.options.forEach((spec) => {
const newOption: PeriqlesFieldOption = {
name: spec.label,
label: spec.label,
value: spec.value,
type: typeof spec.value,
};
radioOptions.push(newOption);
});
} else {
// specs didn't provide options
radioOptions = field.options;
}
return (
<div className={field.name + '-radio periqles-radio'}>
<label className="periqles-radio-div-label">{specs.label}</label>
{radioOptions.map((option, index) => {
return (
<label
key={`${field.name}radio-label${index}`}
className="periqles-radio-option-label">
<input
key={`${field.name}radio-btn${index}`}
type="radio"
name={field.name}
className={field.name + '-radio-option periqles-radio-option'}
value={option.value as string | number | readonly string[]}
onChange={handleChange}
// dynamically set initial "checked" attribute based on whether this option's value matches the div's value
defaultChecked={option.value === formState[field.name]}
/>
{option.label}
</label>
);
})}
</div>
);
case 'select':
if (!specs.options && !field.options) {
return (<label>
{specs.label}
<input
type="text"
className={`${field.name}-select periqles-select`}
name={field.name}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}></input>
</label>);
}
let selectOptions: Array<PeriqlesFieldOption> = [];
if (specs.options && field.options) {
specs.options.forEach((spec) => {
field.options?.forEach((option) => {
if (option.value === spec.value) {
const newOption: PeriqlesFieldOption = {
name: option.name,
label: spec.label,
value: option.value,
type: option.type,
};
return selectOptions.push(newOption);
}
});
});
} else if (specs.options && !field.options) {
// dev can constrain possible inputs on the frontend for fields that are not enumerated on the schema
specs.options.forEach((spec) => {
const newOption: PeriqlesFieldOption = {
name: spec.label,
label: spec.label,
value: spec.value,
type: typeof spec.value,
};
selectOptions.push(newOption);
});
} else {
// specs didn't provide options
selectOptions = field.options;
}
return (
<label>
{specs.label}
<select
className={field.name + '-select periqles-select'}
name={field.name}
// defaultValue={selectOptions[0].value}
defaultValue={''}
onChange={handleChange}>
<option
key={`${field.name}selectnulloption`}
value={''}
className={
field.name + '-select-option periqles-select-option'
}>
Choose one...
</option>
{selectOptions.map((option, index) => {
return (
<option
key={`${field.name}select${option.name}option${index}`}
value={option.value as string | number | readonly string[]}
className={
field.name + '-select-option periqles-select-option'
}>
{option.label}
</option>
);
})}
</select>
</label>
);
case 'textarea':
return (
<label>
{specs.label}
<textarea
className={field.name + '-textarea periqles-textarea'}
name={field.name}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}
/>
</label>
);
default:
return (
<label>
{specs.label}
<input
type="text"
className={`${field.name}-text periqles-text`}
name={field.name}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}></input>
</label>
);
}
};
/**
* Builds an HTML element to collect user input for a GraphQL mutation based on default logic.
* @param {Object} field An object representing an input field for a GraphQL mutation.
* @param {Object} formState
* @param {Function} handleChange
* @return Returns an HTML input element.
*/
export const generateDefaultElement: GenerateDefaultElement = ({field, formState, handleChange}) => {
// assign a label that matches name but w/ spaces between words and first char uppercased
field.label = field.name.replace(/([a-z])([A-Z])/g, '$1 $2');
field.label = field.label[0].toUpperCase() + field.label.slice(1);
switch (field.type) {
case 'Int':
return (
<label>
{field.label}
<input
type="number"
className={field.name + '-number periqles-number'}
name={field.name}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}></input>
</label>
);
// TODO: formState values restricted only to numbers or strings due to HTML input type defs
case 'Boolean':
return (
<label>
{field.label}
<input
type="checkbox"
className={field.name + '-checkbox periqles-checkbox'}
name={field.name}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}></input>
</label>
);
case 'Enum':
if (!field.options || !field.options.length) {
return (<label>
{field.label}
<input
type="text"
className={`${field.name}-select periqles-select`}
name={field.name}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}></input>
</label>);
}
const selectOptions: Array<PeriqlesFieldOption> = field.options;
return (
<label>
{field.label}
<select
className={field.name + '-select periqles-select'}
name={field.name}
// defaultValue={selectOptions[0].value}
defaultValue={''}
onChange={handleChange}>
<option
key={`${field.name}selectnulloption`}
value={''}
className={
field.name + '-select-option periqles-select-option'
}>
Choose one...
</option>
{selectOptions.map((option, index) => {
return (
<option
key={`${field.name}select${option.name}option${index}`}
value={option.value as string | number | readonly string[]}
className={
field.name + '-select-option periqles-select-option'
}>
{option.label}
</option>
);
})}
</select>
</label>
);
default:
const elementLookup = {
pass: 'password',
password: 'password',
color: 'color',
colour: 'color',
url: 'url',
link: 'url',
date: 'date',
time: 'time',
file: 'file',
datetime: 'datetime',
timestamp: 'datetime',
telephone: 'tel',
phone: 'tel',
mobile: 'tel',
phonenumber: 'tel',
cell: 'tel',
};
const textFieldName: string = field.name.toLowerCase();
const elementType: string = elementLookup[textFieldName] || 'text';
return (
<label>
{field.label}
<input
type={elementType}
className={`${field.name}-${elementType} periqles-${elementType}`}
name={field.name}
value={formState[field.name] as string | number | readonly string[]}
onChange={handleChange}></input>
</label>
);
}
}; | the_stack |
import Boom from '@hapi/boom';
import * as Cookie from '@hapi/cookie';
import type { Plugin, Request } from '@hapi/hapi';
import Joi from 'joi';
import * as OpenID from 'openid-client';
import { URL } from 'url';
import type { NostalgieAuthOptions } from '../../../../settings';
import type { ServerAuthCredentials } from '../../../auth/server';
const AuthState = Joi.object({
nonce: Joi.string().required(),
returnTo: Joi.string().required(),
});
interface AuthState {
nonce: string;
returnTo: string;
}
interface ServerAuthSession {
accessToken: string;
expiresAt: number;
idToken: string;
refreshToken?: string;
scope?: string;
}
export const authPlugin: Plugin<{ auth: NostalgieAuthOptions; publicUrl: string }> = {
name: 'nostalgie/auth',
dependencies: ['hapi-pino'],
async register(server, options) {
const { auth } = options;
await server.register(Cookie);
server.logger.trace(options, 'starting auth module');
server.auth.strategy('nostalgie-session', 'cookie', {
cookie: {
name: 'nsid',
encoding: 'iron',
ttl: 1000 * 60 * 60 * 24 * 7 * 4, // 4 weeks
password: auth.cookieSecret,
path: '/',
isSecure: process.env.NODE_ENV !== 'development',
},
keepAlive: true,
validateFunc: async (_request, session: ServerAuthSession) => {
let tokenSet = new OpenID.TokenSet({
access_token: session.accessToken,
expires_at: session.expiresAt,
id_token: session.idToken,
refresh_token: session.refreshToken,
scope: session.scope,
});
if (tokenSet.expired()) {
if (tokenSet.refresh_token) {
const issuer = await fetchIssuerWithCache(auth.issuer);
const client = new issuer.Client({
client_id: auth.clientId,
client_secret: auth.clientSecret,
});
try {
const oldTokenSet = tokenSet;
tokenSet = await client.refresh(tokenSet);
session.accessToken = tokenSet.access_token!;
session.idToken = tokenSet.id_token!;
session.expiresAt = tokenSet.expires_at!;
session.refreshToken = tokenSet.refresh_token || oldTokenSet.refresh_token;
} catch (err) {
server.logger.debug(
{
err,
},
'error refreshing tokens'
);
return {
valid: false,
};
}
} else {
return {
valid: false,
};
}
}
const user = await fetchUserProfileWithCache(session.accessToken);
const credentials: ServerAuthCredentials = {
accessToken: session.accessToken,
idToken: session.idToken,
expiresAt: session.expiresAt,
claims: tokenSet.claims(),
scope: typeof tokenSet.scope === 'string' ? tokenSet.scope.split(/\s+/) : [],
user,
};
return {
valid: true,
credentials,
};
},
});
// Set as the default auth handler. Routes should explicitly opt out if then don't
// want auth.
server.auth.default({
strategy: 'nostalgie-session',
mode: 'optional',
});
server.state('nauth', {
encoding: 'iron',
password: auth.cookieSecret,
path: '/',
isSecure: process.env.NODE_ENV !== 'development',
isHttpOnly: true,
ttl: null, // Session lifetime
isSameSite: 'Lax',
});
// Issuer fetching
function fetchIssuer(issuer: string) {
return OpenID.Issuer.discover(issuer);
}
server.method('fetchIssuerWithCache', fetchIssuer, {
cache: {
//@ts-ignore
cache: 'memory',
generateTimeout: 5000,
expiresIn: 30000,
staleIn: 10000,
staleTimeout: 100,
},
});
const fetchIssuerWithCache: typeof OpenID.Issuer.discover = server.methods.fetchIssuerWithCache;
async function fetchUserProfile(accessToken: string) {
const issuer = await fetchIssuerWithCache(auth.issuer);
const client = new issuer.Client({
client_id: auth.clientId,
});
const userInfo = await client.userinfo(accessToken);
return userInfo;
}
server.method('fetchUserProfileWithCache', fetchUserProfile, {
cache: {
//@ts-ignore
cache: 'memory',
generateTimeout: 5000,
expiresIn: 30000,
staleIn: 10000,
staleTimeout: 100,
},
});
const fetchUserProfileWithCache: typeof fetchUserProfile =
server.methods.fetchUserProfileWithCache;
server.route({
method: 'GET',
path: '/.nostalgie/login',
options: {
auth: {
strategy: 'nostalgie-session',
mode: 'try',
},
cors: false,
validate: {
query: Joi.object({
return_to: Joi.string().default('/'),
scope: Joi.string(),
audience: Joi.string().uri(),
}).optional(),
},
},
handler: async (request, h) => {
const returnTo = validateReturnTo(request, request.query.return_to);
const issuer = await fetchIssuerWithCache(auth.issuer);
const client = new issuer.Client({
client_id: auth.clientId,
redirect_uris: [`${server.info.uri}/.nostalgie/callback`],
response_types: ['code'],
});
const nonce = OpenID.generators.nonce();
const requestedScope = new Set(
request.query.scope ? request.query.scope.split(/\s+/) : undefined
);
requestedScope.add('openid');
// Let's get their email
requestedScope.add('email');
// We want to be able to request the user profile
requestedScope.add('profile');
// Ask for a refresh token
requestedScope.add('offline_access');
const url = client.authorizationUrl({
audience: request.query.audience,
scope: [...requestedScope].join(' '),
response_mode: 'query',
nonce,
});
request.logger.info(
{
returnTo,
},
'Starting login transaction'
);
h.state('nauth', { nonce, returnTo });
return h.redirect(url);
},
});
server.route({
method: 'GET',
path: '/.nostalgie/logout',
options: {
auth: {
strategy: 'nostalgie-session',
mode: 'try',
},
cors: false,
validate: {
query: Joi.object({
return_to: Joi.string().default('/'),
}).optional(),
},
},
handler: async (request, h) => {
// const issuer = await fetchIssuerWithCache(auth.issuer);
// const client = new issuer.Client({
// client_id: auth.clientId,
// return_tos: [`${server.info.uri}/.nostalgie/callback`],
// response_types: ['code'],
// });
// const tokenSet = new OpenID.TokenSet({
// access_token: (request.auth.credentials.user as any).accessToken,
// id_token: (request.auth.credentials.user as any).idToken,
// refresh_token: (request.auth.credentials.user as any).refreshToken,
// expires_at: (request.auth.credentials.user as any).expiresAt,
// expires_in: (request.auth.credentials.user as any).expiresIn,
// });
// const endSessionUrl = client.endSessionUrl({
// id_token_hint: tokenSet,
// post_logout_return_to: '/',
// });
const returnTo = validateReturnTo(request, request.query.return_to);
request.logger.info(
{
claims: {
aud: (request.auth.credentials as any)?.claims.aud,
iss: (request.auth.credentials as any)?.claims.iss,
exp: (request.auth.credentials as any)?.claims.exp,
iat: (request.auth.credentials as any)?.claims.iat,
sub: (request.auth.credentials as any)?.claims.sub,
},
returnTo,
},
'Logged out'
);
request.cookieAuth.clear();
return h.redirect(returnTo).unstate('nauth');
},
});
server.route({
method: 'GET',
path: '/.nostalgie/callback',
options: {
auth: {
strategy: 'nostalgie-session',
mode: 'try',
},
cors: false,
state: {
parse: true,
failAction: 'error',
},
},
handler: async (request, h) => {
if (request.auth.isAuthenticated) {
return h.redirect('/');
}
const nauthState = request.state.nauth;
// Clear the session cookie now that it has been consumed
h.unstate('nauth');
const validationResult = AuthState.validate(nauthState, {
stripUnknown: true,
});
if (validationResult.error) {
request.logger.warn(
{
err: validationResult.error,
},
'Error while validating authentication state cookie payload'
);
throw Boom.badImplementation();
}
const nauth = validationResult.value as AuthState;
const returnTo = validateReturnTo(request, nauth.returnTo);
const redirectUri = `${server.info.uri}/.nostalgie/callback`;
const issuer = await fetchIssuerWithCache(auth.issuer);
const client = new issuer.Client({
client_id: auth.clientId,
client_secret: auth.clientSecret,
redirect_uris: [redirectUri],
// response_types: ['id_token token'],
});
const params = client.callbackParams({
method: request.raw.req.method!,
url: request.raw.req.url!,
body: request.payload,
} as any);
const tokenSet = await client.callback(redirectUri, params, {
nonce: nauth.nonce,
});
if (!tokenSet.access_token) {
request.logger.warn(
{ issuer: auth.issuer },
'received a token set lacking an access_token'
);
throw Boom.badImplementation();
}
if (!tokenSet.id_token) {
request.logger.warn({ issuer: auth.issuer }, 'received a token set lacking an id_token');
throw Boom.badImplementation();
}
if (!tokenSet.expires_at) {
request.logger.warn(
{ issuer: auth.issuer },
'received a token set lacking an expires_at'
);
throw Boom.badImplementation();
}
const serverAuth: ServerAuthSession = {
accessToken: tokenSet.access_token,
expiresAt: tokenSet.expires_at,
idToken: tokenSet.id_token,
refreshToken: tokenSet.refresh_token,
scope: tokenSet.scope,
};
request.cookieAuth.set(serverAuth);
const claims = tokenSet.claims();
request.logger.info(
{
claims: {
aud: claims.aud,
iss: claims.iss,
exp: claims.exp,
iat: claims.iat,
sub: claims.sub,
},
returnTo,
},
'Login callback completed'
);
return h.redirect(returnTo);
},
});
},
};
function validateReturnTo(request: Request, redirectCandidate: string): string {
let returnTo = '/';
try {
const publicUrlObj = new URL(request.server.info.uri);
const resolvedUrl = new URL(redirectCandidate, publicUrlObj);
if (
publicUrlObj.hostname === resolvedUrl.hostname &&
publicUrlObj.port === resolvedUrl.port &&
publicUrlObj.protocol === resolvedUrl.protocol &&
resolvedUrl.pathname.startsWith(publicUrlObj.pathname)
) {
returnTo = `${resolvedUrl.pathname}?${resolvedUrl.search}`;
} else {
request.logger.warn(
{
return_to: redirectCandidate,
},
'Rejecting unsafe redirect'
);
}
} catch (err) {
request.logger.warn(
{
return_to: redirectCandidate,
},
'Rejecting unsafe redirect'
);
}
return returnTo;
} | the_stack |
import cx from 'classnames'
import * as FF from 'final-form'
import * as FP from 'fp-ts'
import * as R from 'ramda'
import * as React from 'react'
import { useDropzone, FileWithPath } from 'react-dropzone'
import * as RF from 'react-final-form'
import * as M from '@material-ui/core'
import SubmitSpinner from 'containers/Bucket/PackageDialog/SubmitSpinner'
import * as Notifications from 'containers/Notifications'
import Logo from 'components/Logo'
import * as CatalogSettings from 'utils/CatalogSettings'
import * as validators from 'utils/validators'
import * as Form from '../Form'
const useInputColorStyles = M.makeStyles((t) => ({
root: {
alignItems: 'flex-start',
display: 'flex',
padding: '2px',
},
input: {
flexGrow: 1,
textAlign: 'center',
marginLeft: t.spacing(2),
},
picker: {
height: '40px',
width: '50px',
},
pickerBlank: {
opacity: 0.3,
'&:hover': {
opacity: 1,
},
},
}))
type InputColorProps = Partial<M.TextFieldProps> & {
input: {
value: string
onChange: (value: string) => void
}
errors: Record<string, React.ReactNode>
meta: RF.FieldMetaState<string>
}
function InputColor({
errors,
meta,
input: { value, onChange },
...props
}: InputColorProps) {
const error = meta.submitFailed && (meta.error || meta.submitError)
const classes = useInputColorStyles()
const handleChange = React.useCallback(
(event) => onChange(event.target.value),
[onChange],
)
const isValidHex = React.useMemo(
() => value && value.length === 7 && !validators.hexColor(value),
[value],
)
return (
<div className={classes.root}>
<input
className={cx(classes.picker, { [classes.pickerBlank]: !value })}
onChange={handleChange}
type="color"
value={isValidHex ? value : props.placeholder}
/>
<M.TextField
className={classes.input}
error={!!error}
helperText={error ? errors[error] || error : null}
onChange={handleChange}
size="small"
value={value}
variant="outlined"
{...props}
/>
</div>
)
}
const useInputFileStyles = M.makeStyles((t) => ({
root: {
alignItems: 'center',
display: 'flex',
outline: `2px dashed ${t.palette.primary.light}`,
padding: '2px',
},
note: {
flexGrow: 1,
textAlign: 'center',
},
placeholder: {
alignItems: 'center',
border: `1px solid ${t.palette.action.disabled}`,
display: 'flex',
height: '50px',
justifyContent: 'center',
width: '50px',
},
preview: {
height: '50px',
width: '50px',
},
}))
interface InputFileProps {
input: {
value: FileWithPath | string
onChange: (value: FileWithPath) => void
}
}
function InputFile({ input: { value, onChange } }: InputFileProps) {
const classes = useInputFileStyles()
const onDrop = React.useCallback(
(files: FileWithPath[]) => {
onChange(files[0])
},
[onChange],
)
const { getInputProps, getRootProps } = useDropzone({
maxFiles: 1,
onDrop,
})
const previewUrl = React.useMemo(() => {
if (!value || typeof value === 'string') return null
return URL.createObjectURL(value)
}, [value])
return (
<div className={classes.root} {...getRootProps()}>
<input {...getInputProps()} />
{!!value && typeof value === 'string' && (
<Logo src={value} height="50px" width="50px" />
)}
{!!previewUrl && <img className={classes.preview} src={previewUrl} />}
{!value && (
<div className={classes.placeholder}>
<M.Icon>hide_image</M.Icon>
</div>
)}
<p className={classes.note}>Drop logo here</p>
</div>
)
}
const useThemePreviewStyles = M.makeStyles((t) => ({
root: {
alignItems: 'center',
display: 'flex',
margin: t.spacing(1, 0, 0),
},
inner: {
...t.typography.body2,
minWidth: '100px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
logoWrapper: {
padding: t.spacing(1),
backgroundColor: ({ backgroundColor }: { backgroundColor?: string }) =>
backgroundColor || '#282b50',
alignItems: 'center',
display: 'flex',
height: '46px',
justifyContent: 'center',
},
logo: {
color: '#fff',
maxHeight: '100%',
maxWidth: '100%',
},
}))
interface ThemePreviewProps {}
function ThemePreview({}: ThemePreviewProps) {
const settings = CatalogSettings.use()
const classes = useThemePreviewStyles({
backgroundColor: settings?.theme?.palette?.primary?.main,
})
return (
<div className={classes.root}>
<div className={cx(classes.inner, classes.logoWrapper)}>
{settings?.logo?.url ? (
<Logo
height="46px"
width="46px"
className={classes.logo}
src={settings?.logo?.url}
/>
) : (
<M.Icon className={classes.logo}>hide_image</M.Icon>
)}
</div>
</div>
)
}
const useThemeEditorStyles = M.makeStyles((t) => ({
actions: {
alignItems: 'center',
display: 'flex',
marginTop: t.spacing(1),
},
progress: {
marginLeft: t.spacing(1),
},
notConfigured: {
...t.typography.body1,
marginRight: t.spacing(2),
},
}))
export default function ThemeEditor() {
const settings = CatalogSettings.use()
const writeSettings = CatalogSettings.useWriteSettings()
const uploadFile = CatalogSettings.useUploadFile()
const { push } = Notifications.use()
const classes = useThemeEditorStyles({
backgroundColor: settings?.theme?.palette?.primary?.main,
})
const [editing, setEditing] = React.useState(false)
const [formKey, setFormKey] = React.useState(1)
const [removing, setRemoving] = React.useState(false)
const edit = React.useCallback(() => {
if (removing) return
setEditing(true)
}, [removing])
const cancel = React.useCallback(() => {
setEditing(false)
}, [])
const handleExited = React.useCallback(() => {
// reset the form
setFormKey(R.inc)
}, [])
const remove = React.useCallback(async () => {
if (editing || removing || (!settings?.theme && !settings?.logo)) return
// XXX: implement custom MUI Dialog-based confirm?
// eslint-disable-next-line no-restricted-globals, no-alert
if (!confirm('You are about to remove custom theme')) return
setRemoving(true)
try {
await writeSettings(FP.function.pipe(settings, R.dissoc('theme'), R.dissoc('logo')))
} catch (e) {
// eslint-disable-next-line no-console
console.warn('Error saving settings:')
// eslint-disable-next-line no-console
console.error(e)
push("Couldn't save settings, see console for details")
} finally {
setRemoving(false)
}
}, [editing, removing, settings, writeSettings, push])
const onSubmit = React.useCallback(
async (values: { logoUrl: string; primaryColor: string }) => {
try {
let logoUrl = values?.logoUrl
// TODO: check is instance of File explicitly
if (logoUrl && typeof logoUrl !== 'string') {
logoUrl = await uploadFile(logoUrl)
}
const updatedSettings = settings || {}
if (logoUrl) {
updatedSettings.logo = {
url: logoUrl,
}
}
if (values.primaryColor) {
updatedSettings.theme = {
palette: {
primary: {
main: values.primaryColor,
},
},
}
} else {
delete updatedSettings.theme
}
await writeSettings(updatedSettings)
setEditing(false)
return undefined
} catch (e) {
// eslint-disable-next-line no-console
console.warn('Error saving settings:')
// eslint-disable-next-line no-console
console.error(e)
return { [FF.FORM_ERROR]: "Couldn't save settings, see console for details" }
}
},
[settings, writeSettings, uploadFile],
)
// FIXME: remove when file upload would be ready
const useThirdPartyDomainForLogo = true
return (
<>
{settings?.theme || settings?.logo ? (
<>
<ThemePreview />
<div className={classes.actions}>
<M.Button
variant="outlined"
color="primary"
size="small"
onClick={edit}
disabled={removing}
>
Edit
</M.Button>
<M.Box pl={1} />
<M.Button color="primary" size="small" onClick={remove} disabled={removing}>
Remove
</M.Button>
{removing && <M.CircularProgress size={24} className={classes.progress} />}
</div>
</>
) : (
<>
<div className={classes.notConfigured}>Not configured</div>
<div className={classes.actions}>
<M.Button variant="outlined" color="primary" size="small" onClick={edit}>
Configure theme
</M.Button>
</div>
</>
)}
<M.Dialog open={editing} onExited={handleExited} fullWidth>
<RF.Form onSubmit={onSubmit} key={formKey}>
{({
handleSubmit,
submitting,
submitFailed,
submitError,
error,
hasValidationErrors,
}) => (
<>
<M.DialogTitle>Configure theme</M.DialogTitle>
<M.DialogContent>
<form onSubmit={handleSubmit}>
{useThirdPartyDomainForLogo ? (
<RF.Field
component={Form.Field}
initialValue={settings?.logo?.url || ''}
name="logoUrl"
label="Logo URL"
placeholder="e.g. https://example.com/path.jpg"
validate={validators.url as FF.FieldValidator<string>}
errors={{
url: 'Image should be valid url',
}}
disabled={submitting}
fullWidth
InputLabelProps={{ shrink: true }}
/>
) : (
<RF.Field
component={InputFile}
initialValue={settings?.logo?.url || ''}
name="logoUrl"
label="Logo URL"
placeholder="e.g. https://example.com/path.jpg"
validate={
validators.composeOr(
validators.file,
validators.url,
) as FF.FieldValidator<string>
}
errors={{
url: 'Image should be valid url',
file: 'Image should be file',
}}
disabled={submitting}
fullWidth
InputLabelProps={{ shrink: true }}
/>
)}
<M.Box pt={2} />
<RF.Field
// @ts-expect-error
component={InputColor}
initialValue={settings?.theme?.palette?.primary?.main || ''}
name="primaryColor"
label="Background color"
placeholder="#282b50"
validate={validators.hexColor as FF.FieldValidator<string>}
errors={{
hex: 'Enter 6-digit hex color, ex. #282b50',
}}
disabled={submitting}
fullWidth
InputLabelProps={{ shrink: true }}
/>
<input type="submit" style={{ display: 'none' }} />
</form>
</M.DialogContent>
<M.DialogActions>
{submitting ? (
<SubmitSpinner />
) : (
(!!error || !!submitError) && (
<M.Box flexGrow={1} display="flex" alignItems="center" pl={2}>
<M.Icon color="error">error_outline</M.Icon>
<M.Box pl={1} />
<M.Typography variant="body2" color="error">
{error || submitError}
</M.Typography>
</M.Box>
)
)}
<M.Button onClick={cancel} disabled={submitting}>
Cancel
</M.Button>
<M.Button
type="submit"
onClick={handleSubmit}
variant="contained"
color="primary"
disabled={submitting || (submitFailed && hasValidationErrors)}
>
Save
</M.Button>
</M.DialogActions>
</>
)}
</RF.Form>
</M.Dialog>
</>
)
} | the_stack |
import child_process from "child_process";
import eris from "eris";
import debounce from "lodash.debounce";
import path from "path";
import {
addMessageReactions,
movePlayersToSilenceChannel,
movePlayersToTalkingChannel,
mutePlayerInChannels,
unmutePlayerInChannels,
updateMessage,
updateMessageWithError,
updateMessageWithSessionOver,
} from "./actions";
import {
EMOTE_IDS_TO_COLOR,
GROUPING_TOGGLE_EMOJI,
LEAVE_EMOJI,
SERVER_IPS,
SessionState,
SHORT_REGION_NAMES,
} from "./constants";
import { orm } from "./database";
import AmongUsSession from "./database/among-us-session";
import PlayerLink from "./database/player-link";
import SessionChannel, { SessionChannelType } from "./database/session-channel";
const WORKING_DIR = path.resolve(process.env.AU_CLIENT_DIR!);
const CLIENT = path.join(WORKING_DIR, process.platform === "win32" ? "client.exe" : "client");
/**
* Incomplete definition of the player data outputted by the client.
*/
export interface PlayerData {
clientId: number;
name: string;
color: number;
statusBitField: number;
tasks: unknown[];
}
export const enum PlayerDataFlags {
DISCONNECTED = 1,
IMPOSTOR = 2,
DEAD = 4,
}
/**
* Class that handles all communication with the AU client in C#, using
* JSON messages passed over the standard out to receive data from the client.
*/
class SessionRunner {
private process: child_process.ChildProcess;
private playerData: PlayerData[] = [];
private deadPlayers = new Set<number>(); // clientIds of dead players
private mutedPlayers = new Set<string>(); // snowflakes of muted players
private isConnected = false;
private isDestroyed = false;
constructor(private bot: eris.Client, private session: AmongUsSession) {}
/**
* Starts this session, launching the client and attempting to connect to
* the relevant lobby, as configured in the session.
*/
public async start() {
this.process = child_process.spawn(CLIENT, [SERVER_IPS[this.session.region], this.session.lobbyCode], {
cwd: WORKING_DIR,
});
// Kill the process if it doesn't do anything after 30 seconds.
setTimeout(() => {
if (this.isConnected || this.isDestroyed) return;
this.process.kill("SIGTERM");
this.handleError(
"It took too long to connect to the Among Us services. This is likely due to server load issues. Try again in a bit."
);
}, 30 * 1000);
let buffered = "";
this.process.stdout!.setEncoding("utf-8");
this.process.stdout!.on("data", data => {
for (const c of data) {
buffered += c;
if (c === "\n") {
this.handleClientStdout(buffered.trim());
buffered = "";
}
}
});
this.process.stdout!.on("close", () => this.handleDisconnect());
this.process.stderr!.setEncoding("utf-8");
this.process.stderr!.on("data", console.log);
}
/**
* Invoked by listeners when the user reacts to the message with the specified
* emoji id. It is already verified that emojiId is a valid color reaction.
*/
public async handleEmojiSelection(emojiId: string, userId: string) {
if (this.isDestroyed) return;
if (emojiId === GROUPING_TOGGLE_EMOJI.split(":")[1]) {
await this.toggleImpostorGrouping(userId);
return;
}
if (emojiId === LEAVE_EMOJI.split(":")[1]) {
await this.leaveLobby(userId);
return;
}
const selectedColor = EMOTE_IDS_TO_COLOR[emojiId];
if (selectedColor === undefined) return;
await this.session.links.init();
const relevantPlayer = this.playerData.find(x => x.color === selectedColor);
if (!relevantPlayer) return;
// Check if they had a different color selected, and remove if that was the case.
const oldMatching = this.session.links.getItems().find(x => x.snowflake === userId);
if (oldMatching) {
await this.session.links.remove(oldMatching);
}
// if the old matching had the same client id, this is a re-react to remove the link.
// if they don't match, add the link
if (!oldMatching || oldMatching.clientId !== "" + relevantPlayer.clientId) {
await this.session.links.add(new PlayerLink("" + relevantPlayer.clientId, userId));
}
await orm.em.flush();
await this.updateMessage();
// If this user already died, retroactively apply the mute.
if (this.deadPlayers.has(relevantPlayer.clientId)) {
this.mutePlayer(relevantPlayer.clientId).catch(() => {});
}
}
/**
* @returns whether the specified clientid is an impostor
*/
public isImpostor(clientId: string): boolean {
return this.playerData.some(
x => "" + x.clientId === clientId && (x.statusBitField & PlayerDataFlags.IMPOSTOR) !== 0
);
}
/**
* Handles the usage of the leave react by any user.
*/
private async leaveLobby(userId: string) {
if (!this.isConnected || userId !== this.session.creator) return;
this.process.kill("SIGINT"); // will trigger a disconnect
}
/**
* Handles the usage of the toggle impostor grouping react by any user.
*/
private async toggleImpostorGrouping(userId: string) {
if (userId !== this.session.creator || this.session.state !== SessionState.LOBBY) {
return;
}
this.session.groupImpostors = !this.session.groupImpostors;
await orm.em.persistAndFlush(this.session);
await this.updateMessage();
console.log(`[+] Set impostor grouping to ${this.session.groupImpostors} for session ${this.session.id}`);
// Create the impostor channel if needed.
if (this.session.groupImpostors) {
await this.session.channels.init();
if (this.session.channels.getItems().some(x => x.type === SessionChannelType.IMPOSTORS)) return;
const categoryChannel = this.session.channels.getItems().find(x => x.type === SessionChannelType.CATEGORY)!;
const impostorChannel = await this.bot.createChannel(this.session.guild, "Impostors", 2, {
parentID: categoryChannel.channelId,
permissionOverwrites: [
{
type: "role",
id: this.session.guild,
deny: eris.Constants.Permissions.readMessages,
allow: 0,
},
],
});
this.session.channels.add(new SessionChannel(impostorChannel.id, SessionChannelType.IMPOSTORS));
await orm.em.persistAndFlush(this.session);
}
}
/**
* Invoked when the client disconnects, such as when the lobby closes.
* Should handle removal of the session and channels.
*/
private async handleDisconnect() {
if (!this.isConnected) return;
this.isConnected = false;
console.log(`[+] Session ${this.session.id} disconnected from Among Us`);
await this.session.channels.init();
for (const channel of this.session.channels) {
await this.bot.deleteChannel(channel.channelId, "Among Us: Session is over.").catch(() => {});
}
await updateMessageWithSessionOver(this.bot, this.session);
await orm.em.removeAndFlush(this.session);
sessions.delete(this.session.id);
this.isDestroyed = true;
}
/**
* Invoked when the client encounters an error during startup. This
* does not need to handle removal of channels, as they aren't created
* yet.
*/
private async handleError(error: string) {
if (this.isDestroyed) return;
console.log(`[+] Session ${this.session.id} encountered an error: '${error}'`);
await updateMessageWithError(this.bot, this.session, error);
await orm.em.removeAndFlush(this.session);
this.isDestroyed = true;
sessions.delete(this.session.id);
}
/**
* Invoked when the client successfully joins the lobby indicated in the
* current session. Creates the relevant voice channels and updates the state.
*/
private async handleConnect() {
if (this.isConnected || this.isDestroyed) return;
console.log(`[+] Session ${this.session.id} connected to lobby.`);
const category = await this.bot.createChannel(
this.session.guild,
"Among Us - " + SHORT_REGION_NAMES[this.session.region] + " - " + this.session.lobbyCode,
4,
"Among Us: Create category for voice channels."
);
this.session.channels.add(new SessionChannel(category.id, SessionChannelType.CATEGORY));
const talkingChannel = await this.bot.createChannel(this.session.guild, "Discussion", 2, {
parentID: category.id,
});
const talkingInvite = await talkingChannel.createInvite({
unique: true,
});
this.session.channels.add(
new SessionChannel(talkingChannel.id, SessionChannelType.TALKING, talkingInvite.code)
);
const mutedChannel = await this.bot.createChannel(this.session.guild, "Muted", 2, {
parentID: category.id,
permissionOverwrites: [
{
type: "role",
id: this.session.guild,
deny: eris.Constants.Permissions.voiceSpeak,
allow: 0,
},
],
});
this.session.channels.add(new SessionChannel(mutedChannel.id, SessionChannelType.SILENCE));
this.isConnected = true;
await orm.em.persistAndFlush(this.session);
await Promise.all([this.setStateTo(SessionState.LOBBY), addMessageReactions(this.bot, this.session)]);
}
/**
* Simple method that changes the current state of the lobby to the specified
* state, then ensures that the chat message is updated to reflect this state.
*/
private async setStateTo(state: SessionState) {
if (this.isDestroyed) return;
this.session.state = state;
await orm.em.flush();
await this.updateMessage();
}
/**
* Processes a game data update from the client, updating the message where
* appropriate.
*/
private async handlePlayerDataUpdate(newData: PlayerData[]) {
const oldByClientId = new Map(this.playerData.map(x => [x.clientId, x]));
const newByClientId = new Map(newData.map(x => [x.clientId, x]));
let shouldUpdateMessage = oldByClientId.size !== newByClientId.size;
for (const [oldId, oldData] of oldByClientId) {
const newData = newByClientId.get(oldId);
if (!newData || oldData.name !== newData.name || oldData.color !== newData.color)
shouldUpdateMessage = true;
}
for (const [newId, newData] of newByClientId) {
if ((newData.statusBitField & PlayerDataFlags.DEAD) !== 0 && !this.deadPlayers.has(newId)) {
this.deadPlayers.add(newId);
this.mutePlayer(newId).catch(() => {});
}
}
this.playerData = newData;
if (shouldUpdateMessage && this.isConnected) {
await this.debouncedUpdateMessage();
}
// if we're in lobby but everyone has tasks now, we've started
if (this.session.state === SessionState.LOBBY && !this.playerData.some(x => !x.tasks || !x.tasks.length)) {
await this.setStateTo(SessionState.PLAYING);
await movePlayersToSilenceChannel(this.bot, this.session);
}
}
/**
* Updates the message for the current state of the lobby.
*/
private async updateMessage() {
await updateMessage(this.bot, this.session, this.playerData);
}
/**
* Version of {@link updateMessage} that will debounce to ensure that
* updates are not pushed too frequently.
*/
private debouncedUpdateMessage = debounce(() => this.updateMessage(), 200);
/**
* Mutes the specified player in the talking channel because they died,
* if they had linked their among us character with their discord.
*/
private async mutePlayer(clientId: number) {
await this.session.links.init();
await this.session.channels.init();
const links = this.session.links.getItems().filter(x => x.clientId === "" + clientId);
for (const link of links) {
this.mutedPlayers.add(link.snowflake);
await mutePlayerInChannels(this.bot, this.session, link.snowflake);
}
}
/**
* Unmutes all players in the main channel that were previously muted.
*/
private async unmutePlayers() {
await Promise.all([...this.mutedPlayers].map(x => unmutePlayerInChannels(this.bot, this.session, x)));
this.mutedPlayers.clear();
}
/**
* Receives and handles output from the client, parsing the result into
* a JSON message and then dispatching the result of that message.
*/
private handleClientStdout = async (msg: string) => {
if (this.isDestroyed) return;
msg = msg.trim();
if (!msg.length) return;
const { type, ...rest } = JSON.parse(msg);
if (type === "connect") {
await this.handleConnect();
}
if (type === "gameEnd") {
console.log(`[+] Session ${this.session.id}: game ended`);
await this.setStateTo(SessionState.LOBBY);
await this.unmutePlayers();
await movePlayersToTalkingChannel(this.bot, this.session);
}
if (type === "talkingStart") {
console.log(`[+] Session ${this.session.id}: talking started`);
await this.setStateTo(SessionState.DISCUSSING);
await movePlayersToTalkingChannel(this.bot, this.session);
}
if (type === "talkingEnd") {
console.log(`[+] Session ${this.session.id}: talking ended`);
if (this.session.state === SessionState.LOBBY) {
// Don't transition until we have all the impostor information.
return;
}
await this.setStateTo(SessionState.PLAYING);
await movePlayersToSilenceChannel(this.bot, this.session);
}
if (type === "disconnect") {
await this.handleDisconnect();
}
if (type === "gameData") {
await this.handlePlayerDataUpdate(rest.data);
}
if (type === "error") {
await this.handleError(rest.message);
}
};
}
const sessions = new Map<number, SessionRunner>();
/**
* Returns the current session runner for the specified session, or null
* if it does not exist.
*/
export function getRunnerForSession(session: AmongUsSession): SessionRunner | null {
return sessions.get(session.id) || null;
}
/**
* Creates a new client instance for the specified AmongUsSession, causing
* it to connect to the lobby and handle events. This method should never
* directly throw.
*/
export default async function startSession(bot: eris.Client, session: AmongUsSession) {
const runner = new SessionRunner(bot, session);
sessions.set(session.id, runner);
await runner.start();
} | the_stack |
import {
AbstractControl,
FormArray,
FormBuilder,
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators
} from '@angular/forms';
import { Component } from '@angular/core';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { ComponentTester, speculoosMatchers } from 'ngx-speculoos';
import { ValdemortModule } from './valdemort.module';
import { ValdemortConfig, DisplayMode } from './valdemort-config.service';
function matchValidator(group: AbstractControl) {
return group.get('password')!.value === group.get('confirmation')!.value ? null : { match: true };
}
@Component({
selector: 'val-reactive-test',
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<input formControlName="firstName" id="firstName" />
<val-errors id="firstNameErrors" controlName="firstName" label="The first name">
<ng-template valError="required" let-label>{{ label }} is required</ng-template>
</val-errors>
<input formControlName="lastName" id="lastName" />
<val-errors id="lastNameErrors" controlName="lastName">
<ng-template valError="minlength" let-error="error">min length: {{ error.requiredLength }}</ng-template>
<ng-template valError="pattern">only letters</ng-template>
</val-errors>
<input formControlName="age" type="number" id="age" />
<val-errors id="ageErrors" [control]="form.get('age')">
<ng-template valError="required">age required</ng-template>
</val-errors>
<div formGroupName="credentials">
<input formControlName="password" id="password" />
<val-errors id="passwordErrors" controlName="password">
<ng-template valError="required">password is required</ng-template>
</val-errors>
<input formControlName="confirmation" />
<val-errors id="confirmationErrors" controlName="confirmation">
<ng-template valError="required">confirmation is required</ng-template>
</val-errors>
</div>
<val-errors id="credentialsControlNameErrors" controlName="credentials">
<ng-template valError="match">match with controlName error</ng-template>
</val-errors>
<val-errors id="credentialsControlErrors" [control]="form.get('credentials')">
<ng-template valError="match">match with control error</ng-template>
</val-errors>
<div formArrayName="hobbies">
<div *ngFor="let hobbyCtrl of hobbies.controls; index as i">
<input [formControlName]="i" />
<val-errors [controlName]="i" id="hobbyErrors">
<ng-template valError="required">each hobby required</ng-template>
</val-errors>
</div>
</div>
<input formControlName="email" id="email" />
<val-errors id="emailErrors" controlName="email" label="The email">
<ng-template valError="email">email must be a valid email address</ng-template>
<ng-template valFallback let-label let-type="type">{{ label }} has an unhandled error of type {{ type }}</ng-template>
</val-errors>
<button id="submit">Submit</button>
</form>
`
})
class ReactiveTestComponent {
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
firstName: ['', Validators.required],
lastName: ['', [Validators.minLength(2), Validators.pattern(/^[a-z]*$/)]],
age: [null, [Validators.required, Validators.min(1)]],
credentials: fb.group(
{
password: ['', Validators.required],
confirmation: ['', Validators.required]
},
{
validators: matchValidator
}
),
hobbies: fb.array([['', Validators.required]]),
email: ['', [Validators.email, Validators.maxLength(10), Validators.pattern(/^[a-z.@]*$/)]]
});
}
get hobbies() {
return this.form.get('hobbies') as FormArray;
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
submit() {}
}
class ReactiveComponentTester extends ComponentTester<ReactiveTestComponent> {
constructor() {
super(ReactiveTestComponent);
}
get firstName() {
return this.input('#firstName')!;
}
get firstNameErrors() {
return this.element('#firstNameErrors')!;
}
get lastName() {
return this.input('#lastName')!;
}
get lastNameErrors() {
return this.element('#lastNameErrors')!;
}
get age() {
return this.input('#age')!;
}
get ageErrors() {
return this.element('#ageErrors')!;
}
get password() {
return this.input('#password')!;
}
get passwordErrors() {
return this.element('#passwordErrors')!;
}
get hobbyErrors() {
return this.element('#hobbyErrors')!;
}
get credentialsControlNameErrors() {
return this.element('#credentialsControlNameErrors')!;
}
get credentialsControlErrors() {
return this.element('#credentialsControlErrors')!;
}
get email() {
return this.input('#email')!;
}
get emailErrors() {
return this.element('#emailErrors')!;
}
get submit() {
return this.button('#submit')!;
}
}
@Component({
selector: 'val-standalone-test',
template: `
<input [formControl]="foo" id="foo" />
<val-errors [control]="foo" id="fooErrors">
<ng-template valError="required">foo required</ng-template>
</val-errors>
<input [(ngModel)]="bar" #barCtrl="ngModel" id="bar" required />
<val-errors [control]="barCtrl.control" id="barErrors">
<ng-template valError="required">bar required</ng-template>
</val-errors>
`
})
class StandaloneTestComponent {
foo = new FormControl('', Validators.required);
bar = '';
}
class StandaloneComponentTester extends ComponentTester<StandaloneTestComponent> {
constructor() {
super(StandaloneTestComponent);
}
get foo() {
return this.input('#foo')!;
}
get fooErrors() {
return this.element('#fooErrors')!;
}
get bar() {
return this.input('#bar')!;
}
get barErrors() {
return this.element('#barErrors')!;
}
}
@Component({
selector: 'val-template-driven-test',
template: `
<form (ngSubmit)="submit()">
<input id="firstName" name="firstName" [(ngModel)]="user.firstName" #firstNameCtrl="ngModel" required />
<val-errors [control]="firstNameCtrl.control" id="firstNameErrors">
<ng-template valError="required">first name required</ng-template>
</val-errors>
<input id="lastName" name="lastName" [(ngModel)]="user.lastName" required />
<val-errors controlName="lastName" id="lastNameErrors">
<ng-template valError="required">last name required</ng-template>
</val-errors>
<div ngModelGroup="credentials">
<input id="password" name="password" [(ngModel)]="user.credentials.password" required />
<val-errors controlName="password" id="passwordErrors">
<ng-template valError="required">password required</ng-template>
</val-errors>
</div>
<button id="submit">Submit</button>
</form>
`
})
class TemplateDrivenTestComponent {
user = {
firstName: '',
lastName: '',
credentials: {
password: ''
}
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
submit() {}
}
class TemplateDrivenComponentTester extends ComponentTester<TemplateDrivenTestComponent> {
constructor() {
super(TemplateDrivenTestComponent);
}
get firstNameErrors() {
return this.element('#firstNameErrors')!;
}
get lastNameErrors() {
return this.element('#lastNameErrors')!;
}
get password() {
return this.input('#password')!;
}
get passwordErrors() {
return this.element('#passwordErrors')!;
}
get submit() {
return this.button('#submit')!;
}
}
@Component({
selector: 'val-wrong-control-name-test',
template: `
<form (ngSubmit)="submit()">
<input id="firstName" name="firstName" [(ngModel)]="user.firstName" #firstNameCtrl="ngModel" required />
<!-- the control name mentions lastName whereas the control is firstName -->
<val-errors controlName="lastName" id="firstNameErrors">
<ng-template valError="required">first name required</ng-template>
</val-errors>
<button id="submit">Submit</button>
</form>
`
})
class WrongControlNameTestComponent {
user = {
firstName: ''
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
submit() {}
}
class WrongControlNameComponentTester extends ComponentTester<WrongControlNameTestComponent> {
constructor() {
super(WrongControlNameTestComponent);
}
get firstName() {
return this.input('#firstName');
}
get firstNameErrors() {
return this.element('#firstNameErrors');
}
get submit() {
return this.button('#submit');
}
}
describe('ValidationErrorsComponent', () => {
beforeEach(() => jasmine.addMatchers(speculoosMatchers));
describe('reactive forms', () => {
let tester: ReactiveComponentTester;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, ValdemortModule],
declarations: [ReactiveTestComponent]
});
tester = new ReactiveComponentTester();
tester.detectChanges();
});
it('should not display errors while not submitted nor touched', () => {
expect(tester.firstNameErrors.attr('style')).toBe('display: none;');
expect(window.getComputedStyle(tester.firstNameErrors.nativeElement).display).toBe('none');
expect(tester.firstNameErrors.elements('div').length).toBe(0);
expect(tester.elements('val-errors div').length).toBe(0);
});
it('should display errors once submitted', () => {
tester.submit.click();
expect(tester.firstNameErrors.attr('style')).toBeFalsy();
expect(window.getComputedStyle(tester.firstNameErrors.nativeElement).display).not.toBe('none');
expect(tester.firstNameErrors.elements('div').length).toBe(1);
});
it('should display errors once touched', () => {
tester.firstName.dispatchEventOfType('blur');
expect(tester.firstNameErrors.attr('style')).toBeFalsy();
expect(window.getComputedStyle(tester.firstNameErrors.nativeElement).display).not.toBe('none');
expect(tester.firstNameErrors.elements('div').length).toBe(1);
});
it('should not display errors if no error template present', () => {
tester.age.fillWith('0');
tester.submit.click();
expect(tester.componentInstance.form.get('age')!.invalid).toBe(true);
expect(window.getComputedStyle(tester.ageErrors.nativeElement).display).toBe('none');
expect(tester.ageErrors.elements('div').length).toBe(0);
});
it('should remove error if no error', () => {
tester.submit.click();
tester.firstName.fillWith('JB');
expect(tester.firstNameErrors.elements('div').length).toBe(0);
});
it('should honor the label', () => {
tester.submit.click();
expect(tester.firstNameErrors).toContainText('The first name is required');
});
it('should expose the error', () => {
tester.lastName.fillWith('a');
tester.lastName.dispatchEventOfType('blur');
expect(tester.lastNameErrors).toContainText('min length: 2');
});
it('should display all errors in order', () => {
tester.lastName.fillWith('1');
tester.lastName.dispatchEventOfType('blur');
expect(tester.lastNameErrors.elements('div').length).toBe(2);
expect(tester.lastNameErrors.elements('div')[0]).toContainText('min length: 2');
expect(tester.lastNameErrors.elements('div')[1]).toContainText('only letters');
});
it('should allow passing a control rather than a control name', () => {
tester.submit.click();
expect(tester.ageErrors).toContainText('age required');
});
it('should validate controls inside a nested form group', () => {
tester.submit.click();
expect(tester.passwordErrors).toContainText('password is required');
});
it('should validate controls inside a nested form array', () => {
tester.submit.click();
expect(tester.hobbyErrors).toContainText('each hobby required');
});
it('should validate a form group identified by controlName', () => {
tester.password.fillWith('a');
tester.submit.click();
expect(tester.credentialsControlNameErrors).toContainText('match with controlName error');
});
it('should validate a form group identified by control', () => {
tester.password.fillWith('a');
tester.submit.click();
expect(tester.credentialsControlErrors).toContainText('match with control error');
});
it('should display fallback errors', () => {
tester.email.fillWith('long invalid email with 1234');
tester.submit.click();
expect(tester.emailErrors.elements('div').length).toBe(3);
expect(tester.emailErrors.elements('div')[0]).toContainText('email must be a valid email address');
expect(tester.emailErrors).toContainText('The email has an unhandled error of type maxlength');
expect(tester.emailErrors).toContainText('The email has an unhandled error of type pattern');
});
});
describe('standalone controls', () => {
let tester: StandaloneComponentTester;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule, ValdemortModule],
declarations: [StandaloneTestComponent]
});
tester = new StandaloneComponentTester();
tester.detectChanges();
});
it('should validate standalone reactive control', () => {
expect(tester.fooErrors).not.toContainText('foo required');
tester.foo.dispatchEventOfType('blur');
expect(tester.fooErrors).toContainText('foo required');
});
it('should validate standalone template-driven control', () => {
expect(tester.barErrors).not.toContainText('bar required');
tester.bar.dispatchEventOfType('blur');
expect(tester.barErrors).toContainText('bar required');
});
});
describe('template-driven forms', () => {
let tester: TemplateDrivenComponentTester;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [FormsModule, ValdemortModule],
declarations: [TemplateDrivenTestComponent]
});
tester = new TemplateDrivenComponentTester();
tick();
tester.detectChanges();
}));
it('should validate top-level field with control', () => {
expect(tester.firstNameErrors).not.toContainText('first name required');
tester.submit.click();
expect(tester.firstNameErrors).toContainText('first name required');
});
it('should validate top-level field with controlName', () => {
expect(tester.lastNameErrors).not.toContainText('last name required');
tester.submit.click();
expect(tester.lastNameErrors).toContainText('last name required');
});
it('should validate field nested in model group', () => {
expect(tester.passwordErrors).not.toContainText('password required');
tester.submit.click();
expect(tester.passwordErrors).toContainText('password required');
});
});
describe('with wrong control name', () => {
let tester: WrongControlNameComponentTester;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [FormsModule, ValdemortModule],
declarations: [WrongControlNameTestComponent]
});
tester = new WrongControlNameComponentTester();
tick();
tester.detectChanges();
}));
it('should not throw by default', fakeAsync(() => {
expect(() => tester.detectChanges()).not.toThrowError();
expect(tester.firstNameErrors).not.toContainText('first name required');
}));
it('should throw if configured to', fakeAsync(() => {
const config = TestBed.inject(ValdemortConfig);
config.shouldThrowOnMissingControl = () => true;
expect(() => tester.detectChanges()).toThrowError(`ngx-valdemort: no control found for controlName: 'lastName'.`);
}));
});
describe('configuration', () => {
let tester: ReactiveComponentTester;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, ValdemortModule],
declarations: [ReactiveTestComponent]
});
const config = TestBed.inject(ValdemortConfig);
config.displayMode = DisplayMode.ONE;
config.errorsClasses = 'a b';
config.errorClasses = 'c d';
config.shouldDisplayErrors = control => control.dirty;
tester = new ReactiveComponentTester();
tester.detectChanges();
});
it('should display error once dirty', () => {
expect(tester.firstNameErrors).not.toContainText('The first name is required');
tester.firstName.fillWith('a');
tester.firstName.fillWith('');
expect(tester.firstNameErrors).toContainText('The first name is required');
});
it('should display the first error only', () => {
tester.lastName.fillWith('1');
expect(tester.lastNameErrors.elements('div').length).toBe(1);
expect(tester.lastNameErrors).toContainText('min length: 2');
});
it('should display the first error in case of fallback', () => {
tester.email.fillWith('long email with 1234');
expect(tester.emailErrors.elements('div').length).toBe(1);
expect(tester.emailErrors).toContainText('email must be a valid email address');
tester.email.fillWith('long-rejected-email@mail.com');
expect(tester.emailErrors.elements('div').length).toBe(1);
expect(tester.emailErrors).toContainText('The email has an unhandled error of type');
});
it('should add CSS classes to the errors component', () => {
tester.lastName.fillWith('1');
expect(tester.lastNameErrors).toHaveClass('a');
expect(tester.lastNameErrors).toHaveClass('b');
});
it('should add CSS classes to the error divs', () => {
tester.lastName.fillWith('1');
expect(tester.lastNameErrors.element('div.c')).not.toBeNull();
expect(tester.lastNameErrors.element('div.d')).not.toBeNull();
});
});
}); | the_stack |
* Hyperledger Cactus Plugin - HTLC Coordinator
* Can exchange assets between networks
*
* The version of the OpenAPI document: 0.0.1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Configuration } from './configuration';
import globalAxios, { AxiosPromise, AxiosInstance } from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base';
/**
*
* @export
* @interface CounterpartyHTLCRequest
*/
export interface CounterpartyHTLCRequest {
/**
*
* @type {HtlcPackage}
* @memberof CounterpartyHTLCRequest
*/
htlcPackage: HtlcPackage;
/**
* connector Instance Id for the connector plugin
* @type {string}
* @memberof CounterpartyHTLCRequest
*/
connectorInstanceId: string;
/**
* keychainId for the keychain plugin
* @type {string}
* @memberof CounterpartyHTLCRequest
*/
keychainId: string;
/**
* Id for the HTLC
* @type {string}
* @memberof CounterpartyHTLCRequest
*/
htlcId: string;
/**
*
* @type {Web3SigningCredential}
* @memberof CounterpartyHTLCRequest
*/
web3SigningCredential: Web3SigningCredential;
/**
*
* @type {number}
* @memberof CounterpartyHTLCRequest
*/
gas?: number;
}
/**
*
* @export
* @enum {string}
*/
export enum HtlcPackage {
Besu = 'BESU',
BesuErc20 = 'BESU_ERC20'
}
/**
*
* @export
* @interface OwnHTLCRequest
*/
export interface OwnHTLCRequest {
/**
*
* @type {HtlcPackage}
* @memberof OwnHTLCRequest
*/
htlcPackage: HtlcPackage;
/**
* connector Instance Id for the connector plugin
* @type {string}
* @memberof OwnHTLCRequest
*/
connectorInstanceId: string;
/**
* keychainId for the keychain plugin
* @type {string}
* @memberof OwnHTLCRequest
*/
keychainId: string;
/**
*
* @type {Array<any>}
* @memberof OwnHTLCRequest
*/
constructorArgs: Array<any>;
/**
*
* @type {Web3SigningCredential}
* @memberof OwnHTLCRequest
*/
web3SigningCredential: Web3SigningCredential;
/**
* Input amount to lock
* @type {number}
* @memberof OwnHTLCRequest
*/
inputAmount: number;
/**
* Output amount to lock
* @type {number}
* @memberof OwnHTLCRequest
*/
outputAmount: number;
/**
* Timestamp to expire the contract
* @type {number}
* @memberof OwnHTLCRequest
*/
expiration: number;
/**
* Hashlock needed to refund the amount
* @type {string}
* @memberof OwnHTLCRequest
*/
hashLock: string;
/**
* The token address
* @type {string}
* @memberof OwnHTLCRequest
*/
tokenAddress: string;
/**
* The receiver address
* @type {string}
* @memberof OwnHTLCRequest
*/
receiver: string;
/**
* The output network id
* @type {string}
* @memberof OwnHTLCRequest
*/
outputNetwork: string;
/**
* The output addreess to receive the tokens
* @type {string}
* @memberof OwnHTLCRequest
*/
outputAddress: string;
/**
*
* @type {number}
* @memberof OwnHTLCRequest
*/
gas?: number;
}
/**
* @type Web3SigningCredential
* @export
*/
export type Web3SigningCredential = Web3SigningCredentialCactusKeychainRef | Web3SigningCredentialNone | Web3SigningCredentialPrivateKeyHex;
/**
*
* @export
* @interface Web3SigningCredentialCactusKeychainRef
*/
export interface Web3SigningCredentialCactusKeychainRef {
/**
*
* @type {Web3SigningCredentialType}
* @memberof Web3SigningCredentialCactusKeychainRef
*/
type: Web3SigningCredentialType;
/**
* The ethereum account (public key) that the credential belongs to. Basically the username in the traditional terminology of authentication.
* @type {string}
* @memberof Web3SigningCredentialCactusKeychainRef
*/
ethAccount: string;
/**
* The key to use when looking up the the keychain entry holding the secret pointed to by the keychainEntryKey parameter.
* @type {string}
* @memberof Web3SigningCredentialCactusKeychainRef
*/
keychainEntryKey: string;
/**
* The keychain ID to use when looking up the the keychain plugin instance that will be used to retrieve the secret pointed to by the keychainEntryKey parameter.
* @type {string}
* @memberof Web3SigningCredentialCactusKeychainRef
*/
keychainId: string;
}
/**
* Using this denotes that there is no signing required because the transaction is pre-signed.
* @export
* @interface Web3SigningCredentialNone
*/
export interface Web3SigningCredentialNone {
/**
*
* @type {Web3SigningCredentialType}
* @memberof Web3SigningCredentialNone
*/
type: Web3SigningCredentialType;
}
/**
*
* @export
* @interface Web3SigningCredentialPrivateKeyHex
*/
export interface Web3SigningCredentialPrivateKeyHex {
/**
*
* @type {Web3SigningCredentialType}
* @memberof Web3SigningCredentialPrivateKeyHex
*/
type: Web3SigningCredentialType;
/**
* The ethereum account (public key) that the credential belongs to. Basically the username in the traditional terminology of authentication.
* @type {string}
* @memberof Web3SigningCredentialPrivateKeyHex
*/
ethAccount: string;
/**
* The HEX encoded private key of an eth account.
* @type {string}
* @memberof Web3SigningCredentialPrivateKeyHex
*/
secret: string;
}
/**
*
* @export
* @enum {string}
*/
export enum Web3SigningCredentialType {
CactusKeychainRef = 'CACTUS_KEYCHAIN_REF',
GethKeychainPassword = 'GETH_KEYCHAIN_PASSWORD',
PrivateKeyHex = 'PRIVATE_KEY_HEX',
None = 'NONE'
}
/**
*
* @export
* @interface WithdrawCounterpartyRequest
*/
export interface WithdrawCounterpartyRequest {
/**
*
* @type {HtlcPackage}
* @memberof WithdrawCounterpartyRequest
*/
htlcPackage: HtlcPackage;
/**
* connector Instance Id for the connector plugin
* @type {string}
* @memberof WithdrawCounterpartyRequest
*/
connectorInstanceId: string;
/**
* keychainId for the keychain plugin
* @type {string}
* @memberof WithdrawCounterpartyRequest
*/
keychainId: string;
/**
* contractId for the contract
* @type {string}
* @memberof WithdrawCounterpartyRequest
*/
contractId?: string;
/**
*
* @type {Web3SigningCredential}
* @memberof WithdrawCounterpartyRequest
*/
web3SigningCredential: Web3SigningCredential;
/**
* Id for the HTLC
* @type {string}
* @memberof WithdrawCounterpartyRequest
*/
htlcId: string;
/**
* Counterparty HTLC secret
* @type {string}
* @memberof WithdrawCounterpartyRequest
*/
secret: string;
/**
*
* @type {number}
* @memberof WithdrawCounterpartyRequest
*/
gas?: number;
}
/**
* DefaultApi - axios parameter creator
* @export
*/
export const DefaultApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Create an instance to interact with the counterparty HTLC
* @param {CounterpartyHTLCRequest} [counterpartyHTLCRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
counterpartyHtlcV1: async (counterpartyHTLCRequest?: CounterpartyHTLCRequest, options: any = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-htlc-coordinator-besu/counterparty-htlc`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter, options.query);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(counterpartyHTLCRequest, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Create an instance to interact with the own HTLC.
* @param {OwnHTLCRequest} [ownHTLCRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
ownHtlcV1: async (ownHTLCRequest?: OwnHTLCRequest, options: any = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-htlc-coordinator-besu/own-htlc`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter, options.query);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(ownHTLCRequest, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Withdraw funds of the counterparty HTLC
* @param {WithdrawCounterpartyRequest} [withdrawCounterpartyRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
withdrawCounterpartyV1: async (withdrawCounterpartyRequest?: WithdrawCounterpartyRequest, options: any = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-htlc-coordinator-besu/withdraw-counterparty`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter, options.query);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(withdrawCounterpartyRequest, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* DefaultApi - functional programming interface
* @export
*/
export const DefaultApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = DefaultApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Create an instance to interact with the counterparty HTLC
* @param {CounterpartyHTLCRequest} [counterpartyHTLCRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async counterpartyHtlcV1(counterpartyHTLCRequest?: CounterpartyHTLCRequest, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.counterpartyHtlcV1(counterpartyHTLCRequest, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Create an instance to interact with the own HTLC.
* @param {OwnHTLCRequest} [ownHTLCRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async ownHtlcV1(ownHTLCRequest?: OwnHTLCRequest, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.ownHtlcV1(ownHTLCRequest, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Withdraw funds of the counterparty HTLC
* @param {WithdrawCounterpartyRequest} [withdrawCounterpartyRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async withdrawCounterpartyV1(withdrawCounterpartyRequest?: WithdrawCounterpartyRequest, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.withdrawCounterpartyV1(withdrawCounterpartyRequest, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* DefaultApi - factory interface
* @export
*/
export const DefaultApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = DefaultApiFp(configuration)
return {
/**
*
* @summary Create an instance to interact with the counterparty HTLC
* @param {CounterpartyHTLCRequest} [counterpartyHTLCRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
counterpartyHtlcV1(counterpartyHTLCRequest?: CounterpartyHTLCRequest, options?: any): AxiosPromise<any> {
return localVarFp.counterpartyHtlcV1(counterpartyHTLCRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Create an instance to interact with the own HTLC.
* @param {OwnHTLCRequest} [ownHTLCRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
ownHtlcV1(ownHTLCRequest?: OwnHTLCRequest, options?: any): AxiosPromise<any> {
return localVarFp.ownHtlcV1(ownHTLCRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Withdraw funds of the counterparty HTLC
* @param {WithdrawCounterpartyRequest} [withdrawCounterpartyRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
withdrawCounterpartyV1(withdrawCounterpartyRequest?: WithdrawCounterpartyRequest, options?: any): AxiosPromise<any> {
return localVarFp.withdrawCounterpartyV1(withdrawCounterpartyRequest, options).then((request) => request(axios, basePath));
},
};
};
/**
* DefaultApi - object-oriented interface
* @export
* @class DefaultApi
* @extends {BaseAPI}
*/
export class DefaultApi extends BaseAPI {
/**
*
* @summary Create an instance to interact with the counterparty HTLC
* @param {CounterpartyHTLCRequest} [counterpartyHTLCRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DefaultApi
*/
public counterpartyHtlcV1(counterpartyHTLCRequest?: CounterpartyHTLCRequest, options?: any) {
return DefaultApiFp(this.configuration).counterpartyHtlcV1(counterpartyHTLCRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Create an instance to interact with the own HTLC.
* @param {OwnHTLCRequest} [ownHTLCRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DefaultApi
*/
public ownHtlcV1(ownHTLCRequest?: OwnHTLCRequest, options?: any) {
return DefaultApiFp(this.configuration).ownHtlcV1(ownHTLCRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Withdraw funds of the counterparty HTLC
* @param {WithdrawCounterpartyRequest} [withdrawCounterpartyRequest]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DefaultApi
*/
public withdrawCounterpartyV1(withdrawCounterpartyRequest?: WithdrawCounterpartyRequest, options?: any) {
return DefaultApiFp(this.configuration).withdrawCounterpartyV1(withdrawCounterpartyRequest, options).then((request) => request(this.axios, this.basePath));
}
} | the_stack |
import { configure } from "mobx";
import { types, getSnapshot } from "mobx-state-tree";
import { Source, Form, converters, Field, RepeatingForm } from "../src";
import { resolveReactions } from "./utils";
// "always" leads to trouble during initialization.
configure({ enforceActions: "observed" });
function refSnapshots(refs: any[] | undefined): any[] {
if (refs === undefined) {
throw new Error("Did not expect undefined refs");
}
return refs.map((ref) => getSnapshot(ref));
}
test("source", async () => {
const Item = types
.model("Item", {
id: types.identifierNumber,
text: types.string,
feature: types.string,
})
.views((self) => ({
get displayText() {
return "Display " + self.text;
},
}));
const Container = types.model("Container", {
entryMap: types.map(Item),
});
const container = Container.create({ entryMap: {} });
const data = [
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
{ id: 3, text: "C", feature: "y" },
];
const loadHit: string[] = [];
const load = async ({ feature }: { feature: string }) => {
loadHit.push(feature);
return data.filter((entry) => entry.feature === feature);
};
const source = new Source({
entryMap: container.entryMap,
load,
cacheDuration: 2,
});
await source.load({ feature: "x" }, 0);
expect(source.getById(1)).toEqual({ id: 1, text: "A", feature: "x" });
const values = source.values({ feature: "x" });
expect(values).not.toBeUndefined();
if (values == null) {
throw new Error("shouldn't happen");
}
expect(refSnapshots(values)).toEqual([
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
]);
expect(values[0].displayText).toEqual("Display A");
expect(loadHit).toEqual(["x"]);
// when we try to reload with the same feature, we don't get a hit for load
await source.load({ feature: "x" }, 0);
expect(loadHit).toEqual(["x"]);
// and we still get the same results
const values2 = source.values({ feature: "x" });
expect(values2).not.toBeUndefined();
expect(refSnapshots(values2)).toEqual([
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
]);
// when the cache duration has expired we expect another load.
await source.load({ feature: "x" }, 3 * 1000);
expect(loadHit).toEqual(["x", "x"]);
});
test("source should load once when multiple loads for the same source are triggered", async () => {
const Item = types
.model("Item", {
id: types.identifierNumber,
text: types.string,
feature: types.string,
})
.views((self) => ({
get displayText() {
return "Display " + self.text;
},
}));
const Container = types.model("Container", {
entryMap: types.map(Item),
});
const container = Container.create({ entryMap: {} });
const data = [
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
{ id: 3, text: "C", feature: "y" },
];
let loadHit: number = 0;
const load = async ({ feature }: { feature: string }) => {
loadHit++;
return data;
};
const source = new Source({
entryMap: container.entryMap,
load,
cacheDuration: 2,
});
await Promise.allSettled([
source.load(),
source.load(),
source.load(),
source.load(),
source.load(),
source.load(),
source.load(),
]);
expect(loadHit).toBe(1);
loadHit = 0;
source.clear();
await Promise.allSettled([
source.load(),
source.load(),
source.load(),
source.load({ feature: "a" }),
source.load(),
source.load(),
source.load(),
]);
expect(loadHit).toBe(2);
const loadWithReject = ({ feature }: { feature: string }) => {
loadHit++;
return Promise.reject();
};
const sourceWithReject = new Source({
entryMap: container.entryMap,
load: loadWithReject,
cacheDuration: 2,
});
// Make sure a reject also clears the promise from the `existingLoad`.
loadHit = 0;
await sourceWithReject.load().catch(() => true);
await sourceWithReject.load().catch(() => true);
await sourceWithReject.load().catch(() => true);
expect(loadHit).toBe(3);
});
test("source container function", async () => {
const Item = types.model("Item", {
id: types.identifierNumber,
text: types.string,
});
const Container = types.model("Container", {
entryMap: types.map(Item),
});
const container = Container.create({ entryMap: {} });
const data = [
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
{ id: 3, text: "C", feature: "y" },
];
const loadHit: string[] = [];
const load = async ({ feature }: { feature: string }) => {
loadHit.push(feature);
return data.filter((entry) => entry.feature === feature);
};
const source = new Source({
entryMap: () => container.entryMap,
load,
cacheDuration: 2,
});
await source.load({ feature: "x" }, 0);
expect(source.getById(1)).toEqual({ id: 1, text: "A" });
const values = source.values({ feature: "x" });
expect(values).not.toBeUndefined();
expect(refSnapshots(values)).toEqual([
{ id: 1, text: "A" },
{ id: 2, text: "B" },
]);
expect(loadHit).toEqual(["x"]);
// when we try to reload with the same feature, we don't get a hit for load
await source.load({ feature: "x" }, 0);
expect(loadHit).toEqual(["x"]);
// and we still get the same results
const values2 = source.values({ feature: "x" });
expect(values2).not.toBeUndefined();
expect(refSnapshots(values2)).toEqual([
{ id: 1, text: "A" },
{ id: 2, text: "B" },
]);
// when the cache duration has expired we expect another load.
await source.load({ feature: "x" }, 3 * 1000);
expect(loadHit).toEqual(["x", "x"]);
});
describe("source accessor in fields", () => {
const ItemA = types.model("ItemA", {
id: types.identifierNumber,
text: types.string,
});
const ContainerA = types.model("ContainerA", {
entryMap: types.map(ItemA),
});
const ItemB = types.model("ItemB", {
id: types.identifierNumber,
text: types.string,
});
const ContainerB = types.model("ContainerB", {
entryMap: types.map(ItemB),
});
const M = types.model("M", {
a: types.maybe(types.reference(ItemA)),
b: types.maybe(types.reference(ItemB)),
});
const R = types.model("R", {
m: M,
containerA: ContainerA,
containerB: ContainerB,
});
// pretend this is data on the server. The load functions use this
// to give correct answers.
const aData = [
{ id: 1, text: "AOne" },
{ id: 2, text: "ATwo" },
];
const bData = [
{ id: 3, text: "BThree", aId: 1 },
{ id: 4, text: "BFour", aId: 1 },
{ id: 5, text: "BFive", aId: 2 },
];
async function loadA(q: any) {
return aData;
}
// we filter b based on a
async function loadB(q: any) {
const a = q.a;
const aId = a != null ? a.id : undefined;
return bData.filter((entry) => entry.aId === aId);
}
test("form without autoLoad", async () => {
const r = R.create({
m: {
a: undefined,
b: undefined,
},
containerA: { entryMap: {} },
containerB: { entryMap: {} },
});
const o = r.m;
const containerA = r.containerA;
const containerB = r.containerB;
const sourceA = new Source({ entryMap: containerA.entryMap, load: loadA });
const sourceB = new Source({ entryMap: containerB.entryMap, load: loadB });
const form = new Form(M, {
a: new Field(converters.maybe(converters.model(ItemA)), {
references: {
source: sourceA,
},
}),
b: new Field(converters.maybe(converters.model(ItemB)), {
references: {
source: sourceB,
// this source is dependent on state. This information
// should be sent whenever a load is issued
dependentQuery: (accessor) => {
return { a: accessor.node.a };
},
},
}),
});
const state = form.state(o);
const fieldA = state.field("a");
const fieldB = state.field("b");
expect(fieldA.references.isEnabled()).toBeTruthy();
// we must trigger a load before we can access references
// synchronously
await fieldA.references.load();
const refsA = fieldA.references.values();
expect(refSnapshots(refsA)).toEqual([
{ id: 1, text: "AOne" },
{ id: 2, text: "ATwo" },
]);
await fieldB.references.load();
// when we haven't selected A yet, this will be empty - no choices
// are possible
const refsB = fieldB.references.values();
expect(refSnapshots(refsB)).toEqual([]);
// now we make a selection in A
const item1 = containerA.entryMap.get("1");
if (item1 === undefined) {
throw new Error("item1 should exist");
}
fieldA.setRaw(item1);
// now we reload B
await fieldB.references.load();
// this will automatically trigger a reload of b, as a is dependent on b
// and we turn on autoReload
await resolveReactions();
// refs for B should now be a different list that fits A
const refsB2 = fieldB.references.values();
expect(refSnapshots(refsB2)).toEqual([
{ id: 3, text: "BThree" },
{ id: 4, text: "BFour" },
]);
});
test("form with autoLoad", async () => {
const r = R.create({
m: {
a: undefined,
b: undefined,
},
containerA: { entryMap: {} },
containerB: { entryMap: {} },
});
const o = r.m;
const containerA = r.containerA;
const containerB = r.containerB;
const sourceA = new Source({ entryMap: containerA.entryMap, load: loadA });
const sourceB = new Source({ entryMap: containerB.entryMap, load: loadB });
const form = new Form(M, {
a: new Field(converters.maybe(converters.model(ItemA)), {
references: {
source: sourceA,
},
}),
b: new Field(converters.maybe(converters.model(ItemB)), {
references: {
source: sourceB,
// this source is dependent on state. This information
// should be sent whenever a load is issued
dependentQuery: (accessor) => {
return { a: accessor.node.a };
},
},
}),
});
const state = form.state(o);
const fieldA = state.field("a");
const fieldB = state.field("b");
const disposeA = fieldA.references.autoLoadReaction();
const disposeB = fieldB.references.autoLoadReaction();
// we must trigger a load before we can access references
// synchronously
await fieldA.references.load();
const refsA = fieldA.references.values();
expect(refSnapshots(refsA)).toEqual([
{ id: 1, text: "AOne" },
{ id: 2, text: "ATwo" },
]);
await fieldB.references.load();
// when we haven't selected A yet, this will be empty - no choices
// are possible
const refsB = fieldB.references.values();
expect(refSnapshots(refsB)).toEqual([]);
// now we make a selection in A
const item1 = containerA.entryMap.get("1");
if (item1 === undefined) {
throw new Error("item1 should exist");
}
fieldA.setRaw(item1);
// // this will automatically trigger a reload of b, as a is dependent on b
// // and we turn on autoReload
await resolveReactions();
// refs for B should now be a different list that fits A
const refsB2 = fieldB.references.values();
expect(refSnapshots(refsB2)).toEqual([
{ id: 3, text: "BThree" },
{ id: 4, text: "BFour" },
]);
disposeA();
disposeB();
});
test("form with autoLoad disposes on delete", async () => {
const n = types.model("N", {
foo: types.array(M),
containerA: ContainerA,
containerB: ContainerB,
});
const r = n.create({
foo: [
{
a: undefined,
b: undefined,
},
],
containerA: { entryMap: {} },
containerB: { entryMap: {} },
});
const containerA = r.containerA;
const containerB = r.containerB;
const sourceA = new Source({ entryMap: containerA.entryMap, load: loadA });
const sourceB = new Source({ entryMap: containerB.entryMap, load: loadB });
let dependentQueryCounter = 0;
const form = new Form(n, {
foo: new RepeatingForm({
a: new Field(converters.maybe(converters.model(ItemA)), {
references: {
source: sourceA,
},
}),
b: new Field(converters.maybe(converters.model(ItemB)), {
references: {
source: sourceB,
// this source is dependent on state. This information
// should be sent whenever a load is issued
dependentQuery: (accessor) => {
dependentQueryCounter += 1;
return { a: accessor.node.a, c: accessor.node.c };
},
},
}),
}),
});
const state = form.state(r);
const repeating = state.repeatingForm("foo");
const firstLine = repeating.index(0);
const fieldA = firstLine.field("a");
const fieldB = firstLine.field("b");
fieldA.references.autoLoadReaction();
fieldB.references.autoLoadReaction();
expect(dependentQueryCounter).toEqual(1);
repeating.remove(r.foo[0]);
expect(dependentQueryCounter).toEqual(1);
});
test("no references", async () => {
const r = R.create({
m: {
a: undefined,
},
containerA: { entryMap: {} },
containerB: { entryMap: {} },
});
const o = r.m;
const form = new Form(M, {
a: new Field(converters.maybe(converters.model(ItemA))),
});
const state = form.state(o);
const fieldA = state.field("a");
expect(fieldA.references.isEnabled()).toBeFalsy();
expect(() => fieldA.references.values()).toThrow();
});
});
test("source clear", async () => {
const Item = types.model("Item", {
id: types.identifierNumber,
text: types.string,
feature: types.string,
});
const Container = types.model("Container", {
entryMap: types.map(Item),
});
const container = Container.create({ entryMap: {} });
const data = [
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
{ id: 3, text: "C", feature: "y" },
];
const load = async () => {
return data;
};
const source = new Source<typeof Item, any>({
entryMap: container.entryMap,
load,
cacheDuration: 2,
});
await source.load({}, 0);
expect(source.getById(1)).toEqual({ id: 1, text: "A", feature: "x" });
const values = source.values({});
expect(values).toBeDefined();
if (values == null) {
throw new Error("This shouldn't happen");
}
expect(values).not.toBeUndefined();
expect(refSnapshots(values)).toEqual([
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
{ id: 3, text: "C", feature: "y" },
]);
source.clear();
expect(Array.from(source.entryMap.keys()).length).toBe(0);
expect(source.values({})).toBeUndefined();
});
test("source default timestamp", async () => {
const Item = types.model("Item", {
id: types.identifierNumber,
text: types.string,
feature: types.string,
});
const Container = types.model("Container", {
entryMap: types.map(Item),
});
const container = Container.create({ entryMap: {} });
const data = [
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
{ id: 3, text: "C", feature: "y" },
];
const loadHit: string[] = [];
const load = async ({ feature }: { feature: string }) => {
loadHit.push(feature);
return data.filter((entry) => entry.feature === feature);
};
const source = new Source({
entryMap: container.entryMap,
load,
cacheDuration: 2,
});
await source.load({ feature: "x" });
expect(loadHit).toEqual(["x"]);
await source.load({ feature: "x" });
// we should still get it from the cache, as timestamp was sent
// implicitly.
expect(loadHit).toEqual(["x"]);
});
test("source default query", async () => {
const Item = types.model("Item", {
id: types.identifierNumber,
text: types.string,
feature: types.string,
});
const Container = types.model("Container", {
entryMap: types.map(Item),
});
const container = Container.create({ entryMap: {} });
const data = [
{ id: 1, text: "A", feature: "x" },
{ id: 2, text: "B", feature: "x" },
{ id: 3, text: "C", feature: "y" },
];
const loadHit: (string | undefined)[] = [];
const load = async ({ feature }: { feature?: string }) => {
loadHit.push(feature);
return data.filter((entry) => entry.feature === feature);
};
const source = new Source({
entryMap: container.entryMap,
load,
cacheDuration: 2,
});
await source.load();
expect(loadHit).toEqual([undefined]);
await source.load();
// we should still get it from the cache, as timestamp was sent
// implicitly.
expect(loadHit).toEqual([undefined]);
}); | the_stack |
import { GraphQLClient } from 'graphql-request';
import * as Dom from 'graphql-request/dist/types.dom';
import gql from 'graphql-tag';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/** The Circle scalar type represents a circle, defined by the coordinates of its center and a radius. The Circle type is used to represent a searchable area together with the '_within_circle' filter. */
Circle: any;
/**
* A date-time string at UTC, such as 2007-12-03T10:15:30Z,
* compliant with the 'date-time' format outlined in section 5.6 of
* the RFC 3339 profile of the ISO 8601 standard for representation
* of dates and times using the Gregorian calendar.
*/
DateTime: any;
/** The 'Dimension' type represents dimensions as whole numeric values between `1` and `4000`. */
Dimension: any;
/** The 'HexColor' type represents color in `rgb:ffffff` string format. */
HexColor: any;
/** The 'Quality' type represents quality as whole numeric values between `1` and `100`. */
Quality: any;
/** The Rectangle scalar type represents a rectangle, defined by the coordinates of its top left and bottom right corners. The Rectangle type is used to represent a searchable area together with the '_within_rectangle' filter. */
Rectangle: any;
};
/** Represents a binary file in a space. An asset can be any file type. */
export type Asset = {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
title: Maybe<Scalars['String']>;
description: Maybe<Scalars['String']>;
contentType: Maybe<Scalars['String']>;
fileName: Maybe<Scalars['String']>;
size: Maybe<Scalars['Int']>;
url: Maybe<Scalars['String']>;
width: Maybe<Scalars['Int']>;
height: Maybe<Scalars['Int']>;
linkedFrom: Maybe<AssetLinkingCollections>;
};
/** Represents a binary file in a space. An asset can be any file type. */
export type AssetUrlArgs = {
transform: Maybe<ImageTransformOptions>;
};
/** Represents a binary file in a space. An asset can be any file type. */
export type AssetLinkedFromArgs = {
allowedLocales: Maybe<Array<Maybe<Scalars['String']>>>;
};
export type AssetCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Asset>>;
};
export type AssetFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
title_exists: Maybe<Scalars['Boolean']>;
title: Maybe<Scalars['String']>;
title_not: Maybe<Scalars['String']>;
title_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_contains: Maybe<Scalars['String']>;
title_not_contains: Maybe<Scalars['String']>;
description_exists: Maybe<Scalars['Boolean']>;
description: Maybe<Scalars['String']>;
description_not: Maybe<Scalars['String']>;
description_in: Maybe<Array<Maybe<Scalars['String']>>>;
description_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
description_contains: Maybe<Scalars['String']>;
description_not_contains: Maybe<Scalars['String']>;
url_exists: Maybe<Scalars['Boolean']>;
url: Maybe<Scalars['String']>;
url_not: Maybe<Scalars['String']>;
url_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_contains: Maybe<Scalars['String']>;
url_not_contains: Maybe<Scalars['String']>;
size_exists: Maybe<Scalars['Boolean']>;
size: Maybe<Scalars['Int']>;
size_not: Maybe<Scalars['Int']>;
size_in: Maybe<Array<Maybe<Scalars['Int']>>>;
size_not_in: Maybe<Array<Maybe<Scalars['Int']>>>;
size_gt: Maybe<Scalars['Int']>;
size_gte: Maybe<Scalars['Int']>;
size_lt: Maybe<Scalars['Int']>;
size_lte: Maybe<Scalars['Int']>;
contentType_exists: Maybe<Scalars['Boolean']>;
contentType: Maybe<Scalars['String']>;
contentType_not: Maybe<Scalars['String']>;
contentType_in: Maybe<Array<Maybe<Scalars['String']>>>;
contentType_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
contentType_contains: Maybe<Scalars['String']>;
contentType_not_contains: Maybe<Scalars['String']>;
fileName_exists: Maybe<Scalars['Boolean']>;
fileName: Maybe<Scalars['String']>;
fileName_not: Maybe<Scalars['String']>;
fileName_in: Maybe<Array<Maybe<Scalars['String']>>>;
fileName_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
fileName_contains: Maybe<Scalars['String']>;
fileName_not_contains: Maybe<Scalars['String']>;
width_exists: Maybe<Scalars['Boolean']>;
width: Maybe<Scalars['Int']>;
width_not: Maybe<Scalars['Int']>;
width_in: Maybe<Array<Maybe<Scalars['Int']>>>;
width_not_in: Maybe<Array<Maybe<Scalars['Int']>>>;
width_gt: Maybe<Scalars['Int']>;
width_gte: Maybe<Scalars['Int']>;
width_lt: Maybe<Scalars['Int']>;
width_lte: Maybe<Scalars['Int']>;
height_exists: Maybe<Scalars['Boolean']>;
height: Maybe<Scalars['Int']>;
height_not: Maybe<Scalars['Int']>;
height_in: Maybe<Array<Maybe<Scalars['Int']>>>;
height_not_in: Maybe<Array<Maybe<Scalars['Int']>>>;
height_gt: Maybe<Scalars['Int']>;
height_gte: Maybe<Scalars['Int']>;
height_lt: Maybe<Scalars['Int']>;
height_lte: Maybe<Scalars['Int']>;
OR: Maybe<Array<Maybe<AssetFilter>>>;
AND: Maybe<Array<Maybe<AssetFilter>>>;
};
export type AssetLinkingCollections = {
entryCollection: Maybe<EntryCollection>;
eventCollection: Maybe<EventCollection>;
externalResourceCollection: Maybe<ExternalResourceCollection>;
sponsorCollection: Maybe<SponsorCollection>;
speakerCollection: Maybe<SpeakerCollection>;
};
export type AssetLinkingCollectionsEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type AssetLinkingCollectionsEventCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type AssetLinkingCollectionsExternalResourceCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type AssetLinkingCollectionsSponsorCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type AssetLinkingCollectionsSpeakerCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export enum AssetOrder {
UrlAsc = 'url_ASC',
UrlDesc = 'url_DESC',
SizeAsc = 'size_ASC',
SizeDesc = 'size_DESC',
ContentTypeAsc = 'contentType_ASC',
ContentTypeDesc = 'contentType_DESC',
FileNameAsc = 'fileName_ASC',
FileNameDesc = 'fileName_DESC',
WidthAsc = 'width_ASC',
WidthDesc = 'width_DESC',
HeightAsc = 'height_ASC',
HeightDesc = 'height_DESC',
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
export type ContentfulMetadata = {
tags: Array<Maybe<ContentfulTag>>;
};
export type ContentfulMetadataFilter = {
tags_exists: Maybe<Scalars['Boolean']>;
tags: Maybe<ContentfulMetadataTagsFilter>;
};
export type ContentfulMetadataTagsFilter = {
id_contains_all: Maybe<Array<Maybe<Scalars['String']>>>;
id_contains_some: Maybe<Array<Maybe<Scalars['String']>>>;
id_contains_none: Maybe<Array<Maybe<Scalars['String']>>>;
};
/**
* Represents a tag entity for finding and organizing content easily.
* Find out more here: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/content-tags
*/
export type ContentfulTag = {
id: Maybe<Scalars['String']>;
name: Maybe<Scalars['String']>;
};
export type Entry = {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
};
export type EntryCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Entry>>;
};
export type EntryFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
OR: Maybe<Array<Maybe<EntryFilter>>>;
AND: Maybe<Array<Maybe<EntryFilter>>>;
};
export enum EntryOrder {
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type Event = Entry & {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
linkedFrom: Maybe<EventLinkingCollections>;
poster: Maybe<Asset>;
title: Maybe<Scalars['String']>;
slug: Maybe<Scalars['String']>;
description: Maybe<Scalars['String']>;
category: Maybe<Scalars['String']>;
startingDate: Maybe<Scalars['DateTime']>;
sessionsCollection: Maybe<EventSessionsCollection>;
onlineEvent: Maybe<Scalars['Boolean']>;
location: Maybe<Scalars['String']>;
coordinates: Maybe<Location>;
url: Maybe<Scalars['String']>;
albumUrl: Maybe<Scalars['String']>;
quota: Maybe<Scalars['Int']>;
notes: Maybe<Scalars['String']>;
videoUrl: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventLinkedFromArgs = {
allowedLocales: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventPosterArgs = {
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventTitleArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventSlugArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventDescriptionArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventCategoryArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventStartingDateArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventSessionsCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventOnlineEventArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventLocationArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventCoordinatesArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventUrlArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventAlbumUrlArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventQuotaArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventNotesArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/event) */
export type EventVideoUrlArgs = {
locale: Maybe<Scalars['String']>;
};
export type EventCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Event>>;
};
export type EventFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
poster_exists: Maybe<Scalars['Boolean']>;
title_exists: Maybe<Scalars['Boolean']>;
title: Maybe<Scalars['String']>;
title_not: Maybe<Scalars['String']>;
title_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_contains: Maybe<Scalars['String']>;
title_not_contains: Maybe<Scalars['String']>;
slug_exists: Maybe<Scalars['Boolean']>;
slug: Maybe<Scalars['String']>;
slug_not: Maybe<Scalars['String']>;
slug_in: Maybe<Array<Maybe<Scalars['String']>>>;
slug_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
slug_contains: Maybe<Scalars['String']>;
slug_not_contains: Maybe<Scalars['String']>;
description_exists: Maybe<Scalars['Boolean']>;
description: Maybe<Scalars['String']>;
description_not: Maybe<Scalars['String']>;
description_in: Maybe<Array<Maybe<Scalars['String']>>>;
description_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
description_contains: Maybe<Scalars['String']>;
description_not_contains: Maybe<Scalars['String']>;
category_exists: Maybe<Scalars['Boolean']>;
category: Maybe<Scalars['String']>;
category_not: Maybe<Scalars['String']>;
category_in: Maybe<Array<Maybe<Scalars['String']>>>;
category_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
category_contains: Maybe<Scalars['String']>;
category_not_contains: Maybe<Scalars['String']>;
startingDate_exists: Maybe<Scalars['Boolean']>;
startingDate: Maybe<Scalars['DateTime']>;
startingDate_not: Maybe<Scalars['DateTime']>;
startingDate_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
startingDate_not_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
startingDate_gt: Maybe<Scalars['DateTime']>;
startingDate_gte: Maybe<Scalars['DateTime']>;
startingDate_lt: Maybe<Scalars['DateTime']>;
startingDate_lte: Maybe<Scalars['DateTime']>;
sessionsCollection_exists: Maybe<Scalars['Boolean']>;
onlineEvent_exists: Maybe<Scalars['Boolean']>;
onlineEvent: Maybe<Scalars['Boolean']>;
onlineEvent_not: Maybe<Scalars['Boolean']>;
location_exists: Maybe<Scalars['Boolean']>;
location: Maybe<Scalars['String']>;
location_not: Maybe<Scalars['String']>;
location_in: Maybe<Array<Maybe<Scalars['String']>>>;
location_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
location_contains: Maybe<Scalars['String']>;
location_not_contains: Maybe<Scalars['String']>;
coordinates_exists: Maybe<Scalars['Boolean']>;
coordinates_within_circle: Maybe<Scalars['Circle']>;
coordinates_within_rectangle: Maybe<Scalars['Rectangle']>;
url_exists: Maybe<Scalars['Boolean']>;
url: Maybe<Scalars['String']>;
url_not: Maybe<Scalars['String']>;
url_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_contains: Maybe<Scalars['String']>;
url_not_contains: Maybe<Scalars['String']>;
albumUrl_exists: Maybe<Scalars['Boolean']>;
albumUrl: Maybe<Scalars['String']>;
albumUrl_not: Maybe<Scalars['String']>;
albumUrl_in: Maybe<Array<Maybe<Scalars['String']>>>;
albumUrl_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
albumUrl_contains: Maybe<Scalars['String']>;
albumUrl_not_contains: Maybe<Scalars['String']>;
quota_exists: Maybe<Scalars['Boolean']>;
quota: Maybe<Scalars['Int']>;
quota_not: Maybe<Scalars['Int']>;
quota_in: Maybe<Array<Maybe<Scalars['Int']>>>;
quota_not_in: Maybe<Array<Maybe<Scalars['Int']>>>;
quota_gt: Maybe<Scalars['Int']>;
quota_gte: Maybe<Scalars['Int']>;
quota_lt: Maybe<Scalars['Int']>;
quota_lte: Maybe<Scalars['Int']>;
notes_exists: Maybe<Scalars['Boolean']>;
notes: Maybe<Scalars['String']>;
notes_not: Maybe<Scalars['String']>;
notes_in: Maybe<Array<Maybe<Scalars['String']>>>;
notes_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
notes_contains: Maybe<Scalars['String']>;
notes_not_contains: Maybe<Scalars['String']>;
videoUrl_exists: Maybe<Scalars['Boolean']>;
videoUrl_contains_all: Maybe<Array<Maybe<Scalars['String']>>>;
videoUrl_contains_some: Maybe<Array<Maybe<Scalars['String']>>>;
videoUrl_contains_none: Maybe<Array<Maybe<Scalars['String']>>>;
OR: Maybe<Array<Maybe<EventFilter>>>;
AND: Maybe<Array<Maybe<EventFilter>>>;
};
export type EventLinkingCollections = {
entryCollection: Maybe<EntryCollection>;
};
export type EventLinkingCollectionsEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export enum EventOrder {
TitleAsc = 'title_ASC',
TitleDesc = 'title_DESC',
SlugAsc = 'slug_ASC',
SlugDesc = 'slug_DESC',
CategoryAsc = 'category_ASC',
CategoryDesc = 'category_DESC',
StartingDateAsc = 'startingDate_ASC',
StartingDateDesc = 'startingDate_DESC',
OnlineEventAsc = 'onlineEvent_ASC',
OnlineEventDesc = 'onlineEvent_DESC',
LocationAsc = 'location_ASC',
LocationDesc = 'location_DESC',
UrlAsc = 'url_ASC',
UrlDesc = 'url_DESC',
AlbumUrlAsc = 'albumUrl_ASC',
AlbumUrlDesc = 'albumUrl_DESC',
QuotaAsc = 'quota_ASC',
QuotaDesc = 'quota_DESC',
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
export type EventSessionsCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Session>>;
};
/** Place to add external resource such as Link, Contact, etc. [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/externalResource) */
export type ExternalResource = Entry & {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
linkedFrom: Maybe<ExternalResourceLinkingCollections>;
title: Maybe<Scalars['String']>;
image: Maybe<Asset>;
description: Maybe<Scalars['String']>;
url: Maybe<Scalars['String']>;
};
/** Place to add external resource such as Link, Contact, etc. [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/externalResource) */
export type ExternalResourceLinkedFromArgs = {
allowedLocales: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** Place to add external resource such as Link, Contact, etc. [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/externalResource) */
export type ExternalResourceTitleArgs = {
locale: Maybe<Scalars['String']>;
};
/** Place to add external resource such as Link, Contact, etc. [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/externalResource) */
export type ExternalResourceImageArgs = {
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
/** Place to add external resource such as Link, Contact, etc. [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/externalResource) */
export type ExternalResourceDescriptionArgs = {
locale: Maybe<Scalars['String']>;
};
/** Place to add external resource such as Link, Contact, etc. [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/externalResource) */
export type ExternalResourceUrlArgs = {
locale: Maybe<Scalars['String']>;
};
export type ExternalResourceCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<ExternalResource>>;
};
export type ExternalResourceFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
title_exists: Maybe<Scalars['Boolean']>;
title: Maybe<Scalars['String']>;
title_not: Maybe<Scalars['String']>;
title_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_contains: Maybe<Scalars['String']>;
title_not_contains: Maybe<Scalars['String']>;
image_exists: Maybe<Scalars['Boolean']>;
description_exists: Maybe<Scalars['Boolean']>;
description: Maybe<Scalars['String']>;
description_not: Maybe<Scalars['String']>;
description_in: Maybe<Array<Maybe<Scalars['String']>>>;
description_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
description_contains: Maybe<Scalars['String']>;
description_not_contains: Maybe<Scalars['String']>;
url_exists: Maybe<Scalars['Boolean']>;
url: Maybe<Scalars['String']>;
url_not: Maybe<Scalars['String']>;
url_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_contains: Maybe<Scalars['String']>;
url_not_contains: Maybe<Scalars['String']>;
OR: Maybe<Array<Maybe<ExternalResourceFilter>>>;
AND: Maybe<Array<Maybe<ExternalResourceFilter>>>;
};
export type ExternalResourceLinkingCollections = {
entryCollection: Maybe<EntryCollection>;
};
export type ExternalResourceLinkingCollectionsEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export enum ExternalResourceOrder {
TitleAsc = 'title_ASC',
TitleDesc = 'title_DESC',
DescriptionAsc = 'description_ASC',
DescriptionDesc = 'description_DESC',
UrlAsc = 'url_ASC',
UrlDesc = 'url_DESC',
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
export enum ImageFormat {
/** JPG image format. */
Jpg = 'JPG',
/**
* Progressive JPG format stores multiple passes of an image in progressively higher detail.
* When a progressive image is loading, the viewer will first see a lower quality pixelated version which
* will gradually improve in detail, until the image is fully downloaded. This is to display an image as
* early as possible to make the layout look as designed.
*/
JpgProgressive = 'JPG_PROGRESSIVE',
/** PNG image format */
Png = 'PNG',
/**
* 8-bit PNG images support up to 256 colors and weigh less than the standard 24-bit PNG equivalent.
* The 8-bit PNG format is mostly used for simple images, such as icons or logos.
*/
Png8 = 'PNG8',
/** WebP image format. */
Webp = 'WEBP'
}
export enum ImageResizeFocus {
/** Focus the resizing on the center. */
Center = 'CENTER',
/** Focus the resizing on the top. */
Top = 'TOP',
/** Focus the resizing on the top right. */
TopRight = 'TOP_RIGHT',
/** Focus the resizing on the right. */
Right = 'RIGHT',
/** Focus the resizing on the bottom right. */
BottomRight = 'BOTTOM_RIGHT',
/** Focus the resizing on the bottom. */
Bottom = 'BOTTOM',
/** Focus the resizing on the bottom left. */
BottomLeft = 'BOTTOM_LEFT',
/** Focus the resizing on the left. */
Left = 'LEFT',
/** Focus the resizing on the top left. */
TopLeft = 'TOP_LEFT',
/** Focus the resizing on the largest face. */
Face = 'FACE',
/** Focus the resizing on the area containing all the faces. */
Faces = 'FACES'
}
export enum ImageResizeStrategy {
/** Resizes the image to fit into the specified dimensions. */
Fit = 'FIT',
/**
* Resizes the image to the specified dimensions, padding the image if needed.
* Uses desired background color as padding color.
*/
Pad = 'PAD',
/** Resizes the image to the specified dimensions, cropping the image if needed. */
Fill = 'FILL',
/** Resizes the image to the specified dimensions, changing the original aspect ratio if needed. */
Scale = 'SCALE',
/** Crops a part of the original image to fit into the specified dimensions. */
Crop = 'CROP',
/** Creates a thumbnail from the image. */
Thumb = 'THUMB'
}
export type ImageTransformOptions = {
/** Desired width in pixels. Defaults to the original image width. */
width: Maybe<Scalars['Dimension']>;
/** Desired height in pixels. Defaults to the original image height. */
height: Maybe<Scalars['Dimension']>;
/**
* Desired quality of the image in percents.
* Used for `PNG8`, `JPG`, `JPG_PROGRESSIVE` and `WEBP` formats.
*/
quality: Maybe<Scalars['Quality']>;
/**
* Desired corner radius in pixels.
* Results in an image with rounded corners (pass `-1` for a full circle/ellipse).
* Defaults to `0`. Uses desired background color as padding color,
* unless the format is `JPG` or `JPG_PROGRESSIVE` and resize strategy is `PAD`, then defaults to white.
*/
cornerRadius: Maybe<Scalars['Int']>;
/** Desired resize strategy. Defaults to `FIT`. */
resizeStrategy: Maybe<ImageResizeStrategy>;
/** Desired resize focus area. Defaults to `CENTER`. */
resizeFocus: Maybe<ImageResizeFocus>;
/**
* Desired background color, used with corner radius or `PAD` resize strategy.
* Defaults to transparent (for `PNG`, `PNG8` and `WEBP`) or white (for `JPG` and `JPG_PROGRESSIVE`).
*/
backgroundColor: Maybe<Scalars['HexColor']>;
/** Desired image format. Defaults to the original image format. */
format: Maybe<ImageFormat>;
};
export type Location = {
lat: Maybe<Scalars['Float']>;
lon: Maybe<Scalars['Float']>;
};
/** A place to write blog post [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/post) */
export type Post = Entry & {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
linkedFrom: Maybe<PostLinkingCollections>;
slug: Maybe<Scalars['String']>;
title: Maybe<Scalars['String']>;
subtitle: Maybe<Scalars['String']>;
content: Maybe<Scalars['String']>;
};
/** A place to write blog post [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/post) */
export type PostLinkedFromArgs = {
allowedLocales: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** A place to write blog post [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/post) */
export type PostSlugArgs = {
locale: Maybe<Scalars['String']>;
};
/** A place to write blog post [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/post) */
export type PostTitleArgs = {
locale: Maybe<Scalars['String']>;
};
/** A place to write blog post [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/post) */
export type PostSubtitleArgs = {
locale: Maybe<Scalars['String']>;
};
/** A place to write blog post [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/post) */
export type PostContentArgs = {
locale: Maybe<Scalars['String']>;
};
export type PostCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Post>>;
};
export type PostFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
slug_exists: Maybe<Scalars['Boolean']>;
slug: Maybe<Scalars['String']>;
slug_not: Maybe<Scalars['String']>;
slug_in: Maybe<Array<Maybe<Scalars['String']>>>;
slug_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
slug_contains: Maybe<Scalars['String']>;
slug_not_contains: Maybe<Scalars['String']>;
title_exists: Maybe<Scalars['Boolean']>;
title: Maybe<Scalars['String']>;
title_not: Maybe<Scalars['String']>;
title_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_contains: Maybe<Scalars['String']>;
title_not_contains: Maybe<Scalars['String']>;
subtitle_exists: Maybe<Scalars['Boolean']>;
subtitle: Maybe<Scalars['String']>;
subtitle_not: Maybe<Scalars['String']>;
subtitle_in: Maybe<Array<Maybe<Scalars['String']>>>;
subtitle_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
subtitle_contains: Maybe<Scalars['String']>;
subtitle_not_contains: Maybe<Scalars['String']>;
content_exists: Maybe<Scalars['Boolean']>;
content: Maybe<Scalars['String']>;
content_not: Maybe<Scalars['String']>;
content_in: Maybe<Array<Maybe<Scalars['String']>>>;
content_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
content_contains: Maybe<Scalars['String']>;
content_not_contains: Maybe<Scalars['String']>;
OR: Maybe<Array<Maybe<PostFilter>>>;
AND: Maybe<Array<Maybe<PostFilter>>>;
};
export type PostLinkingCollections = {
entryCollection: Maybe<EntryCollection>;
};
export type PostLinkingCollectionsEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export enum PostOrder {
SlugAsc = 'slug_ASC',
SlugDesc = 'slug_DESC',
TitleAsc = 'title_ASC',
TitleDesc = 'title_DESC',
SubtitleAsc = 'subtitle_ASC',
SubtitleDesc = 'subtitle_DESC',
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
export type Query = {
asset: Maybe<Asset>;
assetCollection: Maybe<AssetCollection>;
event: Maybe<Event>;
eventCollection: Maybe<EventCollection>;
resources: Maybe<Resources>;
resourcesCollection: Maybe<ResourcesCollection>;
externalResource: Maybe<ExternalResource>;
externalResourceCollection: Maybe<ExternalResourceCollection>;
post: Maybe<Post>;
postCollection: Maybe<PostCollection>;
sponsor: Maybe<Sponsor>;
sponsorCollection: Maybe<SponsorCollection>;
session: Maybe<Session>;
sessionCollection: Maybe<SessionCollection>;
speaker: Maybe<Speaker>;
speakerCollection: Maybe<SpeakerCollection>;
entryCollection: Maybe<EntryCollection>;
};
export type QueryAssetArgs = {
id: Scalars['String'];
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type QueryAssetCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<AssetFilter>;
order: Maybe<Array<Maybe<AssetOrder>>>;
};
export type QueryEventArgs = {
id: Scalars['String'];
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type QueryEventCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<EventFilter>;
order: Maybe<Array<Maybe<EventOrder>>>;
};
export type QueryResourcesArgs = {
id: Scalars['String'];
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type QueryResourcesCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<ResourcesFilter>;
order: Maybe<Array<Maybe<ResourcesOrder>>>;
};
export type QueryExternalResourceArgs = {
id: Scalars['String'];
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type QueryExternalResourceCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<ExternalResourceFilter>;
order: Maybe<Array<Maybe<ExternalResourceOrder>>>;
};
export type QueryPostArgs = {
id: Scalars['String'];
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type QueryPostCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<PostFilter>;
order: Maybe<Array<Maybe<PostOrder>>>;
};
export type QuerySponsorArgs = {
id: Scalars['String'];
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type QuerySponsorCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<SponsorFilter>;
order: Maybe<Array<Maybe<SponsorOrder>>>;
};
export type QuerySessionArgs = {
id: Scalars['String'];
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type QuerySessionCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<SessionFilter>;
order: Maybe<Array<Maybe<SessionOrder>>>;
};
export type QuerySpeakerArgs = {
id: Scalars['String'];
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type QuerySpeakerCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<SpeakerFilter>;
order: Maybe<Array<Maybe<SpeakerOrder>>>;
};
export type QueryEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
where: Maybe<EntryFilter>;
order: Maybe<Array<Maybe<EntryOrder>>>;
};
/** What resource is for? (ex: Hacktoberfest, Basic javascript, etc.) [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/resources) */
export type Resources = Entry & {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
linkedFrom: Maybe<ResourcesLinkingCollections>;
title: Maybe<Scalars['String']>;
description: Maybe<Scalars['String']>;
buttonText: Maybe<Scalars['String']>;
url: Maybe<Scalars['String']>;
};
/** What resource is for? (ex: Hacktoberfest, Basic javascript, etc.) [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/resources) */
export type ResourcesLinkedFromArgs = {
allowedLocales: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** What resource is for? (ex: Hacktoberfest, Basic javascript, etc.) [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/resources) */
export type ResourcesTitleArgs = {
locale: Maybe<Scalars['String']>;
};
/** What resource is for? (ex: Hacktoberfest, Basic javascript, etc.) [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/resources) */
export type ResourcesDescriptionArgs = {
locale: Maybe<Scalars['String']>;
};
/** What resource is for? (ex: Hacktoberfest, Basic javascript, etc.) [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/resources) */
export type ResourcesButtonTextArgs = {
locale: Maybe<Scalars['String']>;
};
/** What resource is for? (ex: Hacktoberfest, Basic javascript, etc.) [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/resources) */
export type ResourcesUrlArgs = {
locale: Maybe<Scalars['String']>;
};
export type ResourcesCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Resources>>;
};
export type ResourcesFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
title_exists: Maybe<Scalars['Boolean']>;
title: Maybe<Scalars['String']>;
title_not: Maybe<Scalars['String']>;
title_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_contains: Maybe<Scalars['String']>;
title_not_contains: Maybe<Scalars['String']>;
description_exists: Maybe<Scalars['Boolean']>;
description: Maybe<Scalars['String']>;
description_not: Maybe<Scalars['String']>;
description_in: Maybe<Array<Maybe<Scalars['String']>>>;
description_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
description_contains: Maybe<Scalars['String']>;
description_not_contains: Maybe<Scalars['String']>;
buttonText_exists: Maybe<Scalars['Boolean']>;
buttonText: Maybe<Scalars['String']>;
buttonText_not: Maybe<Scalars['String']>;
buttonText_in: Maybe<Array<Maybe<Scalars['String']>>>;
buttonText_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
buttonText_contains: Maybe<Scalars['String']>;
buttonText_not_contains: Maybe<Scalars['String']>;
url_exists: Maybe<Scalars['Boolean']>;
url: Maybe<Scalars['String']>;
url_not: Maybe<Scalars['String']>;
url_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_contains: Maybe<Scalars['String']>;
url_not_contains: Maybe<Scalars['String']>;
OR: Maybe<Array<Maybe<ResourcesFilter>>>;
AND: Maybe<Array<Maybe<ResourcesFilter>>>;
};
export type ResourcesLinkingCollections = {
entryCollection: Maybe<EntryCollection>;
};
export type ResourcesLinkingCollectionsEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export enum ResourcesOrder {
TitleAsc = 'title_ASC',
TitleDesc = 'title_DESC',
DescriptionAsc = 'description_ASC',
DescriptionDesc = 'description_DESC',
ButtonTextAsc = 'buttonText_ASC',
ButtonTextDesc = 'buttonText_DESC',
UrlAsc = 'url_ASC',
UrlDesc = 'url_DESC',
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/session) */
export type Session = Entry & {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
linkedFrom: Maybe<SessionLinkingCollections>;
title: Maybe<Scalars['String']>;
speaker: Maybe<Speaker>;
startDatetime: Maybe<Scalars['DateTime']>;
endDatetime: Maybe<Scalars['DateTime']>;
deckUrl: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/session) */
export type SessionLinkedFromArgs = {
allowedLocales: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/session) */
export type SessionTitleArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/session) */
export type SessionSpeakerArgs = {
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/session) */
export type SessionStartDatetimeArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/session) */
export type SessionEndDatetimeArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/session) */
export type SessionDeckUrlArgs = {
locale: Maybe<Scalars['String']>;
};
export type SessionCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Session>>;
};
export type SessionFilter = {
speaker: Maybe<CfSpeakerNestedFilter>;
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
title_exists: Maybe<Scalars['Boolean']>;
title: Maybe<Scalars['String']>;
title_not: Maybe<Scalars['String']>;
title_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
title_contains: Maybe<Scalars['String']>;
title_not_contains: Maybe<Scalars['String']>;
speaker_exists: Maybe<Scalars['Boolean']>;
startDatetime_exists: Maybe<Scalars['Boolean']>;
startDatetime: Maybe<Scalars['DateTime']>;
startDatetime_not: Maybe<Scalars['DateTime']>;
startDatetime_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
startDatetime_not_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
startDatetime_gt: Maybe<Scalars['DateTime']>;
startDatetime_gte: Maybe<Scalars['DateTime']>;
startDatetime_lt: Maybe<Scalars['DateTime']>;
startDatetime_lte: Maybe<Scalars['DateTime']>;
endDatetime_exists: Maybe<Scalars['Boolean']>;
endDatetime: Maybe<Scalars['DateTime']>;
endDatetime_not: Maybe<Scalars['DateTime']>;
endDatetime_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
endDatetime_not_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
endDatetime_gt: Maybe<Scalars['DateTime']>;
endDatetime_gte: Maybe<Scalars['DateTime']>;
endDatetime_lt: Maybe<Scalars['DateTime']>;
endDatetime_lte: Maybe<Scalars['DateTime']>;
deckUrl_exists: Maybe<Scalars['Boolean']>;
deckUrl: Maybe<Scalars['String']>;
deckUrl_not: Maybe<Scalars['String']>;
deckUrl_in: Maybe<Array<Maybe<Scalars['String']>>>;
deckUrl_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
deckUrl_contains: Maybe<Scalars['String']>;
deckUrl_not_contains: Maybe<Scalars['String']>;
OR: Maybe<Array<Maybe<SessionFilter>>>;
AND: Maybe<Array<Maybe<SessionFilter>>>;
};
export type SessionLinkingCollections = {
entryCollection: Maybe<EntryCollection>;
eventCollection: Maybe<EventCollection>;
};
export type SessionLinkingCollectionsEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type SessionLinkingCollectionsEventCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export enum SessionOrder {
TitleAsc = 'title_ASC',
TitleDesc = 'title_DESC',
StartDatetimeAsc = 'startDatetime_ASC',
StartDatetimeDesc = 'startDatetime_DESC',
EndDatetimeAsc = 'endDatetime_ASC',
EndDatetimeDesc = 'endDatetime_DESC',
DeckUrlAsc = 'deckUrl_ASC',
DeckUrlDesc = 'deckUrl_DESC',
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/speaker) */
export type Speaker = Entry & {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
linkedFrom: Maybe<SpeakerLinkingCollections>;
avatar: Maybe<Asset>;
name: Maybe<Scalars['String']>;
jobTitle: Maybe<Scalars['String']>;
employer: Maybe<Scalars['String']>;
showEmployer: Maybe<Scalars['Boolean']>;
url: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/speaker) */
export type SpeakerLinkedFromArgs = {
allowedLocales: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/speaker) */
export type SpeakerAvatarArgs = {
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/speaker) */
export type SpeakerNameArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/speaker) */
export type SpeakerJobTitleArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/speaker) */
export type SpeakerEmployerArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/speaker) */
export type SpeakerShowEmployerArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/speaker) */
export type SpeakerUrlArgs = {
locale: Maybe<Scalars['String']>;
};
export type SpeakerCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Speaker>>;
};
export type SpeakerFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
avatar_exists: Maybe<Scalars['Boolean']>;
name_exists: Maybe<Scalars['Boolean']>;
name: Maybe<Scalars['String']>;
name_not: Maybe<Scalars['String']>;
name_in: Maybe<Array<Maybe<Scalars['String']>>>;
name_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
name_contains: Maybe<Scalars['String']>;
name_not_contains: Maybe<Scalars['String']>;
jobTitle_exists: Maybe<Scalars['Boolean']>;
jobTitle: Maybe<Scalars['String']>;
jobTitle_not: Maybe<Scalars['String']>;
jobTitle_in: Maybe<Array<Maybe<Scalars['String']>>>;
jobTitle_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
jobTitle_contains: Maybe<Scalars['String']>;
jobTitle_not_contains: Maybe<Scalars['String']>;
employer_exists: Maybe<Scalars['Boolean']>;
employer: Maybe<Scalars['String']>;
employer_not: Maybe<Scalars['String']>;
employer_in: Maybe<Array<Maybe<Scalars['String']>>>;
employer_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
employer_contains: Maybe<Scalars['String']>;
employer_not_contains: Maybe<Scalars['String']>;
showEmployer_exists: Maybe<Scalars['Boolean']>;
showEmployer: Maybe<Scalars['Boolean']>;
showEmployer_not: Maybe<Scalars['Boolean']>;
url_exists: Maybe<Scalars['Boolean']>;
url: Maybe<Scalars['String']>;
url_not: Maybe<Scalars['String']>;
url_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_contains: Maybe<Scalars['String']>;
url_not_contains: Maybe<Scalars['String']>;
OR: Maybe<Array<Maybe<SpeakerFilter>>>;
AND: Maybe<Array<Maybe<SpeakerFilter>>>;
};
export type SpeakerLinkingCollections = {
entryCollection: Maybe<EntryCollection>;
sessionCollection: Maybe<SessionCollection>;
};
export type SpeakerLinkingCollectionsEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export type SpeakerLinkingCollectionsSessionCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export enum SpeakerOrder {
NameAsc = 'name_ASC',
NameDesc = 'name_DESC',
JobTitleAsc = 'jobTitle_ASC',
JobTitleDesc = 'jobTitle_DESC',
EmployerAsc = 'employer_ASC',
EmployerDesc = 'employer_DESC',
ShowEmployerAsc = 'showEmployer_ASC',
ShowEmployerDesc = 'showEmployer_DESC',
UrlAsc = 'url_ASC',
UrlDesc = 'url_DESC',
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/sponsor) */
export type Sponsor = Entry & {
sys: Sys;
contentfulMetadata: ContentfulMetadata;
linkedFrom: Maybe<SponsorLinkingCollections>;
name: Maybe<Scalars['String']>;
category: Maybe<Scalars['String']>;
url: Maybe<Scalars['String']>;
logo: Maybe<Asset>;
activeSponsor: Maybe<Scalars['Boolean']>;
exclusive: Maybe<Scalars['Boolean']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/sponsor) */
export type SponsorLinkedFromArgs = {
allowedLocales: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/sponsor) */
export type SponsorNameArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/sponsor) */
export type SponsorCategoryArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/sponsor) */
export type SponsorUrlArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/sponsor) */
export type SponsorLogoArgs = {
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/sponsor) */
export type SponsorActiveSponsorArgs = {
locale: Maybe<Scalars['String']>;
};
/** [See type definition](https://app.contentful.com/spaces/z273njukdgu1/content_types/sponsor) */
export type SponsorExclusiveArgs = {
locale: Maybe<Scalars['String']>;
};
export type SponsorCollection = {
total: Scalars['Int'];
skip: Scalars['Int'];
limit: Scalars['Int'];
items: Array<Maybe<Sponsor>>;
};
export type SponsorFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
name_exists: Maybe<Scalars['Boolean']>;
name: Maybe<Scalars['String']>;
name_not: Maybe<Scalars['String']>;
name_in: Maybe<Array<Maybe<Scalars['String']>>>;
name_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
name_contains: Maybe<Scalars['String']>;
name_not_contains: Maybe<Scalars['String']>;
category_exists: Maybe<Scalars['Boolean']>;
category: Maybe<Scalars['String']>;
category_not: Maybe<Scalars['String']>;
category_in: Maybe<Array<Maybe<Scalars['String']>>>;
category_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
category_contains: Maybe<Scalars['String']>;
category_not_contains: Maybe<Scalars['String']>;
url_exists: Maybe<Scalars['Boolean']>;
url: Maybe<Scalars['String']>;
url_not: Maybe<Scalars['String']>;
url_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_contains: Maybe<Scalars['String']>;
url_not_contains: Maybe<Scalars['String']>;
logo_exists: Maybe<Scalars['Boolean']>;
activeSponsor_exists: Maybe<Scalars['Boolean']>;
activeSponsor: Maybe<Scalars['Boolean']>;
activeSponsor_not: Maybe<Scalars['Boolean']>;
exclusive_exists: Maybe<Scalars['Boolean']>;
exclusive: Maybe<Scalars['Boolean']>;
exclusive_not: Maybe<Scalars['Boolean']>;
OR: Maybe<Array<Maybe<SponsorFilter>>>;
AND: Maybe<Array<Maybe<SponsorFilter>>>;
};
export type SponsorLinkingCollections = {
entryCollection: Maybe<EntryCollection>;
};
export type SponsorLinkingCollectionsEntryCollectionArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
preview: Maybe<Scalars['Boolean']>;
locale: Maybe<Scalars['String']>;
};
export enum SponsorOrder {
NameAsc = 'name_ASC',
NameDesc = 'name_DESC',
CategoryAsc = 'category_ASC',
CategoryDesc = 'category_DESC',
UrlAsc = 'url_ASC',
UrlDesc = 'url_DESC',
ActiveSponsorAsc = 'activeSponsor_ASC',
ActiveSponsorDesc = 'activeSponsor_DESC',
ExclusiveAsc = 'exclusive_ASC',
ExclusiveDesc = 'exclusive_DESC',
SysIdAsc = 'sys_id_ASC',
SysIdDesc = 'sys_id_DESC',
SysPublishedAtAsc = 'sys_publishedAt_ASC',
SysPublishedAtDesc = 'sys_publishedAt_DESC',
SysFirstPublishedAtAsc = 'sys_firstPublishedAt_ASC',
SysFirstPublishedAtDesc = 'sys_firstPublishedAt_DESC',
SysPublishedVersionAsc = 'sys_publishedVersion_ASC',
SysPublishedVersionDesc = 'sys_publishedVersion_DESC'
}
export type Sys = {
id: Scalars['String'];
spaceId: Scalars['String'];
environmentId: Scalars['String'];
publishedAt: Maybe<Scalars['DateTime']>;
firstPublishedAt: Maybe<Scalars['DateTime']>;
publishedVersion: Maybe<Scalars['Int']>;
};
export type SysFilter = {
id_exists: Maybe<Scalars['Boolean']>;
id: Maybe<Scalars['String']>;
id_not: Maybe<Scalars['String']>;
id_in: Maybe<Array<Maybe<Scalars['String']>>>;
id_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
id_contains: Maybe<Scalars['String']>;
id_not_contains: Maybe<Scalars['String']>;
publishedAt_exists: Maybe<Scalars['Boolean']>;
publishedAt: Maybe<Scalars['DateTime']>;
publishedAt_not: Maybe<Scalars['DateTime']>;
publishedAt_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
publishedAt_not_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
publishedAt_gt: Maybe<Scalars['DateTime']>;
publishedAt_gte: Maybe<Scalars['DateTime']>;
publishedAt_lt: Maybe<Scalars['DateTime']>;
publishedAt_lte: Maybe<Scalars['DateTime']>;
firstPublishedAt_exists: Maybe<Scalars['Boolean']>;
firstPublishedAt: Maybe<Scalars['DateTime']>;
firstPublishedAt_not: Maybe<Scalars['DateTime']>;
firstPublishedAt_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
firstPublishedAt_not_in: Maybe<Array<Maybe<Scalars['DateTime']>>>;
firstPublishedAt_gt: Maybe<Scalars['DateTime']>;
firstPublishedAt_gte: Maybe<Scalars['DateTime']>;
firstPublishedAt_lt: Maybe<Scalars['DateTime']>;
firstPublishedAt_lte: Maybe<Scalars['DateTime']>;
publishedVersion_exists: Maybe<Scalars['Boolean']>;
publishedVersion: Maybe<Scalars['Float']>;
publishedVersion_not: Maybe<Scalars['Float']>;
publishedVersion_in: Maybe<Array<Maybe<Scalars['Float']>>>;
publishedVersion_not_in: Maybe<Array<Maybe<Scalars['Float']>>>;
publishedVersion_gt: Maybe<Scalars['Float']>;
publishedVersion_gte: Maybe<Scalars['Float']>;
publishedVersion_lt: Maybe<Scalars['Float']>;
publishedVersion_lte: Maybe<Scalars['Float']>;
};
export type CfSpeakerNestedFilter = {
sys: Maybe<SysFilter>;
contentfulMetadata: Maybe<ContentfulMetadataFilter>;
avatar_exists: Maybe<Scalars['Boolean']>;
name_exists: Maybe<Scalars['Boolean']>;
name: Maybe<Scalars['String']>;
name_not: Maybe<Scalars['String']>;
name_in: Maybe<Array<Maybe<Scalars['String']>>>;
name_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
name_contains: Maybe<Scalars['String']>;
name_not_contains: Maybe<Scalars['String']>;
jobTitle_exists: Maybe<Scalars['Boolean']>;
jobTitle: Maybe<Scalars['String']>;
jobTitle_not: Maybe<Scalars['String']>;
jobTitle_in: Maybe<Array<Maybe<Scalars['String']>>>;
jobTitle_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
jobTitle_contains: Maybe<Scalars['String']>;
jobTitle_not_contains: Maybe<Scalars['String']>;
employer_exists: Maybe<Scalars['Boolean']>;
employer: Maybe<Scalars['String']>;
employer_not: Maybe<Scalars['String']>;
employer_in: Maybe<Array<Maybe<Scalars['String']>>>;
employer_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
employer_contains: Maybe<Scalars['String']>;
employer_not_contains: Maybe<Scalars['String']>;
showEmployer_exists: Maybe<Scalars['Boolean']>;
showEmployer: Maybe<Scalars['Boolean']>;
showEmployer_not: Maybe<Scalars['Boolean']>;
url_exists: Maybe<Scalars['Boolean']>;
url: Maybe<Scalars['String']>;
url_not: Maybe<Scalars['String']>;
url_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_not_in: Maybe<Array<Maybe<Scalars['String']>>>;
url_contains: Maybe<Scalars['String']>;
url_not_contains: Maybe<Scalars['String']>;
OR: Maybe<Array<Maybe<CfSpeakerNestedFilter>>>;
AND: Maybe<Array<Maybe<CfSpeakerNestedFilter>>>;
};
export const EventMetadataFragmentDoc = /*#__PURE__*/ gql`
fragment EventMetadata on Event {
poster {
url
}
title
slug
description
category
startingDate
onlineEvent
location
url
quota
notes
}
`;
export const RecentEventMetadataFragmentDoc = /*#__PURE__*/ gql`
fragment RecentEventMetadata on Event {
...EventMetadata
sessionsCollection {
items {
sys {
id
}
speaker {
avatar {
url
}
name
}
}
}
}
${EventMetadataFragmentDoc}`;
export const SponsorMetadataFragmentDoc = /*#__PURE__*/ gql`
fragment SponsorMetadata on Sponsor {
name
category
url
activeSponsor
logo {
url
}
sys {
id
}
}
`;
export const EventsPageQueryDocument = /*#__PURE__*/ gql`
query eventsPageQuery($locale: String!) {
eventCollection(limit: 50, locale: $locale, order: startingDate_DESC) {
items {
...EventMetadata
sessionsCollection(limit: 50) {
items {
sys {
id
}
speaker {
avatar {
url
}
name
}
}
}
}
}
}
${EventMetadataFragmentDoc}`;
export const HomePageQueryDocument = /*#__PURE__*/ gql`
query homePageQuery($locale: String!) {
eventCollection(limit: 3, locale: $locale, order: startingDate_DESC) {
items {
...RecentEventMetadata
}
}
sponsorCollection(order: name_ASC) {
items {
...SponsorMetadata
}
}
}
${RecentEventMetadataFragmentDoc}
${EventMetadataFragmentDoc}
${SponsorMetadataFragmentDoc}`;
export type SdkFunctionWrapper = <T>(action: (requestHeaders?:Record<string, string>) => Promise<T>, operationName: string) => Promise<T>;
const defaultWrapper: SdkFunctionWrapper = (action, _operationName) => action();
export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {
return {
eventsPageQuery(variables: EventsPageQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<EventsPageQuery> {
return withWrapper((wrappedRequestHeaders) => client.request<EventsPageQuery>(EventsPageQueryDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'eventsPageQuery');
},
homePageQuery(variables: HomePageQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<HomePageQuery> {
return withWrapper((wrappedRequestHeaders) => client.request<HomePageQuery>(HomePageQueryDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'homePageQuery');
}
};
}
export type Sdk = ReturnType<typeof getSdk>;
export type EventsPageQueryVariables = Exact<{
locale: Scalars['String'];
}>;
export type EventsPageQuery = { eventCollection: Maybe<{ items: Array<Maybe<(
{ sessionsCollection: Maybe<{ items: Array<Maybe<{ sys: Pick<Sys, 'id'>, speaker: Maybe<(
Pick<Speaker, 'name'>
& { avatar: Maybe<Pick<Asset, 'url'>> }
)> }>> }> }
& EventMetadataFragment
)>> }> };
export type EventMetadataFragment = (
Pick<Event, 'title' | 'slug' | 'description' | 'category' | 'startingDate' | 'onlineEvent' | 'location' | 'url' | 'quota' | 'notes'>
& { poster: Maybe<Pick<Asset, 'url'>> }
);
export type RecentEventMetadataFragment = (
{ sessionsCollection: Maybe<{ items: Array<Maybe<{ sys: Pick<Sys, 'id'>, speaker: Maybe<(
Pick<Speaker, 'name'>
& { avatar: Maybe<Pick<Asset, 'url'>> }
)> }>> }> }
& EventMetadataFragment
);
export type SponsorMetadataFragment = (
Pick<Sponsor, 'name' | 'category' | 'url' | 'activeSponsor'>
& { logo: Maybe<Pick<Asset, 'url'>>, sys: Pick<Sys, 'id'> }
);
export type HomePageQueryVariables = Exact<{
locale: Scalars['String'];
}>;
export type HomePageQuery = { eventCollection: Maybe<{ items: Array<Maybe<RecentEventMetadataFragment>> }>, sponsorCollection: Maybe<{ items: Array<Maybe<SponsorMetadataFragment>> }> }; | the_stack |
module TS { // TypeSystem
import TSO = TypeSystemObserver;
//////////////////////// Additional ////////////////////////
export interface StaticResult {
varType: TS.Type
}
export class RValueOfType implements StaticResult {
constructor(public varType: TS.Type) { }
}
export class LValueOfType extends RValueOfType { }
export function rValue(type: TS.Type): RValueOfType { return new RValueOfType(type); }
export function lValue(type: TS.Type): LValueOfType { return new LValueOfType(type); }
export class EnclosedValue extends L.IDeclaration {
constructor(public name: string, private value: TS.Obj) {
super(name);
this.value = value.getCopy();
}
expectsType: TS.StaticResult = null;
*createTempValue(environment: Memory.Environment): IterableIterator<L.Operation> {
environment.pushTempValue(this.value.getCopy());
yield Operation.memory(this);
return;
}
*instantiate(environment: Memory.Environment): IterableIterator<L.Operation> {
environment.addValueToStack(environment.popTempValue().getValue(), this.name);
return;
}
*execute(environment: Memory.Environment): IterableIterator<L.Operation> {
yield* this.createTempValue(environment);
yield* this.instantiate(environment);
yield Operation.memory(this);
return;
}
}
export class ImplicitDeclaration extends L.IDeclaration {
constructor(public name: string, public expectsType: TS.StaticResult, private prototype: Prototype) {
super(name);
}
*createTempValue(environment: Memory.Environment): IterableIterator<L.Operation> {
if (this.expectsType instanceof RValueOfType) {
environment.pushTempValue(this.prototype.defaultValue());
}
else {
throw 'Cannot declare alias. Alias field has to be defined as well.';
}
return;
}
*instantiate(environment: Memory.Environment): IterableIterator<L.Operation> {
if (this.expectsType instanceof RValueOfType) {
environment.addValueToStack(environment.popTempValue().getValue().getCopy(), this.name);
}
else {
environment.addAliasToStack(environment.popTempValue(), this.name);
}
return;
}
*execute(environment: Memory.Environment): IterableIterator<L.Operation> {
yield* this.createTempValue(environment);
yield* this.instantiate(environment);
yield Operation.memory(this);
return;
}
}
//////////////////////// Objects ////////////////////////
export class Obj {
observer: TSO.ObjectObserver;
public getCopy(): Obj { return new Obj(); }
}
export class Type {
getTypeName(): string {
return "";
}
assignalbeTo(second: Type): boolean {
return false;
}
}
export class Instance extends Obj {
constructor(public prototype: Prototype) {
super();
}
public hasMethod(name: string): boolean {
return this.prototype.functions[name] != null;
}
public getMethod(thisField: Memory.MemoryField, name: string, alaisedThis: boolean): FunctionObject {
return new Method(thisField, this.prototype.functions[name], alaisedThis);
}
public getCopy(): Obj { return this.prototype.defaultValue(); }
public *construct(environment: Memory.Environment): IterableIterator<L.Operation> {
return;
}
}
export class InstanceType extends Type {
constructor(public prototypeType: PrototypeType) {
super();
}
hasMethod(name: string): boolean {
return this.prototypeType.hasMethod(name);
}
getTypeName(): string {
return this.prototypeType.instanceName;
}
}
export class Prototype extends Obj {
observer = new TSO.PrototypeObserver(this);
constructor(
public functions: { [name: string]: FunctionObject }
) {
super();
}
public getCopy(): Prototype {
return new Prototype(this.functions);
}
defaultValue(): Instance {
return new Instance(this);
}
}
export class PrototypeType extends Type {
constructor(
public instanceName: string,
public functions: { [name: string]: FunctionClassType }
) {
super();
}
hasMethod(name: string): boolean {
return this.functions[name] != null;
}
declaresType(): InstanceType {
return new InstanceType(this);
}
getTypeName(): string {
return 'type ' + this.instanceName;
}
}
export class ClassField extends Memory.MemoryField implements DS.INamed {
observer = new TSO.ClassFieldObserver(this);
constructor(public declaration: L.IDeclaration, public name: string) {
super();
}
}
export class ClassFieldType {
constructor(
public name: string,
public typ: Type)
{ }
}
//export class FunctionParapeter extends Memory.MemoryField implements DataStructures.INamed {
// observer = new TSO.ClassFieldObserver(this);
// constructor(public declaration: L.IDeclaration, public name: string) {
// super();
// }
//}
export class FunctionParapeterType {
constructor(
public name: string,
public paramType: StaticResult,
public hasDefaultValue: boolean)
{ }
}
export class Class extends Prototype {
constructor(
public classType: ClassType,
public fields: { [name: string]: ClassField },
functions: { [name: string]: FunctionObject }
) {
super(functions);
}
public getCopy(): Class {
return new Class(this.classType, this.fields, this.functions);
}
defaultValue(): Instance {
return new ClassObject(this);
}
}
export class ClassType extends PrototypeType {
constructor(
public fields: { [name: string]: ClassFieldType },
functions: { [name: string]: FunctionClassType },
className: string
) {
super(className, functions);
}
hasField(name: string): boolean {
return this.fields[name] != null;
}
declaresType(): ClassObjectType {
return new ClassObjectType(this);
}
}
export class BaseClass extends Class {
constructor(
classType: ClassType,
functions: { [name: string]: FunctionObject }) {
super(classType, {}, functions);
}
getObjectOfValue(value: any): BaseClassObject {
return new BaseClassObject(this, value);
}
}
export class ClassObjectField extends Memory.MemoryField implements DS.INamed {
observer = new TSO.ClassFieldObserver(this);
constructor(value: Obj, public name: string) {
super();
this.setValue(value);
}
}
export class ClassObject extends Instance {
observer: TSO.ObjectObserver = new TSO.ClassObjectObserver(this);
fields: { [id: string]: ClassObjectField } = {};
constructor(
public prototype: Class) {
super(prototype);
}
public *construct(environment: Memory.Environment): IterableIterator<L.Operation> {
var classFields = this.prototype.fields;
for (var name in classFields) {
var classField = classFields[name];
var declaration = classField.declaration;
yield* declaration.createTempValue(environment);
var value = environment.popTempValue().getValue();
this.fields[name] = new ClassObjectField(
value,
classField.name
);
}
return;
}
public getCopy(): ClassObject { // TODO: copy also actual values
var newObject = new ClassObject(
this.prototype);
var fields = this.prototype.fields;
for (var fieldName in this.fields) {
var field = this.fields[fieldName];
newObject.fields[fieldName] = new ClassObjectField(
field.getValue().getCopy(),
field.name
);
}
return newObject;
}
public hasFieldValue(name: string): boolean {
return this.fields[name] != null;
}
public getFieldValue(name: string): Memory.MemoryField {
return this.fields[name];
}
}
export class ClassObjectType extends InstanceType {
constructor(
public prototypeType: ClassType
) { super(prototypeType); }
assignalbeTo(second: InstanceType): boolean {
return (second instanceof ClassObjectType) && (this.prototypeType == second.prototypeType);
}
}
export class VoidObject extends ClassObject {
observer = new TSO.VoidObjectObserver(this);
constructor(public prototye: Class) {
super(prototye);
}
public getCopy(): VoidObject {
return new VoidObject(this.prototye);
}
}
export class BaseClassObject extends ClassObject {
observer = new TSO.BaseClassObjectObserver(this);
constructor(public prototye: BaseClass, public rawValue) {
super(prototye);
}
public getCopy(): BaseClassObject {
return new BaseClassObject(this.prototye, this.rawValue);
}
}
export class FunctionClass extends Prototype {
constructor() {
super({});
}
}
export class FunctionClassType extends PrototypeType {
constructor(
public parameters: FunctionParapeterType[],
public returnType: StaticResult
) {
super('(' + parameters.map(e => e.paramType.varType.getTypeName()).join(', ') + ') => ' + returnType.varType.getTypeName(), {});
}
declaresType(): FunctionType {
return new FunctionType(this);
}
}
export class FunctionObject extends Instance {
observer = new TSO.FunctionObserver(this);
*call(environment: Memory.Environment, passedArguments: number): IterableIterator<L.Operation> {
environment.addScope('Function Call');
for (var i = 0; i < this.closure.length; i++) {
var enclosedValue = this.closure[i];
yield* enclosedValue.execute(environment);
}
for (var i = 0; i < this.parameters.length; i++) {
yield* this.parameters[i].instantiate(environment);
}
yield* this.behaviour(environment);
environment.removeScope();
return;
}
constructor(
public prototype: FunctionClass,
public parameters: L.IDeclaration[],
public behaviour: (environment: Memory.Environment) => IterableIterator<L.Operation>,
public closure: L.IDeclaration[] = [])
{ super(prototype); }
public getCopy(): FunctionObject {
return new FunctionObject(this.prototype, this.parameters, this.behaviour, this.closure);
}
}
export class FunctionType extends InstanceType {
constructor(
public prototypeType: FunctionClassType
) { super(prototypeType); }
}
export class Method extends FunctionObject {
constructor(
thisField: Memory.MemoryField,
baseFunction: FunctionObject,
alaisedThis: boolean
) {
var thisValue = alaisedThis ? null : thisField.getValue().getCopy();
super(
baseFunction.prototype,
baseFunction.parameters,
alaisedThis ?
function* (environment: Memory.Environment) {
environment.addAliasToStack(
thisField,
'this'
);
yield* baseFunction.behaviour(environment);
}
:
function* (environment: Memory.Environment) {
environment.addValueToStack(
thisValue.getCopy(),
'this'
);
yield* baseFunction.behaviour(environment);
},
baseFunction.closure
);
}
}
export class ArrayClass extends Prototype {
constructor(
public elementsClass: Prototype,
public length: number
) {
super({});
}
defaultValue(): Instance {
return new ArrayObject(this);
}
}
export class ArrayClassType extends PrototypeType {
constructor(
public elementsClass: PrototypeType
) {
super(elementsClass.declaresType().getTypeName() + '[]', {});
}
declaresType(): ArrayType {
return new ArrayType(this);
}
}
export class ArrayOfLengthClassType extends ArrayClassType {
constructor(
elementsClass: PrototypeType,
public length: number
) {
super(elementsClass);
}
declaresType(): ArrayType {
return new ArrayType(this);
}
}
export class ArrayField extends Memory.MemoryField {
observer = new TSO.ArrayFieldObserver(this);
constructor(value: TS.Obj, public index: number) {
super();
this.setValue(value);
}
}
export class ArrayObject extends Instance {
observer: TSO.ArrayObjectObserver = new TSO.ArrayObjectObserver(this);
values: ArrayField[];
constructor(
public prototype: ArrayClass
) {
super(prototype);
this.values = [];
for (var i = 0; i < prototype.length; i++) {
var memoryField = new ArrayField(prototype.elementsClass.defaultValue(), i);
this.values[i] = memoryField;
}
}
public getField(index: number): Memory.MemoryField {
return this.values[index];
}
public getCopy(): ArrayObject { // TODO: copy also actual values
var newObject = new ArrayObject(this.prototype);
for (var i = 0; i < this.prototype.length; i++) {
newObject.getField(i).setValue(this.values[i].getValue().getCopy());
}
return newObject;
}
public *construct(environment: Memory.Environment): IterableIterator<L.Operation> {
for (var i = 0; i < this.prototype.length; i++)
yield* (<TS.Instance>this.values[i].getValue()).construct(environment);
return;
}
}
export class ArrayType extends InstanceType {
constructor(
public prototypeType: ArrayClassType
) { super(prototypeType); }
assignalbeTo(second: Type): boolean {
if (!(second instanceof ArrayType))
return false;
return this.prototypeType.elementsClass.declaresType().assignalbeTo((<ArrayType>second).prototypeType.elementsClass.declaresType());
}
}
export class ReferenceClassType extends PrototypeType {
constructor(public referencedPrototypeType: PrototypeType) {
super(referencedPrototypeType.instanceName + ' ref', {});
this.functions['=='] = new FunctionClassType([
new FunctionParapeterType('b', rValue(this.declaresType()), false)
], rValue(TS.Boolean.objectTypeInstance));
this.functions['!='] = new FunctionClassType([
new FunctionParapeterType('b', rValue(this.declaresType()), false)
], rValue(TS.Boolean.objectTypeInstance));
}
declaresType(): ReferenceType {
return new ReferenceType(this);
}
}
export class ReferenceType extends InstanceType {
constructor(
public prototypeType: ReferenceClassType
) { super(prototypeType); }
assignalbeTo(second: InstanceType): boolean {
if (!(second instanceof ReferenceType))
return false;
var a = this.prototypeType.referencedPrototypeType.declaresType().assignalbeTo((<ReferenceType>second).prototypeType.referencedPrototypeType.declaresType());
var b = this.prototypeType.referencedPrototypeType == Void.typeInstance;
return a || b;
}
}
export class ReferenceClass extends Prototype {
constructor(public referencedPrototype: Prototype) {
super({});
this.functions['=='] = new FunctionObject(
new FunctionClass(),
[
new ImplicitDeclaration('b', rValue(null), Int.classInstance)
],
function* (environment) {
var a = <Reference>environment.getFromStack('this').getValue();
var b = <Reference>environment.getFromStack('b').getValue();
var result = Boolean.classInstance.getObjectOfValue(a.reference == b.reference);
environment.pushTempValue(result);
}
);
this.functions['!='] = new FunctionObject(
new FunctionClass(),
[
new ImplicitDeclaration('b', rValue(null), Int.classInstance)
],
function* (environment) {
var a = <Reference>environment.getFromStack('this').getValue();
var b = <Reference>environment.getFromStack('b').getValue();
var result = Boolean.classInstance.getObjectOfValue(a.reference != b.reference);
environment.pushTempValue(result);
}
);
}
defaultValue(): Instance {
return new Reference(this, null);
}
}
export class Reference extends Instance {
observer: TSO.ReferenceObserver = new TSO.ReferenceObserver(this);
constructor(
public prototype: ReferenceClass,
public reference: Memory.MemoryField
) {
super(prototype);
if (reference)
reference.referencedBy(this);
}
public getCopy(): Reference {
return new Reference(this.prototype, this.reference);
}
}
export class Alias extends Reference {
observer: TSO.AliasObserver = new TSO.AliasObserver(this);
}
//////////////////////// Types ////////////////////////
export class Void extends Class {
static typeInstance: ClassType = null;
static objectTypeInstance: ClassObjectType = null;
static classInstance: Void = null;
private static initialized = false;
static initialize() {
if (!Void.initialized) {
var typeInstance: ClassType = new ClassType({}, {}, 'void');
var objectTypeInstance = new ClassObjectType(typeInstance);
typeInstance.functions = {};
var classInstance: Void = new Void(
typeInstance,
{}, {});
this.typeInstance = typeInstance;
this.objectTypeInstance = objectTypeInstance;
this.classInstance = classInstance;
Void.initialized = true;
}
}
defaultValue(): ClassObject {
return new VoidObject(this);
}
}
Void.initialize();
// Built in types
function _base_typeToTypeMethodType(type: Type, returns: Type): FunctionClassType {
return new FunctionClassType([
new FunctionParapeterType('b', rValue(type), false)
], rValue(returns));
}
function _base_typeToTypeMethodOperation(operation: (a, b) => any, alocator: BaseClass) {
return new FunctionObject(
new FunctionClass(),
[
new ImplicitDeclaration('b', rValue(null), null)
],
function* (environment) {
var a = <BaseClassObject>environment.getFromStack('this').getValue();
var b = <BaseClassObject>environment.getFromStack('b').getValue();
environment.pushTempValue(alocator.getObjectOfValue(operation(a.rawValue, b.rawValue)));
});
}
function _base_toTypeMethodType(returns: Type): FunctionClassType {
return new FunctionClassType([
], rValue(returns));
}
function _base_toTypeMethodOperation(operation: (a) => any, alocator: BaseClass): FunctionObject {
return new FunctionObject(
new FunctionClass(),
[],
function* (environment) {
var a = <BaseClassObject>environment.getFromStack('this').getValue();
environment.pushTempValue(alocator.getObjectOfValue(operation(a.rawValue)));
});
}
function _base_printMethod(formatter = (a) => a): FunctionObject {
return new FunctionObject(
new FunctionClass(),
[],
function* (environment) {
var a = <BaseClassObject>environment.getFromStack('this').getValue();
GUI.getConsole().print(formatter(a.rawValue));
});
}
function _base_scanMethod(formatter = (a) => a): FunctionObject {
return new FunctionObject(
new FunctionClass(),
[],
function* (environment) {
var a = <BaseClassObject>environment.getFromStack('this').getValue();
environment.removeScope();
var buffer = BufferManager.getBuffer();
while (!buffer.hasConsoleInput()) {
buffer.requestConsoleInput();
yield Operation.wait();
}
var message = buffer.getConsoleInput();
environment.addScope('');
a.rawValue = formatter(message);
a.observer.updateUI();
});
}
export class Boolean extends BaseClass {
static typeInstance: ClassType = null;
static objectTypeInstance: ClassObjectType = null;
static classInstance: Boolean = null;
private static initialized = false;
static initialize() {
if (!Boolean.initialized) {
var typeInstance: ClassType = new ClassType({}, {}, 'boolean');
var objectTypeInstance: ClassObjectType = new ClassObjectType(typeInstance);
var classInstance: Boolean = new Boolean(typeInstance, {});
var _boolToBoolType = _base_typeToTypeMethodType(objectTypeInstance, objectTypeInstance);
var _toBoolType = _base_toTypeMethodType(objectTypeInstance);
var _toVoidType = _base_toTypeMethodType(Void.objectTypeInstance);
typeInstance.functions = {
'&&': _boolToBoolType,
'||': _boolToBoolType,
'!': _toBoolType,
'print': _toVoidType,
'scan': _toVoidType
};
classInstance.functions['&&'] = _base_typeToTypeMethodOperation((a, b) => a && b, classInstance);
classInstance.functions['||'] = _base_typeToTypeMethodOperation((a, b) => a || b, classInstance);
classInstance.functions['!'] = _base_toTypeMethodOperation((a) => !a, classInstance);
classInstance.functions['print'] = _base_printMethod((a) => {
return a ? 'true' : 'false';
});
classInstance.functions['scan'] = _base_scanMethod((a) => {
return a && a != 'false' && a != 'False';
});
this.typeInstance = typeInstance;
this.objectTypeInstance = objectTypeInstance;
this.classInstance = classInstance;
Boolean.initialized = true;
}
}
getObjectOfValue(value: boolean): BaseClassObject {
return new BaseClassObject(this, value);
}
defaultValue(): Instance {
return this.getObjectOfValue(false);
}
}
Boolean.initialize();
export class Int extends BaseClass {
static typeInstance: ClassType = null;
static objectTypeInstance: ClassObjectType = null;
static classInstance: Int = null;
private static initialized = false;
static initialize() {
if (!Int.initialized) {
var typeInstance: ClassType = new ClassType({}, {}, 'number');
var objectTypeInstance: ClassObjectType = new ClassObjectType(typeInstance);
var classInstance: Int = new Int(typeInstance, {});
var _intToIntType = _base_typeToTypeMethodType(objectTypeInstance, objectTypeInstance);
var _intToBooleanType = _base_typeToTypeMethodType(objectTypeInstance, Boolean.objectTypeInstance);
var _toIntType = _base_toTypeMethodType(objectTypeInstance);
var _toVoidType = _base_toTypeMethodType(Void.objectTypeInstance);
typeInstance.functions = {
'+': _intToIntType,
'-': _intToIntType,
'*': _intToIntType,
'/': _intToIntType,
'%': _intToIntType,
'==': _intToBooleanType,
'!=': _intToBooleanType,
'<': _intToBooleanType,
'<=': _intToBooleanType,
'>': _intToBooleanType,
'>=': _intToBooleanType,
'print': _toVoidType,
'scan': _toVoidType,
'++': _toIntType,
'--': _toIntType,
'_++': _toIntType,
'_--': _toIntType
};
classInstance.functions['+'] = _base_typeToTypeMethodOperation((a, b) => a + b, classInstance);
classInstance.functions['-'] = _base_typeToTypeMethodOperation((a, b) => a - b, classInstance);
classInstance.functions['*'] = _base_typeToTypeMethodOperation((a, b) => a * b, classInstance);
classInstance.functions['/'] = _base_typeToTypeMethodOperation((a, b) => a / b, classInstance);
classInstance.functions['%'] = _base_typeToTypeMethodOperation((a, b) => a % b, classInstance);
classInstance.functions['=='] = _base_typeToTypeMethodOperation((a, b) => a == b, Boolean.classInstance);
classInstance.functions['!='] = _base_typeToTypeMethodOperation((a, b) => a != b, Boolean.classInstance);
classInstance.functions['<'] = _base_typeToTypeMethodOperation((a, b) => a < b, Boolean.classInstance);
classInstance.functions['<='] = _base_typeToTypeMethodOperation((a, b) => a <= b, Boolean.classInstance);
classInstance.functions['>'] = _base_typeToTypeMethodOperation((a, b) => a > b, Boolean.classInstance);
classInstance.functions['>='] = _base_typeToTypeMethodOperation((a, b) => a >= b, Boolean.classInstance);
classInstance.functions['print'] = _base_printMethod();
classInstance.functions['scan'] = _base_scanMethod((a) => {
var numberValue = parseInt(a);
if (isNaN(numberValue))
numberValue = 0;
return numberValue;
});
classInstance.functions['++'] = new FunctionObject(
new FunctionClass(),
[],
function* (environment) {
var a = <BaseClassObject>environment.getFromStack('this').getValue();
a.rawValue++;
environment.pushTempValue(classInstance.getObjectOfValue(a.rawValue));
a.observer.updateUI();
});
classInstance.functions['--'] = new FunctionObject(
new FunctionClass(),
[],
function* (environment) {
var a = <BaseClassObject>environment.getFromStack('this').getValue();
a.rawValue--;
environment.pushTempValue(classInstance.getObjectOfValue(a.rawValue));
a.observer.updateUI();
});
classInstance.functions['_++'] = new FunctionObject(
new FunctionClass(),
[],
function* (environment) {
var a = <BaseClassObject>environment.getFromStack('this').getValue();
environment.pushTempValue(classInstance.getObjectOfValue(a.rawValue));
a.rawValue++;
a.observer.updateUI();
});
classInstance.functions['_--'] = new FunctionObject(
new FunctionClass(),
[],
function* (environment) {
var a = <BaseClassObject>environment.getFromStack('this').getValue();
environment.pushTempValue(classInstance.getObjectOfValue(a.rawValue));
a.rawValue--;
a.observer.updateUI();
});
this.typeInstance = typeInstance;
this.objectTypeInstance = objectTypeInstance;
this.classInstance = classInstance;
Int.initialized = true;
}
}
getObjectOfValue(value: number): BaseClassObject {
return new BaseClassObject(this, value);
}
defaultValue(): Instance {
return this.getObjectOfValue(0);
}
}
Int.initialize();
export class String extends BaseClass {
static typeInstance: ClassType = null;
static objectTypeInstance: ClassObjectType = null;
static classInstance: String = null;
private static initialized = false;
static initialize() {
if (!String.initialized) {
var typeInstance: ClassType = new ClassType({}, {}, 'string');
var objectTypeInstance: ClassObjectType = new ClassObjectType(typeInstance);
var classInstance: String = new String(typeInstance, {});
var _stringToStringType = _base_typeToTypeMethodType(objectTypeInstance, objectTypeInstance);
var _toIntType = _base_toTypeMethodType(Int.objectTypeInstance);
var _toVoidType = _base_toTypeMethodType(Void.objectTypeInstance);
typeInstance.functions = {
'+': _stringToStringType,
'length': _toIntType,
'print': _toVoidType,
'scan': _toVoidType
};
classInstance.functions['+'] = _base_typeToTypeMethodOperation((a, b) => a + b, classInstance);
classInstance.functions['length'] = _base_toTypeMethodOperation((a) => a.length, Int.classInstance);
classInstance.functions['print'] = _base_printMethod();
classInstance.functions['scan'] = _base_scanMethod();
this.typeInstance = typeInstance;
this.objectTypeInstance = objectTypeInstance;
this.classInstance = classInstance;
String.initialized = true;
}
}
getObjectOfValue(value: string): BaseClassObject {
return new BaseClassObject(this, value);
}
defaultValue(): Instance {
return this.getObjectOfValue("");
}
}
String.initialize();
} | the_stack |
import "minimal-polyfills/Array.prototype.find";
import { importProxy } from "./importProxy";
import { create } from "./Evt.create";
import { getCtxFactory } from "./Evt.getCtx";
import { factorize } from "./Evt.factorize";
import { merge } from "./Evt.merge";
import { from } from "./Evt.from";
import { useEffect } from "./Evt.useEffect";
import { asPostable } from "./Evt.asPostable";
import { asyncPipe } from "./Evt.asyncPipe";
import { asNonPostable } from "./Evt.asNonPostable";
import { parsePropsFromArgs, matchAll } from "./Evt.parsePropsFromArgs";
import { newCtx } from "./Evt.newCtx";
import { LazyEvt } from "./LazyEvt";
import { defineAccessors } from "../tools/typeSafety/defineAccessors";
import { invokeOperator } from "./util/invokeOperator";
import { Polyfill as Map, LightMap } from "minimal-polyfills/Map";
import { Polyfill as WeakMap } from "minimal-polyfills/WeakMap";
import * as runExclusive from "run-exclusive";
import { overwriteReadonlyProp } from "../tools/typeSafety/overwriteReadonlyProp";
import { typeGuard } from "../tools/typeSafety/typeGuard";
import { encapsulateOpState } from "./util/encapsulateOpState";
import { Deferred } from "../tools/Deferred";
import { loosenType } from "./Evt.loosenType";
import { safeClearTimeout, safeSetTimeout, Timer } from "../tools/safeSetTimeout";
import { isPromiseLike } from "../tools/typeSafety/isPromiseLike";
import type { Handler } from "./types/Handler";
import * as _1 from "./types/Operator";
import * as _2 from "./types/EvtError";
import * as _3 from "./types/interfaces/CtxLike";
type NonPostableEvt<T> = import("./types/interfaces").NonPostableEvt<T>;
type StatefulEvt<T> = import("./types/interfaces").StatefulEvt<T>;
/** https://docs.evt.land/api/evt */
export type Evt<T> = import("./types/interfaces").Evt<T>;
class EvtImpl<T> implements Evt<T> {
static readonly create = create;
static readonly newCtx = newCtx;
static readonly merge = merge;
static readonly from = from;
static readonly useEffect = useEffect;
static readonly getCtx = getCtxFactory();
static readonly loosenType = loosenType;
static readonly factorize = factorize;
static readonly asPostable = asPostable;
static readonly asyncPipe = asyncPipe;
static readonly asNonPostable = asNonPostable;
private static __defaultMaxHandlers = 25;
static setDefaultMaxHandlers(n: number): void {
this.__defaultMaxHandlers = isFinite(n) ? n : 0;
}
toStateful(p1: any, p2?: _3.CtxLike): StatefulEvt<any> {
const isP1Ctx = _3.z_3.match(p1);
const initialValue: any = isP1Ctx ? undefined : p1;
const ctx = p2 || (isP1Ctx ? p1 : undefined);
const out = new importProxy.StatefulEvt<any>(initialValue);
const callback = (data: T) => out.post(data);
if (!!ctx) {
this.attach(ctx, callback);
} else {
this.attach(callback);
}
return out;
}
declare readonly evtAttach: Evt<Handler<T, any>>;
declare readonly evtDetach: Evt<Handler<T, any>>;
private readonly lazyEvtAttach = new LazyEvt<Handler<T, any>>();
private readonly lazyEvtDetach = new LazyEvt<Handler<T, any>>();
private static __1: void = (() => {
if (false) { EvtImpl.__1 }
defineAccessors(
EvtImpl.prototype,
"evtAttach",
{
"get": function (this: EvtImpl<any>) {
return this.lazyEvtAttach.evt;
}
}
);
defineAccessors(
EvtImpl.prototype,
"evtDetach",
{
"get": function (this: EvtImpl<any>) {
return this.lazyEvtDetach.evt;
}
}
);
})();
private __maxHandlers: undefined | number = undefined;
setMaxHandlers(n: number): this {
this.__maxHandlers = isFinite(n) ? n : 0;
return this;
}
readonly postCount: number = 0;
private traceId: string | null = null;
private traceFormatter!: (data: T) => string;
private log!: Exclude<Parameters<NonPostableEvt<any>["enableTrace"]>[0]["log"], false>;
enableTrace(
params: {
id: string,
formatter?: (data: T) => string,
log?: ((message?: any, ...optionalParams: any[]) => void) | false
}
//NOTE: Not typeof console.log as we don't want to expose types from node
): void {
const { id, formatter, log } = params;
this.traceId = id;
this.traceFormatter = formatter || (
data => {
try {
return JSON.stringify(data, null, 2);
} catch {
return `${data}`;
}
}
);
this.log =
log === undefined ?
((...inputs) => console.log(...inputs)) :
log === false ? undefined : log
;
}
disableTrace(): this {
this.traceId = null;
return this;
}
private readonly handlers: Handler<T, any>[] = [];
private readonly handlerTriggers: LightMap<
Handler<T, any>,
(opResult: _1.Operator.fλ.Result.Matched<any, any>) => PromiseLike<void> | undefined
> = new Map();
//NOTE: An async handler ( attached with waitFor ) is only eligible to handle a post if the post
//occurred after the handler was set. We don't want to waitFor event from the past.
//private readonly asyncHandlerChronologyMark = new WeakMap<ImplicitParams.Async, number>();
declare private readonly asyncHandlerChronologyMark: WeakMap<
Handler.PropsFromMethodName.Async,
number
>;
declare private __asyncHandlerChronologyMark:
(typeof EvtImpl.prototype.asyncHandlerChronologyMark) | undefined;
//NOTE: There is an exception to the above rule, we want to allow async waitFor loop
//do so we have to handle the case where multiple event would be posted synchronously.
declare private readonly asyncHandlerChronologyExceptionRange: WeakMap<
Handler.PropsFromMethodName.Async,
{ lowerMark: number; upperMark: number; }
>;
declare private __asyncHandlerChronologyExceptionRange:
(typeof EvtImpl.prototype.asyncHandlerChronologyExceptionRange) | undefined;
declare private readonly statelessByStatefulOp: WeakMap<
_1.Operator.fλ.Stateful<T, any, any>,
_1.Operator.fλ.Stateless<T, any, any>
>;
declare private __statelessByStatefulOp:
(typeof EvtImpl.prototype.statelessByStatefulOp) | undefined;
private static __2: void = (() => {
if (false) { EvtImpl.__2; }
Object.defineProperties(EvtImpl.prototype,
([
"__asyncHandlerChronologyMark",
"__asyncHandlerChronologyExceptionRange",
"__statelessByStatefulOp"
] as const).map(key => [
key.substr(2),
{
"get": function (this: EvtImpl<any>) {
if (this[key] === undefined) {
this[key] = new WeakMap<any, any>();
}
return this[key];
}
}
] as const).reduce<any>((prev, [key, obj]) => ({ ...prev, [key]: obj }), {})
);
})();
/*
NOTE: Used as Date.now() would be used to compare if an event is anterior
or posterior to an other. We don't use Date.now() because two call within
less than a ms will return the same value unlike this function.
*/
private __currentChronologyMark = 0;
private getChronologyMark() {
return this.__currentChronologyMark++;
}
private asyncHandlerCount: number = 0;
private detachHandler(
handler: Handler<T, any>,
wTimer: [Timer | undefined],
rejectPr: (error: _2.EvtError.Detached) => void
) {
const index = this.handlers.indexOf(handler);
if (index < 0) {
return false;
}
if (typeGuard<Handler<T, any, _3.CtxLike<any>>>(handler, !!handler.ctx)) {
handler.ctx.zz__removeHandler(handler);
}
this.handlers.splice(index, 1);
if (handler.async) {
this.asyncHandlerCount--;
}
this.handlerTriggers.delete(handler);
if (wTimer[0] !== undefined) {
safeClearTimeout(wTimer[0]);
rejectPr(new _2.EvtError.Detached());
}
this.lazyEvtDetach.post(handler);
return true;
}
private triggerHandler<U>(
handler: Handler<T, U>,
wTimer: [Timer | undefined],
resolvePr: ((transformedData: any) => void) | undefined,
opResult: _1.Operator.fλ.Result.Matched<any, any>
): PromiseLike<void> | undefined {
const { callback, once } = handler;
if (wTimer[0] !== undefined) {
safeClearTimeout(wTimer[0]);
wTimer[0] = undefined;
}
doDetachIfNeeded(handler, opResult, once);
const [transformedData] = opResult;
const prOrValue = callback?.call(
this,
transformedData
);
resolvePr?.(transformedData);
return isPromiseLike(prOrValue) ? prOrValue : undefined;
}
private addHandler<U>(
propsFromArgs: Handler.PropsFromArgs<T, U>,
propsFromMethodName: Handler.PropsFromMethodName
): Handler<T, U> {
if (_1.z_f1.fλ_Stateful_match<T, any, any>(propsFromArgs.op)) {
this.statelessByStatefulOp.set(
propsFromArgs.op,
encapsulateOpState(propsFromArgs.op)
);
}
const d = new Deferred<U>();
const wTimer: [Timer | undefined] = [undefined];
const handler: Handler<T, U> = {
...propsFromArgs,
...propsFromMethodName,
"detach": () => this.detachHandler(handler, wTimer, d.reject),
"promise": d.pr
};
if (typeof handler.timeout === "number") {
wTimer[0] = safeSetTimeout(() => {
wTimer[0] = undefined;
handler.detach();
d.reject(new _2.EvtError.Timeout(handler.timeout!));
}, handler.timeout);
}
this.handlerTriggers.set(
handler,
opResult => this.triggerHandler(
handler,
wTimer,
d.isPending ? d.resolve : undefined,
opResult
)
);
if (handler.async) {
this.asyncHandlerChronologyMark.set(
handler,
this.getChronologyMark()
);
}
if (handler.prepend) {
let i: number;
for (i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].extract) {
continue;
}
break;
}
this.handlers.splice(i, 0, handler);
} else {
this.handlers.push(handler);
}
if (handler.async) {
this.asyncHandlerCount++;
}
this.checkForPotentialMemoryLeak();
if (typeGuard<Handler<T, U, _3.CtxLike<any>>>(handler, !!handler.ctx)) {
handler.ctx.zz__addHandler(handler, this);
}
this.lazyEvtAttach.post(handler);
return handler;
}
private checkForPotentialMemoryLeak(): void {
const maxHandlers = this.__maxHandlers !== undefined ?
this.__maxHandlers :
EvtImpl.__defaultMaxHandlers
;
if (
maxHandlers === 0 ||
this.handlers.length % (maxHandlers + 1) !== 0) {
return;
}
let message = [
`MaxHandlersExceededWarning: Possible Evt memory leak detected.`,
`${this.handlers.length} handlers attached${this.traceId ? ` to "${this.traceId}"` : ""}.\n`,
`Use Evt.prototype.setMaxHandlers(n) to increase limit on a specific Evt.\n`,
`Use Evt.setDefaultMaxHandlers(n) to change the default limit currently set to ${EvtImpl.__defaultMaxHandlers}.\n`,
].join("");
const map = new Map<string, number>();
this.getHandlers()
.map(({ ctx, async, once, prepend, extract, op, callback }) => ({
"hasCtx": !!ctx,
once,
prepend,
extract,
"isWaitFor": async,
...(op === matchAll ? {} : { "op": op.toString() }),
...(!callback ? {} : { "callback": callback.toString() })
}))
.map(obj =>
"{\n" + Object.keys(obj)
.map(key => ` ${key}: ${(obj as any)[key]}`)
.join(",\n") + "\n}"
)
.forEach(str => map.set(str, (map.has(str) ? map.get(str)! : 0) + 1))
;
message += "\n" + Array.from(map.keys())
.map(str => `${map.get(str)} handler${map.get(str) === 1 ? "" : "s"} like:\n${str}`)
.join("\n") + "\n";
if (this.traceId === null) {
message += "\n" + [
`To validate the identify of the Evt instance that is triggering this warning you can call`,
`Evt.prototype.enableTrace({ "id": "My evt id", "log": false }) on the Evt that you suspect.\n`
].join(" ");
}
try {
console.warn(message);
} catch {
}
}
getStatelessOp<U, CtxResult>(op: _1.Operator<T, U, CtxResult>): _1.Operator.Stateless<T, U, CtxResult> {
return _1.z_f1.fλ_Stateful_match(op) ?
this.statelessByStatefulOp.get(op)! :
op
}
private trace(data: T) {
if (this.traceId === null) {
return;
}
let message = `(${this.traceId}) `;
const isExtracted = !!this.handlers.find(
({ extract, op }) => (
extract &&
!!this.getStatelessOp(op)(data)
)
);
if (isExtracted) {
message += "extracted ";
} else {
const handlerCount = this.handlers
.filter(
({ extract, op }) => !extract &&
!!this.getStatelessOp(op)(data)
)
.length;
message += `${handlerCount} handler${(handlerCount > 1) ? "s" : ""}, `;
}
this.log?.(message + this.traceFormatter(data));
}
/** Return [ isExtracted, prAllHandlerCallbacksResolved ] */
private postSync(data: T): readonly [boolean, Promise<void>] {
const prAllHandlerCallbacksResolved: PromiseLike<void>[] = [];
const getReturnValue = (isExtracted: boolean) => [
isExtracted,
Promise.all(prAllHandlerCallbacksResolved).then(() => { })
] as const;
for (const handler of [...this.handlers]) {
const { async, op, extract } = handler;
if (async) {
continue;
}
const opResult = invokeOperator(
this.getStatelessOp(op),
data,
true
);
if (_1.z_f1.fλ_Result_NotMatched_match(opResult)) {
doDetachIfNeeded(handler, opResult);
continue;
}
const handlerTrigger = this.handlerTriggers.get(handler);
//NOTE: Possible if detached while in the loop.
if (!handlerTrigger) {
continue;
}
const prOrUndefined = handlerTrigger(opResult);
if (prOrUndefined !== undefined) {
prAllHandlerCallbacksResolved.push(prOrUndefined);
}
if (extract) {
return getReturnValue(true);
}
}
return getReturnValue(false);
}
private postAsyncFactory() {
return runExclusive.buildMethodCb(
(data: T, postChronologyMark: number, releaseLock?) => {
if (this.asyncHandlerCount === 0) {
releaseLock();
return;
}
const promises: Promise<void>[] = [];
let chronologyMarkStartResolveTick: number;
//NOTE: Must be before handlerTrigger call.
Promise.resolve().then(
() => chronologyMarkStartResolveTick = this.getChronologyMark()
);
for (const handler of [...this.handlers]) {
if (!handler.async) {
continue;
}
const opResult = invokeOperator(
this.getStatelessOp(handler.op),
data,
true
);
if (_1.z_f1.fλ_Result_NotMatched_match(opResult)) {
doDetachIfNeeded(handler, opResult);
continue;
}
const handlerTrigger = this.handlerTriggers.get(handler);
if (!handlerTrigger) {
continue;
}
const shouldCallHandlerTrigger = (() => {
const handlerMark = this.asyncHandlerChronologyMark.get(handler)!;
if (postChronologyMark > handlerMark) {
return true;
}
const exceptionRange = this.asyncHandlerChronologyExceptionRange.get(handler);
return (
exceptionRange !== undefined &&
exceptionRange.lowerMark < postChronologyMark &&
postChronologyMark < exceptionRange.upperMark &&
handlerMark > exceptionRange.upperMark
);
})();
if (!shouldCallHandlerTrigger) {
continue;
}
promises.push(
new Promise<void>(
resolve => handler.promise
.then(() => resolve())
.catch(() => resolve())
)
);
handlerTrigger(opResult);
}
if (promises.length === 0) {
releaseLock();
return;
}
const handlersDump = [...this.handlers];
Promise.all(promises).then(() => {
for (const handler of this.handlers) {
if (!handler.async) {
continue;
}
if (handlersDump.indexOf(handler) >= 0) {
continue;
}
this.asyncHandlerChronologyExceptionRange.set(
handler,
{
"lowerMark": postChronologyMark,
"upperMark": chronologyMarkStartResolveTick
}
);
}
releaseLock();
});
}
);
}
declare private postAsync: (
(
data: T,
postChronologyMark: number
) => void
) | undefined;
private static readonly propsFormMethodNames: Record<
"waitFor" | "attach" | "attachExtract" | "attachPrepend" | "attachOnce" |
"attachOncePrepend" | "attachOnceExtract"
,
Handler.PropsFromMethodName
> = {
"waitFor": { "async": true, "extract": false, "once": true, "prepend": false },
"attach": { "async": false, "extract": false, "once": false, "prepend": false },
"attachExtract": { "async": false, "extract": true, "once": false, "prepend": true },
"attachPrepend": { "async": false, "extract": false, "once": false, "prepend": true },
"attachOnce": { "async": false, "extract": false, "once": true, "prepend": false },
"attachOncePrepend": { "async": false, "extract": false, "once": true, "prepend": true },
"attachOnceExtract": { "async": false, "extract": true, "once": true, "prepend": true }
};
isHandled(data: T): boolean {
return !!this.getHandlers()
.find(({ op }) => !!this.getStatelessOp(op)(data))
;
}
getHandlers(): Handler<T, any>[] {
return [...this.handlers];
}
detach(ctx?: _3.CtxLike<any>): Handler<T, any, any>[] {
const detachedHandlers: Handler<T, any>[] = [];
for (const handler of this.getHandlers()) {
if (ctx !== undefined && handler.ctx !== ctx) {
continue;
}
const wasStillAttached = handler.detach();
//NOTE: It should not be possible.
if (!wasStillAttached) {
continue;
}
detachedHandlers.push(handler);
}
return detachedHandlers;
}
pipe(...args: any[]): Evt<any> {
const evtDelegate = new EvtImpl<any>();
this.addHandler(
{
...parsePropsFromArgs<T>(args, "pipe"),
"callback": (transformedData: any) => evtDelegate.post(transformedData)
},
EvtImpl.propsFormMethodNames.attach
);
return evtDelegate;
}
waitFor(...args: any[]): Promise<any> {
return this.addHandler(
parsePropsFromArgs<T>(args, "waitFor"),
EvtImpl.propsFormMethodNames.waitFor
).promise;
}
$attach(...inputs: any[]) {
return (this.attach as any)(...inputs);
}
attach(...args: any[]) {
return this.__attachX(args, "attach");
}
$attachOnce(...inputs: any[]) {
return (this.attachOnce as any)(...inputs);
}
attachOnce(...args: any[]) {
return this.__attachX(args, "attachOnce");
}
$attachExtract(...inputs: any[]) {
return (this.attachExtract as any)(...inputs);
}
attachExtract(...args: any[]) {
return this.__attachX(args, "attachExtract");
}
$attachPrepend(...inputs: any[]) {
return (this.attachPrepend as any)(...inputs);
}
attachPrepend(...args: any[]) {
return this.__attachX(args, "attachPrepend");
}
$attachOncePrepend(...inputs: any[]) {
return (this.attachOncePrepend as any)(...inputs);
}
attachOncePrepend(...args: any[]) {
return this.__attachX(args, "attachOncePrepend");
}
$attachOnceExtract(...inputs: any[]) {
return (this.attachOnceExtract as any)(...inputs);
}
attachOnceExtract(...args: any[]) {
return this.__attachX(args, "attachOnceExtract");
}
private __attachX(
args: any[],
methodName: keyof typeof EvtImpl.propsFormMethodNames
): any {
const propsFromArgs = parsePropsFromArgs<T>(args, "attach*");
const handler = this.addHandler(
propsFromArgs,
EvtImpl.propsFormMethodNames[methodName]
);
return propsFromArgs.timeout === undefined ?
this :
handler.promise
;
}
postAsyncOnceHandled(data: T): number | Promise<number> {
if (this.isHandled(data)) {
return this.post(data);
}
const d = new Deferred<number>();
this.evtAttach.attachOnce(
({ op }) => !!invokeOperator(this.getStatelessOp(op), data),
() => Promise.resolve().then(() => d.resolve(this.post(data)))
);
return d.pr;
}
private postOrPostAndWait(data: T, wait: false): number;
private postOrPostAndWait(data: T, wait: true): Promise<void>;
private postOrPostAndWait(data: T, wait: boolean): number | Promise<void> {
this.trace(data);
overwriteReadonlyProp(this, "postCount", this.postCount + 1);
//NOTE: Must be before postSync.
const postChronologyMark = this.getChronologyMark();
const [isExtracted, prAllHandlerCallbacksResolved] = this.postSync(data);
const getReturnValue = wait ?
() => prAllHandlerCallbacksResolved :
() => this.postCount;
if (isExtracted) {
return getReturnValue();
}
if (this.postAsync === undefined) {
if (this.asyncHandlerCount === 0) {
return getReturnValue();
}
this.postAsync = this.postAsyncFactory();
}
this.postAsync(data, postChronologyMark);
return getReturnValue();
}
post(data: T) {
return this.postOrPostAndWait(data, false);
}
postAndWait(data: T) {
return this.postOrPostAndWait(data, true);
}
}
//NOTE: For some reason can't set it as static method so we put it here
export function doDetachIfNeeded<U = any>(
handler: Handler<any, U>,
opResult: _1.Operator.fλ.Result.Matched<U, any>,
once: boolean
): void;
export function doDetachIfNeeded(
handler: Handler<any, any>,
opResult: _1.Operator.fλ.Result.NotMatched<any>,
): void;
export function doDetachIfNeeded<U = any>(
handler: Handler<any, U>,
opResult: _1.Operator.fλ.Result<U, any>,
once?: boolean
): void {
const detach = _1.z_f1.fλ_Result_getDetachArg(opResult);
if (typeof detach !== "boolean") {
const [ctx, error, res] = detach;
if (!!error) {
ctx.abort(error);
} else {
ctx.done(res);
}
} else if (detach || !!once) {
handler.detach();
}
}
export const Evt: {
new <T>(): Evt<T>;
readonly prototype: Evt<any>;
readonly create: typeof create;
readonly newCtx: typeof newCtx;
readonly merge: typeof merge;
readonly from: typeof from;
readonly useEffect: typeof useEffect;
readonly getCtx: ReturnType<typeof getCtxFactory>;
readonly loosenType: typeof loosenType;
readonly factorize: typeof factorize;
readonly asPostable: typeof asPostable;
readonly asyncPipe: typeof asyncPipe;
readonly asNonPostable: typeof asNonPostable;
/** https://docs.evt.land/api/evt/setdefaultmaxhandlers */
setDefaultMaxHandlers(n: number): void;
} = EvtImpl;
try { overwriteReadonlyProp(Evt as any, "name", "Evt"); } catch { }
importProxy.Evt = Evt; | the_stack |
/// <reference path="../../elements.d.ts" />
/// <reference path="../../../../tools/definitions/react.d.ts" />
import { LogLineContainerInterface } from '../../elements';
import { Polymer } from '../../../../tools/definitions/polymer';
import { PaperDropdownMenu } from '../../options/inputs/paper-dropdown-menu/paper-dropdown-menu';
import { TabData, LogLineData, LogListenerLine, BackgroundpageWindow, LogListenerObject } from '../../../js/background/sharedTypes';
import { I18NKeys } from '../../../_locales/i18n-keys';
declare const ReactDOM: {
render<T>(el: React.ReactElement<T>, container: HTMLElement): any;
};
declare const browserAPI: browserAPI;
declare global {
interface ContextMenuElement extends HTMLElement {
source: LogConsoleElement.ContextMenuSource;
}
}
namespace LogConsoleElement {
export const logConsoleProperties: {
lines: number;
ids: {
id: string|CRM.GenericNodeId;
title: string;
}[];
tabIndexes: TabIndex[];
selectedId: CRM.GenericNodeId;
selectedTab: TabId;
selectedTabIndex: TabIndex;
tabs: TabData[];
textfilter: string;
waitingForEval: boolean;
__this: LogConsole;
} = {
lines: {
value: 0,
type: Number,
notify: true
},
ids: {
type: Array,
value: [],
notify: true
},
tabIndexes: {
type: Array,
value: [],
notify: true
},
selectedId: {
type: Number,
notify: true,
value: 0
},
selectedTab: {
type: Number,
notify: true,
value: 0
},
selectedTabIndex: {
type: Number,
notify: true,
value: 0
},
tabs: {
type: Array,
value: [],
notify: true
},
textfilter: {
type: String,
value: '',
notify: true
},
waitingForEval: {
type: Boolean,
value: false,
notify: true
},
__this: { }
} as any;
export interface ContextMenuSource {
props: {
value: LogLineData[]|LogLineData;
parent: React.Component<any, any> & {
isLine(): boolean;
};
line: LogListenerLine;
};
}
export class LC {
static is: string = 'log-console';
private static _bgPage: BackgroundpageWindow;
static properties: any = logConsoleProperties;
private static _logListener: LogListenerObject;
private static _logLines: LogLineContainerInterface;
static observers = [
'_updateLog(selectedId, selectedTab, textfilter)'
];
static done: boolean;
static _hideGenericToast(this: LogConsole) {
this.$.genericToast.hide();
};
static _textFilterChange(this: LogConsole) {
this.set('textfilter', this.$.textFilter.value);
};
static async _takeToTab(this: LogConsole, event: Polymer.ClickEvent) {
const target = event.target;
let tabId = (target.children[0] as HTMLElement).innerText;
const tab = await browserAPI.tabs.get(~~tabId).catch(async () => {
window.logConsole.$.genericToast.text = await this.__async(I18NKeys.logging.tabClosed);
window.logConsole.$.genericToast.show();
});
if (!tab) {
return;
}
if ('highlight' in browserAPI.tabs) {
const chromeTabs: typeof _chrome.tabs = browserAPI.tabs as any;
if (!chromeTabs.highlight) {
return;
}
await chromeTabs.highlight({
windowId: tab.windowId,
tabs: tab.index
}, async () => {
if ((window as any).chrome.runtime.lastError) {
console.log((window as any).chrome.runtime.lastError);
console.log(await this.__async(I18NKeys.logging.somethingWentWrong));
}
});
}
};
static _focusInput(this: LogConsole) {
this.$.consoleInput.focus();
};
private static _fixTextareaLines(this: LogConsole) {
this.$.consoleInput.setAttribute('rows', (this.$.consoleInput.value.split('\n').length || 1) + '');
this.$.linesCont.scrollTop = this.$.linesCont.scrollHeight;
};
private static _executeCode(this: LogConsole, code: string) {
if (this.selectedTab !== 0 && this.selectedId !== 0) {
const selectedItems = this._getSelectedItems();
browserAPI.runtime.sendMessage({
type: 'executeCRMCode',
data: {
code: code,
id: selectedItems.id.id,
tabIndex: selectedItems.tabIndex,
tab: selectedItems.tab.id,
logListener: this._logListener
}
});
this.waitingForEval = true;
this._logLines.add([{
code: code
}], {
isEval: true,
nodeTitle: selectedItems.id.title,
tabTitle: selectedItems.tab.title,
tabInstanceIndex: selectedItems.tabIndex,
id: selectedItems.id.id,
tabId: selectedItems.tab.id,
lineNumber: '<eval>:0',
timestamp: new Date().toLocaleString()
});
} else {
this.$.inputFieldWarning.classList.add('visible');
this.$.consoleInput.setAttribute('disabled', 'disabled');
this.async(() => {
this.$.inputFieldWarning.classList.remove('visible');
this.$.consoleInput.removeAttribute('disabled');
}, 5000);
}
};
static _inputKeypress(this: LogConsole, event: KeyboardEvent) {
if (event.key === 'Enter') {
if (!event.shiftKey) {
this._executeCode(this.$.consoleInput.value);
this.$.consoleInput.value = '';
this.$.consoleInput.setAttribute('rows', '1');
} else {
this.async(this._fixTextareaLines, 10);
}
} else if (event.key === 'Backspace' || event.key === 'Delete') {
this.async(this._fixTextareaLines, 10);
}
this.$.linesCont.scrollTop = this.$.linesCont.scrollHeight;
};
private static _getSelectedItems(this: LogConsole): {
id: {
id: string|CRM.GenericNodeId;
title: string;
};
tab: {
id: string|TabId;
title: string;
};
tabIndex: TabIndex;
} {
const tabVal = (this.tabs && this.tabs[~~this.selectedTab - 1]) || {
id: 'all',
title: 'all'
};
const idVal = this.selectedId === 0 ? {
id: 'all',
title: 'all'
} : this.ids[~~this.selectedId - 1];
return {
tab: tabVal,
id: idVal,
tabIndex: this.selectedTabIndex
};
};
private static _getSelectedValues(this: LogConsole) {
const selectedItems = this._getSelectedItems();
return {
id: selectedItems.id.id,
tab: selectedItems.tab.id,
tabIndex: selectedItems.tabIndex
};
};
static _updateLog(this: LogConsole, _selectedId: CRM.GenericNodeId, _selectedTab: number, textfilter: string) {
const selected = this._getSelectedValues();
const lines: LogListenerLine[] = (this._logListener && this._logListener.update(
selected.id,
selected.tab,
selected.tabIndex,
textfilter
)) || [];
if (this._logLines) {
this._logLines.clear();
lines.forEach((line) => {
this._logLines.add(line.data, line);
});
}
this.lines = lines.length;
};
static _getTotalLines(this: LogConsole) {
return this.lines;
};
private static _hasChanged(this: LogConsole, prev: {
id: string|number|CRM.GenericNodeId;
title: string;
}[], current: {
id: string|number|CRM.GenericNodeId;
title: string;
}[]) {
return JSON.stringify(prev) !== JSON.stringify(current);
}
private static _transitionSelected(this: LogConsole, prev: {
id: string|number;
title: string;
}, arr: {
id: string|number;
title: string;
}[], prop: string) {
//Find the previous selected value in the new batch
if (prev) {
for (let index in arr) {
if (arr[index].id === prev.id) {
this.set(prop, ~~index + 1);
return;
}
}
}
this.set(prop, 0);
}
static _getIdTabs(this: LogConsole, selectedId: string|CRM.GenericNodeId): TabData[] {
this.async(() => {
this._refreshMenu(this.$.tabDropdown, this.$.tabRepeat);
}, 10);
if (this._bgPage) {
const id = selectedId === 0 ? 0 as CRM.GenericNodeId : ~~this.ids[~~selectedId - 1].id as CRM.GenericNodeId;
this._bgPage._getIdsAndTabs(id, -1, ({tabs}) => {
if (!this._hasChanged(this.tabs, tabs)) {
return;
}
const prevTabsSelected = this.tabs[this.selectedTab - 1];
this.set('tabs', tabs);
this._transitionSelected(prevTabsSelected, tabs, 'selectedTab');
});
}
return this.tabs;
};
static _getTabsIds(this: LogConsole, selectedTab: number): {
id: number|string;
title: string;
}[] {
this.async(() => {
this._refreshMenu(this.$.idDropdown, this.$.idRepeat);
}, 10);
if (this._bgPage) {
const tab: TabId|'background' = selectedTab === 0 ? -1 : this.tabs[selectedTab - 1].id;
this._bgPage._getIdsAndTabs(0 as CRM.GenericNodeId, tab, ({ids}) => {
if (!this._hasChanged(this.ids, ids)) {
return;
}
const prevIdsSelected = this.ids[~~this.selectedId - 1];
this.set('ids', ids);
this._transitionSelected(prevIdsSelected, ids, 'selectedId');
});
}
return this.ids;
}
static _getTabIndexes(this: LogConsole, selectedId: string|CRM.GenericNodeId, selectedTab: TabId): TabIndex[] {
this.async(() => {
this._refreshMenu(this.$.tabIndexDropdown, this.$.tabIndexRepeat);
}, 10);
if (selectedId === 0 || selectedTab === 0) {
return [];
}
if (this._bgPage) {
const id = selectedId === 0 ? 0 as CRM.GenericNodeId : ~~this.ids[~~selectedId - 1].id as CRM.GenericNodeId;
const tab = selectedTab === 0 ? -1 : this.tabs[selectedTab - 1].id;
this._bgPage._getCurrentTabIndex(id, tab, (newTabIndexes: TabIndex[]) => {
this.set('tabIndexes', newTabIndexes);
});
}
return this.tabIndexes;
}
static _escapeHTML(this: LogConsole, string: string): string {
return string
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
private static _processLine(this: LogConsole, line: LogListenerLine) {
this._logLines.add(line.data, line);
};
private static _processEvalLine(this: LogConsole, line: LogListenerLine) {
if (line.val.type === 'error') {
line.isError = true;
}
const lastEval = this._logLines.popEval();
this._logLines.add([{
code: lastEval.data[0].code,
result: line.val.result,
hasResult: true
}], lastEval.line);
this.waitingForEval = false;
};
private static _closeMenus(this: LogConsole) {
this.$.idDropdown.close();
this.$.tabDropdown.close();
this.$.tabIndexDropdown.close();
}
private static _refreshMenu(this: LogConsole, menu: PaperDropdownMenu, template: HTMLDomRepeatElement) {
template.render();
this.async(() => {
menu.init();
menu.updateSelectedContent();
}, 100);
menu.onValueChange = (_oldState: number, newState: number) => {
this._closeMenus();
switch (menu.id) {
case 'idDropdown':
this.set('selectedId', newState);
break;
case 'tabDropdown':
this.set('selectedTab', newState);
break;
case 'tabIndexDropdown':
this.set('selectedTabIndex', newState);
break;
}
}
}
private static async _init(this: LogConsole, callback: () => void) {
const bgPage = await browserAPI.runtime.getBackgroundPage() as BackgroundpageWindow;
this._bgPage = bgPage;
bgPage._listenIds((ids) => {
const prevSelected = this.ids[~~this.selectedId - 1];
this.set('ids', ids);
this._transitionSelected(prevSelected, ids, 'selectedId');
this.async(() => {
this._refreshMenu(this.$.idDropdown, this.$.idRepeat);
}, 50);
});
bgPage._listenTabs((tabs) => {
const prevSelected = this.tabs[this.selectedTab - 1];
this.set('tabs', tabs);
this._transitionSelected(prevSelected, tabs, 'selectedTab');
this.async(() => {
this._refreshMenu(this.$.tabDropdown, this.$.tabRepeat);
}, 50);
});
bgPage._listenLog((logLine) => {
if (logLine.type && logLine.type === 'evalResult') {
this._processEvalLine(logLine);
} else if (logLine.type && logLine.type === 'hints') {
this._processLine(logLine);
} else {
this._processLine(logLine);
}
}, (logListener) => {
this._logListener = logListener;
}).forEach((logLine) => {
this._processLine(logLine);
});
this.async(() => {
this._refreshMenu(this.$.tabIndexDropdown, this.$.tabIndexRepeat);
callback && callback();
}, 50);
};
static _contextStoreAsLocal(this: LogConsole) {
let source: any = this.$.contextMenu.source;
let sourceVal = source.props.value;
//Get the LogLine
while (source.props.parent) {
sourceVal = source.props.value;
source = source.props.parent;
}
const sourceLine = source;
//Get the index of this element in the logLine
const index = (sourceLine.props.value as LogLineData[]).indexOf(sourceVal as LogLineData);
const logLine = sourceLine.props.line;
//Send a message to the background page
browserAPI.runtime.sendMessage({
type: 'createLocalLogVariable',
data: {
code: {
index: index,
path: this._contextCopyPath(true),
logId: logLine.logId
},
id: logLine.id,
tab: logLine.tabId,
tabIndex: logLine.tabIndex,
logListener: this._logListener
}
});
};
static _contextLogValue(this: LogConsole) {
const source = this.$.contextMenu.source;
this._logLines.add([source.props.value as LogLineData], {
id: 'local',
tabId: 'local',
tabInstanceIndex: 0,
nodeTitle: 'logger page',
tabTitle: 'logger page',
data: [source.props.value as LogLineData],
lineNumber: '<log-console>:0:0',
timestamp: new Date().toLocaleString()
});
};
static _contextClearConsole(this: LogConsole) {
this._logLines.clear();
};
private static _copy(this: LogConsole, value: string) {
this.$.copySource.innerText = value;
const snipRange = document.createRange();
snipRange.selectNode(this.$.copySource);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(snipRange);
try {
document.execCommand('copy');
} catch(e) {
console.log(e);
}
selection.removeAllRanges();
};
static _contextCopyAsJSON(this: LogConsole) {
const value = this.$.contextMenu.source.props.value;
this._copy(JSON.stringify(value, function(key, value) {
if (key === '__parent' || key === '__proto__') {
return undefined;
}
return value;
}) || '');
};
private static _contextCopyPath(this: LogConsole, noCopy: boolean = false): string|boolean {
const path = [];
let source: any = this.$.contextMenu.source;
let childValue = source.props.value;
while (source.props.parent && !source.props.parent.isLine()) {
source = source.props.parent;
if (Array.isArray(source.props.value)) {
path.push('[' + source.props.value.indexOf(childValue as LogLineData) + ']');
} else {
const keys = Object.getOwnPropertyNames(source.props.value).concat(['__proto__']);
let foundValue = false;
for (let i = 0; i < keys.length; i++) {
if ((source.props.value as any)[keys[i]] === childValue) {
if (/[a-z|A-Z]/.exec(keys[i].charAt(0))) {
path.push('.' + keys[i]);
} else {
path.push('["' + keys[i] + '"]');
}
foundValue = true;
break;
}
}
if (!foundValue) {
return false;
}
}
childValue = source.props.value;
}
if (!noCopy) {
this._copy(path.reverse().join(''));
}
return path.reverse().join('');
};
private static _setPossibleOptions(this: LogConsole, source: ContextMenuSource) {
let enableCopyAsJSON = false;
try {
JSON.stringify(source.props.value, function(key, value) {
if (key === '__parent' || key === '__proto__') {
return undefined;
}
return value;
}) !== undefined;
enableCopyAsJSON = true;
} catch(e) { console.log(e); }
let logLine: any = source;
do { logLine = logLine.props.parent; } while (logLine.props.parent);
const enableCreateLocalVar = !!logLine.props.line.logId;
this.$.copyAsJSON.classList[enableCopyAsJSON ? 'remove' : 'add']('disabled');
this.$.storeAsLocal.classList[enableCreateLocalVar ? 'remove': 'add']('disabled');
};
static initContextMenu(this: LogConsole, source: ContextMenuSource, event: MouseEvent) {
const contextMenu = this.$.contextMenu;
contextMenu.style.left = event.clientX + 'px';
contextMenu.style.top = event.clientY + 'px';
contextMenu.source = source;
this._setPossibleOptions(source);
contextMenu.classList.add('visible');
};
static ready(this: LogConsole) {
this.__this = this;
window.logConsole = this;
this._logLines = (ReactDOM.render(
(window.React.createElement as any)(
(window.logElements.logLines as any) as string, {
items: [],
logConsole: this
}),
this.$.lines) as any) as LogLineContainerInterface;
document.body.addEventListener('click', () => {
this.$.contextMenu.classList.remove('visible');
});
this.async(() => {
this._init(() => {
this.done = true;
if (window.logPage) {
window.logPage.isLoading = false;
}
});
}, 1000);
}
}
if (window.objectify) {
window.register(LC);
} else {
window.addEventListener('RegisterReady', () => {
window.register(LC);
});
}
}
export type LogConsole = Polymer.El<'log-console',
typeof LogConsoleElement.LC & typeof LogConsoleElement.logConsoleProperties>; | the_stack |
import * as React from 'react';
import { Link } from 'react-router-dom';
import styled from '@emotion/styled';
import ReadMore from './ReadMore';
import SpreadsheetKeyExtractor from './SpreadsheetKeyExtractor';
import { Away, Column, Logo, Row } from '@flowmap.blue/core';
import { Helmet } from 'react-helmet';
import MapboxLogo from './images/mapbox-logo-black.svg';
import ElPasoLogo from './images/city-of-el-paso-eptx.png';
import LinuxFoundation from './images/linux-foundation-hztl-white.svg';
import AecomLogo from './images/aecom-logo-light.svg';
// import MoeLogo from './images/moe-logo.svg';
import GreaterAucklandLogo from './images/greater-auckland-logo.svg';
import NycCitiBikeImage from './images/nyc-citi-bike_1000px.jpg';
import TLLogo from './images/TL-Horizontal-Black.svg';
import MTALogo from './images/mta-logo.svg';
import TflLogo from './images/Tfl-logo.svg';
import NZMinistryOfTransportLogo from './images/nz-minstry-of-transport-logo.svg';
import KingCountyLogo from './images/KingCounty-logo.png';
import UddLogo from './images/logo-udd-blanco.svg';
import EurocontrolLogo from './images/eurocontrol-logo.svg';
import TrondheimLogo from './images/trondheim-logo.svg';
// import StadtZuerichLogo from './images/stadtzurich-logo.svg';
import OpenDataZuerichLogo from './images/stadtzurich-opendata-logo.svg';
import UcfLogo from './images/ucf-logo.svg';
import { Button, Classes, Colors } from '@blueprintjs/core';
import Nav from './Nav';
import News from './News';
import ReactPlayer from 'react-player';
import { ListOfUses, ListOfUsesItem } from './Gallery';
const ContentBody = styled.div`
padding: 10px 20px;
@media (min-width: 500px) {
padding: 20px 60px;
}
& h1 {
font-size: 2rem;
}
margin: auto;
max-width: 1500px;
`;
const LogoTitle = styled.h1`
margin-bottom: 1em;
`;
const Support = styled.p`
margin-top: 1.5em;
display: flex;
justify-items: center;
flex-wrap: wrap;
`;
const AwardImage = styled.img`
filter: grayscale(80%);
transition: filter 0.5s;
&:hover {
filter: grayscale(20%);
}
`;
const SupportLogoLink = styled.a`
position: relative;
margin-top: 20px;
margin-right: 35px;
//top: 0.14em;
transition: opacity 0.2s;
opacity: 0.6;
//margin: 0 22px;
img {
max-width: 200px;
}
&:hover {
opacity: 1;
}
`;
const SupportLogo = ({ src, href }: { src: string; href: string }) => (
<SupportLogoLink href={href} target="_blank" rel="noopener noreferrer">
<img alt="support logo" src={src} height={22} />
</SupportLogoLink>
);
const NoWrap = styled.span`
display: flex;
flex-wrap: nowrap;
`;
const DemoVideo = styled.div`
width: 100%;
margin-bottom: 20px;
max-width: 500px;
display: inline-block;
@media (min-width: 800px) {
float: right;
margin-left: 20px;
}
`;
const ResponsivePlayer = styled.div`
position: relative;
padding-top: 56.25%; /* Player ratio: 100 / (1280 / 720) */
`;
const ResponsiveReactPlayer = styled(ReactPlayer)`
position: absolute;
top: 0;
left: 0;
border: 1px solid ${Colors.GRAY1};
`;
const ListOfSteps = styled.ol`
margin: 30px 20px;
& > li {
margin: 1em 0;
padding-left: 0.3em;
}
@media (max-width: 500px) {
margin: 0;
padding: 0;
list-style-position: inside;
& > li {
padding-left: 0;
margin-left: 0;
}
}
`;
const NewsletterDescription = styled.div`
font-size: 9pt;
color: ${Colors.GRAY4};
`;
const NewsletterOuter = styled.div`
justify-self: flex-end;
flex: 1;
display: flex;
justify-content: flex-end;
button {
white-space: nowrap;
}
input {
width: 270px;
}
@media (max-width: 800px) {
input {
width: 200px;
}
margin-bottom: 2rem;
}
`;
const UsedByContainer = styled.div`
display: flex;
flex-wrap: wrap;
align-items: center;
justify-items: center;
& > * > img {
max-width: 100px;
height: 50px;
}
& > * {
padding: 1em;
opacity: 0.5;
transition: opacity 0.2s;
&:hover {
opacity: 1;
}
}
padding: 1em;
`;
const TitleRow = styled.div`
display: flex;
flex-wrap: wrap;
width: 100%;
align-items: center;
@media (max-width: 800px) {
flex-direction: column;
align-items: flex-start;
}
`;
const Home = () => (
<>
<Nav />
<ContentBody className={Classes.DARK}>
<Helmet>
<link href="https://flowmap.blue/" rel="canonical" />
<title>Flowmap.blue - Flow map visualization tool</title>
</Helmet>
<TitleRow>
<LogoTitle>
<Logo fontSize={35} collapseWidth={300} />
</LogoTitle>
<NewsletterOuter>
<form action="https://tinyletter.com/flowmap-blue" method="post" target="_blank">
<Column spacing={10}>
<Row spacing={10}>
<input
className={Classes.INPUT}
type="text"
name="email"
id="tlemail"
placeholder="Enter your@email.address here"
/>
<input type="hidden" defaultValue={1} name="embed" />
<Button type="submit" text="Subscribe" />
</Row>
<NewsletterDescription>
Subscribe to the newsletter to learn about{' '}
<Away href="https://tinyletter.com/flowmap-blue/archive">
updates and new features
</Away>
.
</NewsletterDescription>
</Column>
</form>
</NewsletterOuter>
</TitleRow>
<DemoVideo>
<ResponsivePlayer>
<ResponsiveReactPlayer
url={['/videos/demo_500.webm', '/videos/demo_500.mp4']}
light={NycCitiBikeImage}
width="100%"
height="100%"
controls={true}
loop={true}
playing={true}
/>
</ResponsivePlayer>
</DemoVideo>
<section>
<p>Create geographic flow maps representing your data published in Google Sheets.</p>
<p>Visualize numbers of movements between locations (origin-destination data).</p>
<p>Explore the data interactively.</p>
</section>
<section>
<h2>What is it for?</h2>
<div>
Flowmap.blue is used to visualize various real-world phenomena in which pairs of locations
are involved:
<ListOfUses>
<ListOfUsesItem>Urban mobility</ListOfUsesItem>
<ListOfUsesItem>Commuters</ListOfUsesItem>
<ListOfUsesItem>Pedestrian movement</ListOfUsesItem>
<ListOfUsesItem>Bus travels </ListOfUsesItem>
<ListOfUsesItem>Metro rides</ListOfUsesItem>
<ListOfUsesItem>Train rides</ListOfUsesItem>
<ListOfUsesItem>Air travels</ListOfUsesItem>
<ListOfUsesItem>Marine traffic</ListOfUsesItem>
<ListOfUsesItem>Bicycle sharing</ListOfUsesItem>
<ListOfUsesItem>Scooter sharing</ListOfUsesItem>
<ListOfUsesItem>Car ride sharing </ListOfUsesItem>
<ListOfUsesItem>Taxi rides</ListOfUsesItem>
<ListOfUsesItem>Internal migration</ListOfUsesItem>
<ListOfUsesItem>International migration</ListOfUsesItem>
<ListOfUsesItem>Refugees</ListOfUsesItem>
<ListOfUsesItem>Human trafficking </ListOfUsesItem>
<ListOfUsesItem>Drug flows </ListOfUsesItem>
<ListOfUsesItem>Freight transportation </ListOfUsesItem>
<ListOfUsesItem>Material flows</ListOfUsesItem>
<ListOfUsesItem>Trade </ListOfUsesItem>
<ListOfUsesItem>Bird migrations </ListOfUsesItem>
<ListOfUsesItem>Livestock movements </ListOfUsesItem>
<ListOfUsesItem>Plant migration</ListOfUsesItem>
<ListOfUsesItem>Urban infrastructure</ListOfUsesItem>
<ListOfUsesItem>Sewage flows</ListOfUsesItem>
<ListOfUsesItem>Waste management</ListOfUsesItem>
<ListOfUsesItem>Supply chain </ListOfUsesItem>
<ListOfUsesItem>Epidemiology</ListOfUsesItem>
<ListOfUsesItem>Historical journeys </ListOfUsesItem>
<ListOfUsesItem>Scientific collaborations</ListOfUsesItem>
</ListOfUses>
</div>
Make sure to check <Link to="/gallery">the examples gallery</Link>.
</section>
<section>
<h2>Who is using it?</h2>
<UsedByContainer>
<Away href="https://new.mta.info">
<img src={MTALogo} />
</Away>
<Away href="https://tfl.gov.uk">
<img src={TflLogo} />
</Away>
<Away href="https://aecom.com">
<img src={AecomLogo} />
</Away>
<Away href="https://ansperformance.eu/study/daily_country_flows_2020/">
<img src={EurocontrolLogo} />
</Away>
<Away href="https://www.elpasotexas.gov">
<img src={ElPasoLogo} />
</Away>
{/*<Away href="https://www.stadt-zuerich.ch/">*/}
{/* <img src={StadtZuerichLogo} />*/}
{/*</Away>*/}
<Away href="https://data.stadt-zuerich.ch">
<img src={OpenDataZuerichLogo} />
</Away>
<Away href="https://www.trondelagfylke.no/vare-tjenester/plan-og-areal/kart-statistikk-og-analyse/nyhetsarkiv-kart-og-statistikk/faktafredag---pendlestrommer-i-trondelag-pa-mer-enn-100-personer-per-4.kvartal-2018/">
<img src={TrondheimLogo} />
</Away>
<Away href="http://datagramas.cl/2015/03/run-run-inferencia-y-visualizaci%C3%B3n-de-uso-de-modos-de-transporte-en-la-ciudad-2015-presente/">
<img src={UddLogo} />
</Away>
<Away href="https://www.transport.govt.nz">
<img src={NZMinistryOfTransportLogo} style={{ maxWidth: 130 }} />
</Away>
{/*<Away href="https://www.education.govt.nz">*/}
{/* <img src={MoeLogo} />*/}
{/*</Away>*/}
<Away href="https://kingcounty.gov">
<img src={KingCountyLogo} style={{ height: 20 }} />
</Away>
<Away href="https://www.greaterauckland.org.nz/2020/08/11/2018-census-commuting-data/">
<img src={GreaterAucklandLogo} />
</Away>
</UsedByContainer>
</section>
<section>
{/*How to make a flow map*/}
<h2 id="how-to">How to make a flow map</h2>
<p>
To visualize and publish a data set as a flow map you need to have a Google account.{' '}
<Away href="https://accounts.google.com/signup">Sign up here</Away> if you don't.
</p>
<p>Follow these steps:</p>
<ListOfSteps>
<li>
Open{' '}
<Away href="https://docs.google.com/spreadsheets/d/1aEgwtGUGc0TdnsO0jIm50hshCZ-m4DHms3P0Qq9IYdA">
the template spreadsheet
</Away>{' '}
</li>
<li>Make a copy of it (find “File” / “Make a copy…” in the menu)</li>
<li>
Add data to the new spreadsheet.{' '}
<ReadMore>
<p>
The spreadsheet has three sheets in it. They are named “<b>properties</b>”, “
<b>locations</b>” and “<b>flows</b>”. The <b>properties</b> sheet has the title and
the description for your data set and a few other configuration parameters. The{' '}
<b>locations</b> sheet has the columns <b>id</b>, <b>lat</b>, <b>lon</b> and the
optional <b>name</b>. The <b>flows</b> sheet has <b>origin</b>, <b>dest</b>,{' '}
<b>count</b> and optional <b>time</b>. The values in the <b>origin</b> and{' '}
<b>dest</b> columns must be the respective locations' <b>id</b>s.
</p>
<p>
Use the <Link to="/od-matrix-converter">OD-matrix converter</Link> if your movement
counts are represented as an OD-matrix.
</p>
Our <Link to="/geocoding">Geocoding tool</Link> can help you finding the geographic
coordinates for locations if you only have their names in your dataset.
</ReadMore>
</li>
{/*<li>Publish your spreadsheet by going to "File" / "Publish to the web…"</li>*/}
<li>
Click the “Share” button, then change the selection from “Restricted” to “Anyone with
the link” in the drop-down under “Get link”.{' '}
<ReadMore>
This step is required so that Flowmap.blue can access the data in your spreadsheet.
The spreadsheet and the flow map will be effectively private as long as you don't send
their URLs to anyone and don't publish them online. We'll treat your data as private
by default and will not disclose the URLs without getting an explicit consent from you
(unless you disclose them yourself first by linking from a publicly accessible
website).
</ReadMore>
</li>
<SpreadsheetKeyExtractor />
</ListOfSteps>
If you are not comfortable uploading your data to Google Sheets, consider using our{' '}
<Link to="/in-browser">In-browser flow map</Link> or load CSV files from any specific URLs
as{' '}
<Away href="https://github.com/FlowmapBlue/flowmap.blue/issues/18#issuecomment-610063627">
described here
</Away>
.
</section>
{/*<section>*/}
{/* <h2>Data preparation helpers</h2>*/}
{/* <p>*/}
{/* <Button>Convert OD-matrix</Button>*/}
{/* </p>*/}
{/*</section>*/}
<section>
<h2 id="news">News</h2>
<News />
</section>
<section>
<h2 id="tools">Tools</h2>
<p>
Our <Link to="/geocoding">Geocoding tool</Link> can help you finding the geographic
coordinates for locations if you only have their names in your dataset.
</p>
<p>
Use the <Link to="/od-matrix-converter">OD-matrix converter</Link> if your movement counts
are represented as an OD-matrix.
</p>
<p>
With the <Link to="/in-browser">In-browser flow map</Link> you can visualize OD-data{' '}
<b>directly in your browser</b> without having to upload the data to Google Sheets.
</p>
</section>
<section>
<h2 id="need-help">Need help?</h2>
<p>
<Away href="https://spectrum.chat/flowmap-blue/general">Ask a question in the forum</Away>
,{` `}
<Away href="https://github.com/FlowmapBlue/flowmap.blue/issues">submit an issue</Away>
{` or `}
<a href="mailto:ilya@boyandin.me?subject=Flowmap.blue">write me an email</a>.
</p>
</section>
<section>
<h2 id="privacy">Data privacy</h2>
<p>
Flowmap.blue does not store any of the data the users upload to Google Sheets. The data
from the spreadsheets is loaded directly into the clients' browsers. We are using{' '}
<Away href="https://developers.google.com/chart/interactive/docs/querylanguage">
Google Visualization API
</Away>{' '}
for that.
</p>
<p>
We treat the data as private, including the URLs of the spreadsheets and flow maps
published by the users. We do not disclose the URLs without getting an explicit consent
from the authors (unless the authors have already disclosed them by linking from a
publicly accessible website).
</p>
<p>
We collect usage statistics via Google Analytics and track errors via Sentry. We want to
know how Flowmap.blue is used and when it fails so that we can improve it. The use of
Google Analytics involves setting cookies in the users' browsers for detecting recurring
visits and working sessions.
</p>
<p>
We may try to contact you asking for a permission to add your flow map to the list of
examples on the homepage of Flowmap.blue.
</p>
</section>
<section>
<h2 id="open-source">Open source</h2>
<p>
{`The source code of Flowmap.blue `}
<Away href="https://github.com/FlowmapBlue/flowmap.blue">is freely available</Away>
{` under the `}
<Away href="https://github.com/FlowmapBlue/flowmap.blue/blob/master/LICENSE">
MIT license
</Away>
.
</p>
<p>
Make sure to include a proper attribution (URL of Flowmap.blue, the original author) if
you use it in a different project.
</p>
</section>
<section>
<h2 id="credits">Credits</h2>
<p>
Developed by <Away href="https://ilya.boyandin.me">Ilya Boyandin</Away> using {` `}
<Away href="https://github.com/teralytics/flowmap.gl">flowmap.gl</Away>,{` `}
<Away href="http://deck.gl">deck.gl</Away>,{` `}
<Away href="https://github.com/mapbox/mapbox-gl-js">mapbox</Away>,{` `}
<Away href="https://d3js.org/">d3</Away>,{` `}
<Away href="https://blueprintjs.com/">blueprint</Away>,{` `}
<Away href="https://github.com/CartoDB/cartocolor">CARTOColors</Away>.
</p>
<p>With kind support from</p>
<Support>
<SupportLogo href="https://www.teralytics.net" src={TLLogo} />
<SupportLogo href="https://www.mapbox.com" src={MapboxLogo} />
<SupportLogo href="https://uc.foundation" src={UcfLogo} />
<SupportLogo href="https://www.linuxfoundation.org" src={LinuxFoundation} />
</Support>
</section>
<section>
<span style={{ zoom: 0.8 }}>
<Away href="https://www.netlify.com">
<img
width={114}
height={51}
src="https://www.netlify.com/img/global/badges/netlify-dark.svg"
alt="Deploys by Netlify"
/>
</Away>
</span>
<span
style={{
marginLeft: '1em',
zoom: 0.75,
filter: 'grayscale(0.8)contrast(0.75)',
opacity: 0.8,
}}
>
<Away href="https://www.producthunt.com/posts/flowmap-blue?utm_source=badge-featured&utm_medium=badge&utm_souce=badge-flowmap-blue">
<img
src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=285959&theme=dark"
alt="Flowmap.blue - Flow map visualization for geographic movement analysis | Product Hunt"
style={{ width: 250, height: 54 }}
width="250"
height="54"
/>
</Away>
</span>
</section>
<section>
<h2 id="awards">Awards</h2>
<Away href="https://www.informationisbeautifulawards.com/showcase/3815">
<AwardImage
width={100}
src="https://infobawards.s3.amazonaws.com/2019/badges/w-2019.png"
/>
</Away>
</section>
</ContentBody>
</>
);
export default Home; | the_stack |
import * as bunyan from "bunyan";
import * as http from "http";
import * as http2 from "http2";
import * as url from "url";
const GRPC_CONTENT_TYPE = "application/grpc";
const GRPC_WEB_CONTENT_TYPE = "application/grpc-web";
const GRPC_WEB_TEXT_CONTENT_TYPE = "application/grpc-web-text";
const logger = bunyan.createLogger({
name: "grpc-web-proxy",
streams: [{ stream: process.stdout }],
serializers: bunyan.stdSerializers
});
export const Mode = [
"http1-insecure",
"http2-insecure",
"http2-fake-https",
"http2-secure"
] as const;
export type Mode = typeof Mode[number];
export interface IGrpcWebProxyOptions {
backend: string;
port: number;
mode?: Mode;
key?: string;
cert?: string;
}
export class GrpcWebProxy {
private webServer: http2.Http2Server | http.Server;
private grpcClient: http2.ClientHttp2Session;
private isShutdown: boolean;
constructor(options: IGrpcWebProxyOptions) {
// Set defaults.
options = { mode: "http1-insecure", ...options };
// Create the server.
this.webServer =
options.mode === "http1-insecure"
? http
.createServer((req, res) => this.handleHttp1GrpcWebRequest(req, res))
.listen(options.port)
: // As this is http2 server, most browsers require it to be https, so this is the default.
options.mode === "http2-fake-https"
? http2.createSecureServer({ key: FAKE_KEY, cert: FAKE_CERT }).listen(options.port)
: options.mode === "http2-insecure"
? http2.createServer().listen(options.port)
: http2.createSecureServer({ key: options.key, cert: options.cert }).listen(options.port);
// Handle requests.
this.webServer.on("stream", (stream, headers) => {
this.handleHttp2GrpcWebRequest(stream, headers);
});
// Constantly try to connect to the backend.
const _ = this.connectAndKeepAlive(options.backend);
}
public shutdown() {
this.isShutdown = true;
if (this.webServer.listening) {
this.webServer.close();
}
if (!!this.grpcClient) {
this.grpcClient.close();
}
}
private async connectAndKeepAlive(backend: string) {
while (!this.isShutdown) {
if (!this.grpcClient || this.grpcClient.destroyed) {
this.grpcClient = http2.connect(backend);
this.grpcClient.on("connect", () => {
logger.info(`Successfully connected to backend: ${backend}`);
});
this.grpcClient.on("error", error => {
logger.error(`Failed to connect to backend: ${backend}\n${error}`);
});
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
private handleHttp1GrpcWebRequest(
webRequest: http.IncomingMessage,
webResponse: http.ServerResponse
) {
const webHeaders = webRequest.headers;
try {
// CORS requests.
if (webRequest.method === "OPTIONS") {
webResponse.writeHead(200, corsResponseAllowOrigin(webHeaders));
webResponse.end();
return;
}
// gRPC-web requests.
const grpcRequestHeaders = {
...cleanRequestHeaders(webHeaders),
// Copy over some sudo HTTP2 headers.
":path": url.parse(webRequest.url).pathname,
":method": webRequest.method
};
const grpcRequest = this.grpcClient.request(grpcRequestHeaders);
// We can't write immediately, as we need to write HTTP1 headers first.
// Save up response chunks and write them when we can.
const earlyChunks: any[] = [];
let writtenHead = false;
webRequest.pipe(grpcRequest);
webRequest.on("close", () => {
grpcRequest.end();
});
grpcRequest.on("response", headers => {
// Write out headers.
writtenHead = true;
webResponse.writeHead(200, cleanResponseHeaders(headers, webHeaders.origin));
earlyChunks.forEach(chunk => webResponse.write(chunk));
});
grpcRequest.on("trailers", headers => {
const trailerChunk = trailersToPayload(headers);
if (writtenHead) {
webResponse.write(trailerChunk);
} else {
earlyChunks.push(trailerChunk);
}
});
grpcRequest.on("data", chunk => {
if (writtenHead) {
webResponse.write(chunk);
} else {
earlyChunks.push(chunk);
}
});
grpcRequest.on("error", e => {
webResponse.end();
});
grpcRequest.on("end", () => {
webResponse.end();
});
} catch (e) {
webResponse.end();
logger.error(e);
}
}
private handleHttp2GrpcWebRequest(
webStream: http2.ServerHttp2Stream,
webHeaders: http2.IncomingHttpHeaders
) {
try {
// CORS requests.
if (webHeaders[":method"] === "OPTIONS") {
webStream.respond({ ...corsResponseAllowOrigin(webHeaders), ":status": 200 });
webStream.end();
return;
}
// gRPC-web requests.
const grpcRequestHeaders = cleanRequestHeaders(webHeaders);
const grpcRequest = this.grpcClient.request(grpcRequestHeaders);
webStream.on("data", chunk => {
grpcRequest.write(chunk);
});
webStream.on("close", () => {
grpcRequest.end();
});
grpcRequest.on("response", headers => {
webStream.respond(cleanResponseHeaders(headers, webHeaders.origin));
});
grpcRequest.on("trailers", headers => {
webStream.write(trailersToPayload(headers));
});
grpcRequest.on("data", chunk => {
webStream.write(chunk);
});
grpcRequest.on("error", e => {
logger.error(e);
webStream.end();
});
grpcRequest.on("end", () => {
webStream.end();
});
} catch (e) {
webStream.end();
logger.error(e);
}
}
}
/**
* Returns a lenient cors response, allowing any origin and all headers sent.
*/
function corsResponseAllowOrigin(requestHeaders: http2.IncomingHttpHeaders) {
const allowRequestHeaders = requestHeaders["access-control-request-headers"];
const allowRequestHeadersList =
typeof allowRequestHeaders === "string" ? [allowRequestHeaders] : allowRequestHeaders;
return {
"access-control-allow-credentials": "true",
"access-control-allow-headers": [
"x-grpc-web",
"content-type",
...Object.keys(requestHeaders),
...allowRequestHeadersList
].join(", "),
"access-control-allow-methods": "POST",
"access-control-allow-origin": requestHeaders.origin,
"access-control-max-age": 600,
"content-length": 0,
vary: "origin, access-control-request-method, access-control-request-headers"
};
}
/**
* Clean the request headers from web to grpc service.
*/
function cleanRequestHeaders(webHeaders: http2.IncomingHttpHeaders): http2.OutgoingHttpHeaders {
const contentType = webHeaders["content-type"] || GRPC_WEB_CONTENT_TYPE;
const incomingContentType = GRPC_WEB_CONTENT_TYPE;
const isTextFormat = contentType.startsWith(GRPC_WEB_TEXT_CONTENT_TYPE);
if (isTextFormat) {
throw new Error("Text format is unsupported.");
}
const grpcRequestHeaders: http2.OutgoingHttpHeaders = { ...webHeaders };
grpcRequestHeaders["content-type"] = contentType.replace(incomingContentType, GRPC_CONTENT_TYPE);
delete grpcRequestHeaders["content-length"];
// These are HTTP1 headers that aren't allowed in a HTTP2 request.
delete grpcRequestHeaders.host;
delete grpcRequestHeaders.connection;
grpcRequestHeaders.protomajor = 2;
grpcRequestHeaders.protominor = 0;
grpcRequestHeaders.te = "trailers";
return grpcRequestHeaders;
}
/**
* Clean the response headers from grpc service to web.
*/
function cleanResponseHeaders(
grpcHeaders: http2.IncomingHttpHeaders,
origin: string | string[]
): http2.OutgoingHttpHeaders {
const newHeaders: http2.OutgoingHttpHeaders = { ...grpcHeaders };
// Not entirely sure why this needs to be removed, but it does.
delete newHeaders[":status"];
// Set grpc-status to 0 if it's not present in the server response.
newHeaders["grpc-status"] = newHeaders["grpc-status"] || 0;
// The original content type was grpc, change to web.
newHeaders["content-type"] = GRPC_CONTENT_TYPE;
newHeaders["access-control-allow-origin"] = origin;
newHeaders["access-control-expose-headers"] = [...Object.keys(newHeaders)].join(", ");
return newHeaders;
}
/**
* Turn trailers into response chunks as per the grpc-web protocol.
*/
function trailersToPayload(trailerHeaders: http2.IncomingHttpHeaders) {
const headersBuffer = Buffer.from(
Object.keys(trailerHeaders)
.filter(key => ["grpc-status"].includes(key))
.map(key => `${key}: ${trailerHeaders[key]}\r\n`)
.join("")
);
const buffer = new ArrayBuffer(5);
const uint8View = new Uint8Array(buffer);
const uint32View = new Uint8Array(buffer);
uint8View.set([128], 0);
uint32View.set([headersBuffer.byteLength], 1);
return Buffer.concat([uint8View, headersBuffer]);
}
const FAKE_KEY = `
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDNIoBojiZnziZc
1Etawvo8ZKPYCDEQ/fY7laO43bDNRapmKfoqXJDQfBuqNwRv8PRM7vBYm7+b0RXE
Kn3RHQD9WKe59+Tnwf3VKGjKIwQ96s9kHh/FEfFXeZBa2b7t8tDxHhttruhK1g3+
nhDivufv/Aarz7RqauG6u3v3pFGRYaRNn9yuZdu8zbyerRLTrhYoslIuoBd0Nl40
SPbTcwREYJRayjQqpGWlzvGJvLhVJENVGAzzuMd5wXBVEGN3Wg5fAcwpZCddCW16
uNZEKRhVFv6Cvce3lLB3MvNrd/MOp/WoXVszYXA+bse7Fh3wnQe4g6JBJfZ2MyMr
iB+eBetrAgMBAAECggEBALIJr8kPFuYhVcpbtssfTm/8KPfmpC9LO9qbFW3tevWt
8SaaaDU8AbPxA1HITmGZj272MkO1aaei4HFRL8G+mo1H1MrjDBjZlaTbXZeSrKvQ
kA8k1g4EdKKnL1KqibubcxzSNJwNoi7ReXPzXFRvvH3dDy0vKDb0bNXUwtM8Gk9C
D5JTFhc2uhI6Mvv6NXTsbOlpy0rJejFCd/4owO8xWwXgOJlP2QSO756uCwHE9EVd
m6rxOlZKzrt/2v8rlzEiW/wQk6MzyUcBkS9CiaODRBOwqcNDCZc+rhODd/2V2qgN
g8sORZZ+aGrgkI016cHCxXPzeYBfDib1uYclULJZ0gECgYEA/mebyNWhOcNBpjoq
8iVbQElppxlHvVh4cknbN77OqDDRxZg2xnOnxxzmOK/oIsqMEhs9mRy6r1S84pqB
rkpEfOrYek2PA9agttYVngy7J3yOBXRX4ZTPI50KpFsN45L3XxdizXfJwj6bpvVq
jgmf5OGcfsfXvVkolWiIaJSWihsCgYEAzmvNBeb3+JBkPeYkJYJ10xwH+yOnZd6w
/WlhlKFXekngL+6uRz2vHcoW+1Fw9yRm7pO8wpYWVuj3fYfU9kn9YqdOC/2k+qVl
pvDheCKh06Zk1a5ZdIcePn567Q1T2As+UzJ9nHlAjQxi4g9z3bZAuOFyx6Rm24sz
dDY420vIOPECgYEAs/Zm5TL50fqlvgj3yENUwa0s59+iN/cVfQNx54U6ew/N1JFQ
biHyVY/D6+XDuJi/bS+H63+/L7gpxcK2aaxvtk4KxLmIqZZyKeRXdm5bFhut+33J
jPHPdcnpdUpUEOAtzT6lzeMm/hl70idZMRDt4uMV6TlFC9S+OLKxjAlQVHECgYBn
Hh0unKI1jtQ0w9o8zr5TdsZZ5AbE8glSnqk7mZncojkXWNHBDwSDCiiO5bFcFNhC
yJTcVCPWyMyR7iAp5O5qsQ9hGBWpjKSKT/0iiZJz68SlplJTzwgByidYcnb3Dy7U
Wv27BCuGCrD/Ix8Lm/cbJKy1JOCpPhG3NTsT+fiM0QKBgQDEtot3hM3DNHiKBbUC
Xbk7lPd6/SyYJ2yjqGvEhHiE047Z+M7hmvYV+gwhxb3i6QMoYR464lgi1JH4iGgG
on8mjhpkUa9jQjObZEau+pjsm8BjhUWTNhLYMa5pi1POywjnEoWiqvPHJUM7YPLC
Ml7ChCE3i/uo1FNPVmZ9vmNo1g==
-----END PRIVATE KEY-----
`;
const FAKE_CERT = `
-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwIBAgIUMNWIVnJyRDpAQ4aCOK9JLc3/N20wDQYJKoZIhvcNAQEL
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0xOTExMDIxNjE2NDJaFw0xOTEy
MDIxNjE2NDJaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw
HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQDNIoBojiZnziZc1Etawvo8ZKPYCDEQ/fY7laO43bDN
RapmKfoqXJDQfBuqNwRv8PRM7vBYm7+b0RXEKn3RHQD9WKe59+Tnwf3VKGjKIwQ9
6s9kHh/FEfFXeZBa2b7t8tDxHhttruhK1g3+nhDivufv/Aarz7RqauG6u3v3pFGR
YaRNn9yuZdu8zbyerRLTrhYoslIuoBd0Nl40SPbTcwREYJRayjQqpGWlzvGJvLhV
JENVGAzzuMd5wXBVEGN3Wg5fAcwpZCddCW16uNZEKRhVFv6Cvce3lLB3MvNrd/MO
p/WoXVszYXA+bse7Fh3wnQe4g6JBJfZ2MyMriB+eBetrAgMBAAGjUzBRMB0GA1Ud
DgQWBBQ+8iEq1jJ+0o2emTM1cqUsJnJfGzAfBgNVHSMEGDAWgBQ+8iEq1jJ+0o2e
mTM1cqUsJnJfGzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQC6
WvwMDoY/IQ2HlPMae/hb5RcBYBanM2iLwqPVOEjYw+fXiej4uNJ3zL++tCX50Wwp
JgX9e7+FiC3KDf4TeGDz+VUA0KcBcft6bQYctDWN2WLavRktY2Bly3f+eQlXRtaJ
ZhxFi2aSxthmlIa3qKHkAkwGfSTObGu62HjJa/xtXSLyKA7wid3Sk/c/Qwu9RAd1
J448MERrg0tcvs2NL7/MmdEwMSsMnHQW+XyePfqDvMCicobu+PY9YNTOuDFY+dZl
OcI9EnRqZrVICRaWK/p9U9UNL/mqoYyFqr1O0t4fSsLijzU4Tfybe3GK36RZFu3k
xH2QtZqGBWSDjPDTUyp2
-----END CERTIFICATE-----
`; | the_stack |
'use strict';
import * as os from 'os';
import * as fs from 'fs-extra';
import * as vscode from 'vscode';
import * as chai from 'chai';
import * as sinonChai from 'sinon-chai';
import * as sinon from 'sinon';
import { TestItem } from './testTektonitem';
import { TaskRun } from '../../src/tekton/taskrun';
import { TknImpl } from '../../src/tkn';
import { TektonItem } from '../../src/tekton/tektonitem';
import { CliExitData } from '../../src/cli';
import * as logInEditor from '../../src/util/log-in-editor';
import { ContextType } from '../../src/context-type';
import { Command } from '../../src/cli-command';
const expect = chai.expect;
chai.use(sinonChai);
suite('Tekton/TaskRun', () => {
const sandbox = sinon.createSandbox();
let execStub: sinon.SinonStub;
let showErrorMessageStub: sinon.SinonStub;
let unlinkStub: sinon.SinonStub;
let getPipelineRunNamesStub: sinon.SinonStub;
let showQuickPickStub: sinon.SinonStub<unknown[], unknown>;
const pipelineItem = new TestItem(null, 'pipeline', ContextType.PIPELINE);
const pipelineRunItem = new TestItem(pipelineItem, 'pipelinerun', ContextType.PIPELINERUN, undefined, '2019-07-25T12:03:00Z', 'True');
const taskRunItem = new TestItem(pipelineRunItem, 'taskrun', ContextType.PIPELINERUN, undefined, '2019-07-25T12:03:00Z', 'True');
let showLogInEditorStub: sinon.SinonStub;
let configurationStub: sinon.SinonStub;
let osStub: sinon.SinonStub;
let writeFileStub: sinon.SinonStub;
let showInformationMessageStub: sinon.SinonStub;
setup(() => {
execStub = sandbox.stub(TknImpl.prototype, 'execute').resolves({ error: null, stdout: '', stderr: '' });
showQuickPickStub = sandbox.stub(vscode.window, 'showQuickPick').resolves(undefined);
getPipelineRunNamesStub = sandbox.stub(TektonItem, 'getPipelineRunNames').resolves([pipelineRunItem]);
sandbox.stub(TknImpl.prototype, 'getPipelineRunsList').resolves([pipelineRunItem]);
sandbox.stub(TknImpl.prototype, 'getTasks').resolves([taskRunItem]);
sandbox.stub(vscode.window, 'showInputBox').resolves();
osStub = sandbox.stub(os, 'tmpdir').resolves();
unlinkStub = sandbox.stub(fs, 'unlink').resolves();
showInformationMessageStub = sandbox.stub(vscode.window, 'showInformationMessage').resolves();
showErrorMessageStub = sandbox.stub(vscode.window, 'showErrorMessage').resolves();
writeFileStub = sandbox.stub(fs, 'writeFile').resolves();
showLogInEditorStub = sandbox.stub(logInEditor, 'showLogInEditor').resolves();
configurationStub = sandbox.stub(vscode.workspace, 'getConfiguration').returns({ get: () => false } as unknown as vscode.WorkspaceConfiguration);
});
teardown(() => {
sandbox.restore();
});
suite('list command', () => {
let termStub: sinon.SinonStub;
setup(() => {
termStub = sandbox.stub(TknImpl.prototype, 'executeInTerminal').resolves();
});
suite('called from \'Tekton Pipelines Explorer\'', () => {
test('executes the list tkn command in terminal', async () => {
await TaskRun.listFromPipelineRun(taskRunItem);
expect(termStub).calledOnceWith(Command.listTaskRunsForPipelineRunInTerminal(taskRunItem.getName()));
});
});
suite('called from command palette', () => {
test('calls the appropriate error message when no project found', async () => {
getPipelineRunNamesStub.restore();
try {
await TaskRun.listFromPipelineRun(null);
} catch (err) {
expect(err.message).equals('You need at least one PipelineRun available. Please create new Tekton PipelineRun and try again.');
return;
}
});
});
suite('called from command bar', () => {
teardown(() => {
termStub.restore();
});
test('skips tkn command execution if canceled by user', async () => {
showQuickPickStub.onFirstCall().resolves(undefined);
await TaskRun.listFromPipelineRun(null);
// tslint:disable-next-line: no-unused-expression
expect(termStub).not.called;
});
});
suite('listFromTasks command', () => {
const taskItem = new TestItem(null, 'task', ContextType.TASK);
suite('called from \'Tekton Pipelines Explorer\'', () => {
test('executes the listFromTasks tkn command in terminal', async () => {
await TaskRun.listFromTask(taskItem);
expect(termStub).calledOnceWith(Command.listTaskRunsForTasksInTerminal(taskItem.getName()));
});
});
suite('called from command palette', () => {
test('calls the appropriate error message when no project found', async () => {
sandbox.stub(TknImpl.prototype, 'getTaskRunsForTasks').resolves([]);
try {
await TaskRun.listFromTask(null);
} catch (err) {
expect(err.message).equals('You need at least one Task available. Please create new Tekton Task and try again.');
return;
}
});
});
suite('called from command bar', () => {
test('skips tkn command execution if canceled by user', async () => {
showQuickPickStub.onFirstCall().resolves(undefined);
await TaskRun.listFromTask(null);
// tslint:disable-next-line: no-unused-expression
expect(termStub).not.called;
});
});
});
suite('log output', () => {
test('Log calls the correct tkn command in terminal w/ context', async () => {
await TaskRun.logs(taskRunItem);
expect(termStub).calledOnceWith(Command.showTaskRunLogs(taskRunItem.getName()));
termStub.restore();
});
test('Show log in editor', async () => {
configurationStub.returns({ get: () => true } as unknown as vscode.WorkspaceConfiguration);
await TaskRun.logs(taskRunItem);
expect(showLogInEditorStub).calledOnceWith(Command.showTaskRunLogs(taskRunItem.getName()));
});
});
suite('followLog', () => {
test('followLog calls the correct tkn command in terminal', async () => {
await TaskRun.followLogs(taskRunItem);
expect(termStub).calledOnceWith(Command.showTaskRunFollowLogs(taskRunItem.getName()));
});
test('Show followLog log in editor', async () => {
configurationStub.returns({ get: () => true } as unknown as vscode.WorkspaceConfiguration);
await TaskRun.followLogs(taskRunItem);
expect(showLogInEditorStub).calledOnceWith(Command.showTaskRunFollowLogs(taskRunItem.getName()));
});
});
});
suite('Open Task Definition', () => {
let loadTektonResourceStub: sinon.SinonStub;
setup(() => {
loadTektonResourceStub = sandbox.stub(TektonItem, 'loadTektonResource')
});
test('openDefinition should ask taskrun definition', async () => {
execStub.resolves({ stdout: '{"metadata":{"labels": {"tekton.dev/task": "FooTaskName"}}, "spec":{"taskRef":{"kind": "FooKind"}}}' } as CliExitData);
loadTektonResourceStub.returns(undefined);
await TaskRun.openDefinition(taskRunItem);
expect(execStub).calledOnceWith(Command.getTaskRun(taskRunItem.getName()));
expect(loadTektonResourceStub).calledOnceWith('FooKind', 'FooTaskName');
});
test('openDefinition should check errors on fetching taskrun definition', async () => {
execStub.resolves({ error: 'Foo error' } as CliExitData);
loadTektonResourceStub.returns(undefined);
await TaskRun.openDefinition(taskRunItem);
expect(execStub).calledOnceWith(Command.getTaskRun(taskRunItem.getName()));
expect(loadTektonResourceStub).not.called;
expect(showErrorMessageStub).calledOnceWith('TaskRun may not have started yet, try again when it starts running. "Foo error"');
});
test('openDefinition should show error if trying to open condition taskrun', async () => {
execStub.resolves({ stdout: '{"metadata":{"labels": {"tekton.dev/task": "FooTaskName","tekton.dev/conditionCheck": "bar-condition-run"}}, "spec":{"taskRef":{"kind": "FooKind"}}}' } as CliExitData);
loadTektonResourceStub.returns(undefined);
await TaskRun.openDefinition(taskRunItem);
expect(execStub).calledOnceWith(Command.getTaskRun(taskRunItem.getName()));
expect(loadTektonResourceStub).not.called;
expect(showErrorMessageStub).calledOnceWith('Cannot find Condition definition for: taskrun. Please look in Pipeline definition');
});
});
suite('Open Task Definition', () => {
test('Restart taskRun', async () => {
execStub.onFirstCall().resolves({ stdout: JSON.stringify({
apiVersion:'tekton.dev/v1beta1',
kind: 'TaskRun',
metadata: {
name: 'send-cloud-event',
},
spec: {
resources: {
outputs: [
{
name: 'myimage',
resourceSpec: {
params: [
{
name: 'url',
value: 'fake'
}
]
}
}
]
},
serviceAccountName: 'default',
taskRef: {
kind: 'Task',
name: 'send-cloud-event-task'
},
}
})});
osStub.returns('path');
execStub.onSecondCall().resolves({ stdout: 'successfully created'});
await TaskRun.restartTaskRun(taskRunItem);
unlinkStub.calledOnce;
osStub.calledOnce;
writeFileStub.calledOnce;
showInformationMessageStub.calledOnce;
execStub.calledTwice;
expect(showInformationMessageStub).calledOnceWith('TaskRun successfully restarted');
});
test('show error message if fails to restart taskRun', async () => {
execStub.onFirstCall().resolves({ stdout: JSON.stringify({
apiVersion:'tekton.dev/v1beta1',
kind: 'TaskRun',
metadata: {
name: 'send-cloud-event',
},
spec: {
resources: {
outputs: [
{
name: 'myimage',
resourceSpec: {
params: [
{
name: 'url',
value: 'fake'
}
]
}
}
]
},
serviceAccountName: 'default',
taskRef: {
kind: 'Task',
name: 'send-cloud-event-task'
},
}
})});
osStub.returns('path');
execStub.onSecondCall().resolves({ error: 'fails'});
await TaskRun.restartTaskRun(taskRunItem);
unlinkStub.calledOnce;
osStub.calledOnce;
writeFileStub.calledOnce;
showErrorMessageStub.calledOnce;
execStub.calledTwice;
expect(showErrorMessageStub).calledOnceWith('Fail to restart TaskRun: fails');
});
});
}); | the_stack |
import { assert } from 'chai';
import { Shape } from '../../src/Shape.js';
import { addStage, Konva, compareLayers, isNode } from './test-utils';
describe('Container', function () {
// ======================================================
it('clip', function () {
var stage = addStage();
var layer = new Konva.Layer({
clip: { x: 0, y: 0, width: stage.width() / 2, height: 100 },
});
var group = new Konva.Group();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
name: 'myCircle',
draggable: true,
});
stage.add(layer);
layer.add(group);
group.add(circle);
layer.draw();
var trace = layer.getContext().getTrace();
assert.equal(
trace,
'clearRect(0,0,578,200);save();transform(1,0,0,1,0,0);beginPath();rect(0,0,289,100);clip();transform(1,0,0,1,0,0);restore();clearRect(0,0,578,200);save();transform(1,0,0,1,0,0);beginPath();rect(0,0,289,100);clip();transform(1,0,0,1,0,0);save();transform(1,0,0,1,289,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=green;fill();lineWidth=4;strokeStyle=black;stroke();restore();restore();'
);
});
// ======================================================
it('clip function', function () {
var stage = addStage();
// cliped by circle is the same as draw circle
var layer = new Konva.Layer();
stage.add(layer);
var circle = new Konva.Circle({
fill: 'black',
x: 50,
y: 50,
radius: 40,
});
layer.add(circle);
layer.draw();
var clipedLayer = new Konva.Layer({
clipFunc: function (ctx) {
ctx.arc(50, 50, 40, 0, Math.PI * 2, false);
},
});
stage.add(clipedLayer);
var rect = new Konva.Rect({
x: 10,
y: 10,
fill: 'black',
width: 200,
height: 200,
});
clipedLayer.add(rect);
stage.draw();
compareLayers(layer, clipedLayer, 150);
});
// ======================================================
it('clip function', function () {
if (isNode) {
// how to use Path2D in nodejs env?
return;
}
var stage = addStage();
// cliped by circle is the same as draw circle
var layer = new Konva.Layer();
stage.add(layer);
var circle = new Konva.Circle({
fill: 'black',
x: 50,
y: 50,
radius: 40,
});
layer.add(circle);
layer.draw();
var clipedLayer = new Konva.Layer({
clipFunc: function (ctx) {
const path2D = new Path2D();
path2D.arc(50, 50, 40, 0, Math.PI * 2, false);
ctx.fill(path2D);
},
});
stage.add(clipedLayer);
var rect = new Konva.Rect({
x: 10,
y: 10,
fill: 'black',
width: 200,
height: 200,
});
clipedLayer.add(rect);
stage.draw();
compareLayers(layer, clipedLayer, 150);
});
// ======================================================
it('adder validation', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
name: 'myCircle',
});
stage.add(layer);
layer.add(group);
group.add(circle);
layer.draw();
// disassemble the tree
circle.remove();
group.remove();
layer.remove();
// ===================================
var errorThrown = false;
try {
stage.add(stage as any);
} catch (err) {
errorThrown = true;
}
assert.equal(
errorThrown,
true,
'error should have been thrown when adding stage to stage'
);
stage.remove();
// ===================================
var errorThrown = false;
try {
stage.add(group as any);
} catch (err) {
errorThrown = true;
}
assert.equal(
errorThrown,
true,
'error should have been thrown when adding group to stage'
);
group.remove();
// ===================================
var errorThrown = false;
try {
stage.add(circle as any);
} catch (err) {
errorThrown = true;
}
assert.equal(
errorThrown,
true,
'error should have been thrown when adding shape to stage'
);
circle.remove();
// ===================================
var errorThrown = false;
try {
layer.add(stage as any);
} catch (err) {
errorThrown = true;
}
assert.equal(
errorThrown,
true,
'error should have been thrown when adding stage to layer'
);
stage.remove();
// ===================================
var errorThrown = false;
try {
layer.add(layer);
} catch (err) {
errorThrown = true;
}
assert.equal(
errorThrown,
true,
'error should have been thrown when adding layer to layer'
);
layer.remove();
// ===================================
var errorThrown = false;
try {
group.add(stage as any);
} catch (err) {
errorThrown = true;
}
assert.equal(
errorThrown,
true,
'error should have been thrown when adding stage to group'
);
stage.remove();
// ===================================
var errorThrown = false;
try {
group.add(layer);
} catch (err) {
errorThrown = true;
}
assert.equal(
errorThrown,
true,
'error should have been thrown when adding layer to group'
);
layer.remove();
});
// ======================================================
it('add layer then group then shape', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
name: 'myCircle',
});
// these should all pass because they are valid
stage.add(layer);
layer.add(group);
group.add(circle);
layer.draw();
var trace = layer.getContext().getTrace();
assert.equal(
trace,
'clearRect(0,0,578,200);clearRect(0,0,578,200);save();transform(1,0,0,1,289,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=green;fill();lineWidth=4;strokeStyle=black;stroke();restore();'
);
});
// ======================================================
it('add shape then stage then layer', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
name: 'myCircle',
});
group.add(circle);
stage.add(layer);
layer.add(group);
layer.draw();
var trace = layer.getContext().getTrace();
assert.equal(
trace,
'clearRect(0,0,578,200);clearRect(0,0,578,200);save();transform(1,0,0,1,289,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=green;fill();lineWidth=4;strokeStyle=black;stroke();restore();'
);
});
// ======================================================
it('select shape by id and name', function () {
var stage = addStage();
var layer = new Konva.Layer({
id: 'myLayer',
});
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
id: 'myCircle',
});
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'myRect',
});
layer.add(circle);
layer.add(rect);
stage.add(layer);
var node;
node = stage.find('#myCircle')[0];
assert.equal(node.className, 'Circle', 'className should be Circle');
node = layer.find('.myRect')[0];
assert.equal(node.className, 'Rect', 'className should be rect');
node = layer.find('#myLayer')[0];
assert.equal(node, undefined, 'node should be undefined');
node = stage.find('#myLayer')[0];
assert.equal(node.nodeType, 'Layer', 'node type should be Layer');
});
// ======================================================
it('select shape by name with "-" char', function () {
var stage = addStage();
var layer = new Konva.Layer();
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'bounding-box',
});
layer.add(rect);
stage.add(layer);
var node = stage.find('.bounding-box')[0];
assert.equal(node, rect);
});
// ======================================================
it('select should return elements in their order', function () {
var stage = addStage();
var layer = new Konva.Layer();
stage.add(layer);
// create circle before any nodes
var circle = new Konva.Circle({
radius: 50,
fill: 'red',
name: 'node',
});
var group = new Konva.Group({
name: 'node',
});
layer.add(group);
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'node',
});
group.add(rect);
group.add(circle);
// move circle
circle.moveToBottom();
assert.equal(layer.findOne('.node'), group, 'group here');
var nodes = layer.find('.node');
assert.equal(nodes[0], group, 'group first');
assert.equal(nodes[1], circle, 'then circle');
assert.equal(nodes[2], rect, 'then rect');
assert.equal(layer.findOne('Shape'), circle, 'circle is first');
});
// ======================================================
it('select shape with findOne', function () {
var stage = addStage();
var layer = new Konva.Layer({
id: 'myLayer',
});
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
id: 'myCircle',
});
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'myRect',
});
layer.add(circle);
layer.add(rect);
stage.add(layer);
var node;
node = stage.findOne('#myCircle');
assert.equal(node, circle);
node = layer.findOne('.myRect');
assert.equal(node, rect);
node = layer.findOne('#myLayer');
assert.equal(node, undefined, 'node should be undefined');
node = stage.findOne('#myLayer');
assert.equal(node, layer, 'node type should be Layer');
node = stage.findOne(function (node) {
return node.getType() === 'Shape';
});
assert.equal(node, circle, 'findOne should work with functions');
});
// ======================================================
it('select shapes with multiple selectors', function () {
var stage = addStage();
var layer = new Konva.Layer({
id: 'myLayer',
});
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
id: 'myCircle',
});
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'myRect',
});
layer.add(circle);
layer.add(rect);
stage.add(layer);
assert.equal(
layer.find('#myCircle, .myRect').length,
2,
'should be 2 items in the array'
);
assert.equal(
layer.find('#myCircle, .myRect')[0]._id,
circle._id,
'circle id is wrong'
);
assert.equal(
layer.find('#myCircle, .myRect')[1]._id,
rect._id,
'rect id is wrong'
);
assert.equal(
layer.find('#myCircle, Circle, .myRect, Rect').length,
2,
'should be 2 items in the array'
);
assert.equal(
layer.find('#myCircle, Circle, .myRect, Rect')[0]._id,
circle._id,
'circle id is wrong'
);
assert.equal(
layer.find('#myCircle, Circle, .myRect, Rect')[1]._id,
rect._id,
'rect id is wrong'
);
});
// ======================================================
it('select shape by function', function () {
var stage = addStage();
var layer = new Konva.Layer();
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'myRect',
});
layer.add(rect);
stage.add(layer);
var fn = function (node) {
return node.nodeType === 'Shape';
};
var noOp = function (node) {
return false;
};
assert.equal(stage.find(fn)[0], rect);
assert.equal(stage.find(noOp).length, 0);
});
// ======================================================
it('select shape with duplicate id', function () {
var stage = addStage();
var layer = new Konva.Layer();
stage.add(layer);
var rect1 = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
id: 'myRect',
});
layer.add(rect1);
var rect2 = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
id: 'myRect',
});
layer.add(rect2);
stage.draw();
assert.equal(stage.find('#myRect').length, 2);
assert.equal(stage.find('#myRect')[0], rect1);
assert.equal(stage.find('#myRect')[1], rect2);
});
// ======================================================
it('set x on an array of nodes', function () {
var stage = addStage();
var layer = new Konva.Layer();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
name: 'myShape',
});
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'myShape',
});
layer.add(circle);
layer.add(rect);
stage.add(layer);
var shapes = layer.find('.myShape');
assert.equal(shapes.length, 2, 'shapes array should have 2 elements');
shapes.forEach(function (node) {
node.x(200);
});
layer.draw();
shapes.forEach(function (node) {
assert.equal(node.x(), 200, 'shape x should be 200');
});
});
// ======================================================
it('set fill on array by Shape-selector', function () {
var stage = addStage();
var layer = new Konva.Layer();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
name: 'myShape',
});
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'myShape',
});
layer.add(circle);
layer.add(rect);
stage.add(layer);
var shapes = layer.find<Shape>('Shape');
assert.equal(shapes.length, 2, 'shapes array should have 2 elements');
shapes.forEach(function (node) {
node.fill('gray');
});
layer.draw();
shapes.forEach(function (node) {
assert.equal(node.fill(), 'gray', 'shape x should be 200');
});
});
// ======================================================
it('add listener to an array of nodes', function () {
var stage = addStage();
var layer = new Konva.Layer();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
name: 'myShape',
});
var rect = new Konva.Rect({
x: 300,
y: 100,
width: 100,
height: 50,
fill: 'purple',
stroke: 'black',
strokeWidth: 4,
name: 'myShape',
});
layer.add(circle);
layer.add(rect);
stage.add(layer);
var shapes = layer.find('.myShape');
assert.equal(shapes.length, 2, 'shapes array should have 2 elements');
var a = 0;
shapes.forEach((shape) =>
shape.on('mouseover', function () {
a++;
})
);
circle.fire('mouseover');
assert.equal(a, 1, 'listener should have fired for circle');
rect.fire('mouseover');
assert.equal(a, 2, 'listener should have fired for rect');
});
// ======================================================
it('remove all children from layer', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var circle1 = new Konva.Circle({
x: 100,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
var circle2 = new Konva.Circle({
x: 300,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
group.add(circle1);
group.add(circle2);
layer.add(group);
stage.add(layer);
assert.equal(layer.children.length, 1, 'layer should have 1 children');
assert.equal(group.children.length, 2, 'group should have 2 children');
layer.removeChildren();
layer.draw();
assert.equal(layer.children.length, 0, 'layer should have 0 children');
assert.equal(
group.children.length,
2,
'group still should have 2 children'
);
});
// ======================================================
it('add group', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
group.add(circle);
layer.add(group);
stage.add(layer);
var trace = layer.getContext().getTrace();
assert.equal(
trace,
'clearRect(0,0,578,200);save();transform(1,0,0,1,289,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=green;fill();lineWidth=4;strokeStyle=black;stroke();restore();'
);
});
// ======================================================
it('create two groups, move first group', function () {
var stage = addStage();
var greenLayer = new Konva.Layer();
var blueLayer = new Konva.Layer();
var greenGroup = new Konva.Group();
var blueGroup = new Konva.Group();
var greencircle = new Konva.Circle({
x: stage.width() / 2 - 100,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
draggable: true,
});
var bluecircle = new Konva.Circle({
x: stage.width() / 2 + 100,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
greenGroup.add(greencircle);
blueGroup.add(bluecircle);
greenLayer.add(greenGroup);
blueLayer.add(blueGroup);
stage.add(greenLayer);
stage.add(blueLayer);
blueLayer.removeChildren();
var blueGroup2 = new Konva.Group();
var bluecircle2 = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
blueGroup2.add(bluecircle2);
blueLayer.add(blueGroup2);
blueLayer.draw();
blueGroup2.position({ x: 100, y: 0 });
blueLayer.draw();
var trace = blueLayer.getContext().getTrace();
assert.equal(
trace,
'clearRect(0,0,578,200);save();transform(1,0,0,1,389,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();clearRect(0,0,578,200);save();transform(1,0,0,1,289,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();clearRect(0,0,578,200);save();transform(1,0,0,1,389,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();'
);
});
// ======================================================
it('node type selector', function () {
var stage = addStage();
var layer = new Konva.Layer();
var fooLayer = new Konva.Layer();
var group = new Konva.Group();
var blue = new Konva.Rect({
x: 200,
y: 100,
width: 100,
height: 50,
fill: 'blue',
});
var red = new Konva.Rect({
x: 250,
y: 100,
width: 100,
height: 50,
fill: 'red',
});
group.add(red);
layer.add(blue);
layer.add(group);
stage.add(layer);
stage.add(fooLayer);
assert.equal(stage.find('Shape').length, 2, 'stage should have 2 shapes');
assert.equal(layer.find('Shape').length, 2, 'layer should have 2 shapes');
assert.equal(group.find('Shape').length, 1, 'layer should have 2 shapes');
assert.equal(stage.find('Layer').length, 2, 'stage should have 2 layers');
assert.equal(stage.find('Group').length, 1, 'stage should have 1 group');
assert.equal(layer.find('Group').length, 1, 'layer should have 1 group');
assert.equal(layer.find('Shape').length, 2, 'layer should have 2 shapes');
assert.equal(layer.find('Layer').length, 0, 'layer should have 0 layers');
assert.equal(
layer.find('Group, Rect').length,
3,
'layer should have 3 [group or rects]'
);
assert.equal(
fooLayer.find('Group').length,
0,
'layer should have 0 groups'
);
assert.equal(
fooLayer.find('Shape').length,
0,
'layer should have 0 shapes'
);
assert.equal(group.find('Shape').length, 1, 'group should have 1 shape');
assert.equal(group.find('Layer').length, 0, 'group should have 0 layers');
assert.equal(group.find('Group').length, 0, 'group should have 0 groups');
});
// ======================================================
it('node and shape type selector', function () {
var stage = addStage();
var layer = new Konva.Layer();
var layer2 = new Konva.Layer();
var fooLayer = new Konva.Layer();
var group = new Konva.Group();
var blue = new Konva.Rect({
x: 100,
y: 50,
width: 100,
height: 50,
fill: 'blue',
});
var red = new Konva.Rect({
x: 150,
y: 75,
width: 100,
height: 50,
fill: 'red',
});
var green = new Konva.Rect({
x: 200,
y: 100,
width: 100,
height: 50,
fill: 'green',
});
var blueCircle = new Konva.Circle({
x: 350,
y: 75,
radius: 40,
fill: 'blue',
});
var redCircle = new Konva.Circle({
x: 400,
y: 125,
radius: 40,
fill: 'red',
});
var textpath = new Konva.TextPath({
y: 35,
stroke: 'black',
strokeWidth: 1,
fill: 'orange',
fontSize: 18,
fontFamily: 'Arial',
text: "The quick brown fox jumped over the lazy dog's back",
data: 'M 10,10 300,150 550,150',
});
var path = new Konva.Path({
x: 200,
y: -75,
data: 'M200,100h100v50z',
fill: '#ccc',
stroke: '#333',
strokeWidth: 2,
shadowColor: 'black',
shadowBlur: 2,
shadowOffset: { x: 10, y: 10 },
shadowOpacity: 0.5,
});
var poly = new Konva.RegularPolygon({
x: stage.width() / 2,
y: stage.height() / 2,
sides: 5,
radius: 50,
fill: 'green',
stroke: 'blue',
strokeWidth: 5,
name: 'foobar',
});
group.add(red);
group.add(redCircle);
layer.add(blue);
layer.add(green);
layer.add(blueCircle);
layer.add(group);
layer2.add(textpath);
layer2.add(path);
layer2.add(poly);
stage.add(layer);
stage.add(layer2);
stage.add(fooLayer);
assert.equal(stage.find('Shape').length, 8, 'stage should have 5 shapes');
assert.equal(stage.find('Layer').length, 3, 'stage should have 2 layers');
assert.equal(stage.find('Group').length, 1, 'stage should have 1 group');
assert.equal(stage.find('Rect').length, 3, 'stage should have 3 rects');
assert.equal(stage.find('Circle').length, 2, 'stage should have 2 circles');
assert.equal(
stage.find('RegularPolygon').length,
1,
'stage should have 1 regular polygon'
);
assert.equal(
stage.find('TextPath').length,
1,
'stage should have 1 text path'
);
assert.equal(stage.find('Path').length, 1, 'stage should have 1 path');
assert.equal(layer.find('Shape').length, 5, 'layer should have 5 shapes');
assert.equal(layer.find('Layer').length, 0, 'layer should have 0 layers');
assert.equal(layer.find('Group').length, 1, 'layer should have 1 group');
assert.equal(layer.find('Rect').length, 3, 'layer should have 3 rects');
assert.equal(layer.find('Circle').length, 2, 'layer should have 2 circles');
assert.equal(
layer.find('RegularPolygon').length,
0,
'layer should have 0 regular polygon'
);
assert.equal(
layer.find('TextPath').length,
0,
'layer should have 0 text path'
);
assert.equal(layer.find('Path').length, 0, 'layer should have 0 path');
assert.equal(layer2.find('Shape').length, 3, 'layer2 should have 3 shapes');
assert.equal(layer2.find('Layer').length, 0, 'layer2 should have 0 layers');
assert.equal(layer2.find('Group').length, 0, 'layer2 should have 0 group');
assert.equal(
layer2.find('RegularPolygon').length,
1,
'layer2 should have 1 regular polygon'
);
assert.equal(
layer2.find('TextPath').length,
1,
'layer2 should have 1 text path'
);
assert.equal(layer2.find('Path').length, 1, 'layer2 should have 1 path');
assert.equal(
fooLayer.find('Shape').length,
0,
'layer should have 0 shapes'
);
assert.equal(
fooLayer.find('Group').length,
0,
'layer should have 0 groups'
);
assert.equal(fooLayer.find('Rect').length, 0, 'layer should have 0 rects');
assert.equal(
fooLayer.find('Circle').length,
0,
'layer should have 0 circles'
);
assert.equal(group.find('Shape').length, 2, 'group should have 2 shape');
assert.equal(group.find('Layer').length, 0, 'group should have 0 layers');
assert.equal(group.find('Group').length, 0, 'group should have 0 groups');
assert.equal(group.find('Rect').length, 1, 'group should have 1 rects');
assert.equal(group.find('Circle').length, 1, 'gropu should have 1 circles');
});
// ======================================================
it('test find() selector by adding shapes with multiple names', function () {
var stage = addStage();
var layer = new Konva.Layer({
name: 'layerName',
id: 'layerId',
});
var group = new Konva.Group({
name: 'groupName',
id: 'groupId',
});
var rect = new Konva.Rect({
x: 200,
y: 20,
width: 100,
height: 50,
fill: 'red',
name: 'red rectangle',
id: 'rectId',
});
var circle = new Konva.Circle({
x: 50,
y: 50,
radius: 20,
fill: 'red',
name: 'red circle',
id: 'circleId',
});
group.add(rect);
group.add(circle);
layer.add(group);
stage.add(layer);
assert.equal(
stage.find('.rectangle')[0],
rect,
'problem with shape name selector'
);
assert.equal(
layer.find('.rectangle')[0],
rect,
'problem with shape name selector'
);
assert.equal(
group.find('.rectangle')[0],
rect,
'problem with shape name selector'
);
assert.equal(
stage.find('.circle')[0],
circle,
'problem with shape name selector'
);
assert.equal(
layer.find('.circle')[0],
circle,
'problem with shape name selector'
);
assert.equal(
group.find('.circle')[0],
circle,
'problem with shape name selector'
);
assert.equal(
stage.find('.red')[0],
rect,
'problem with shape name selector'
);
assert.equal(
stage.find('.red')[1],
circle,
'problem with shape name selector'
);
assert.equal(
layer.find('.red')[0],
rect,
'problem with shape name selector'
);
assert.equal(
layer.find('.red')[1],
circle,
'problem with shape name selector'
);
assert.equal(
group.find('.red')[0],
rect,
'problem with shape name selector'
);
assert.equal(
group.find('.red')[1],
circle,
'problem with shape name selector'
);
assert.equal(
stage.find('.groupName')[0],
group,
'problem with group name selector'
);
assert.equal(
layer.find('.groupName')[0],
group,
'problem with group name selector'
);
assert.equal(
stage.find('.layerName')[0],
layer,
'problem with layer name selector'
);
});
// ======================================================
it('test find() selector by adding shape, then group, then layer', function () {
var stage = addStage();
var layer = new Konva.Layer({
name: 'layerName',
id: 'layerId',
});
var group = new Konva.Group({
name: 'groupName',
id: 'groupId',
});
var rect = new Konva.Rect({
x: 200,
y: 20,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
name: 'rectName',
id: 'rectId',
});
group.add(rect);
layer.add(group);
stage.add(layer);
assert.equal(
stage.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
stage.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
layer.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
layer.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
group.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
group.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
stage.find('.groupName')[0].attrs.id,
'groupId',
'problem with group name selector'
);
assert.equal(
stage.find('#groupId')[0].attrs.id,
'groupId',
'problem with group id selector'
);
assert.equal(
layer.find('.groupName')[0].attrs.id,
'groupId',
'problem with group name selector'
);
assert.equal(
layer.find('#groupId')[0].attrs.id,
'groupId',
'problem with group id selector'
);
assert.equal(
stage.find('.layerName')[0].attrs.id,
'layerId',
'problem with layer name selector'
);
assert.equal(
stage.find('#layerId')[0].attrs.id,
'layerId',
'problem with layer id selector'
);
});
// ======================================================
it('test find() selector by adding group, then shape, then layer', function () {
var stage = addStage();
var layer = new Konva.Layer({
name: 'layerName',
id: 'layerId',
});
var group = new Konva.Group({
name: 'groupName',
id: 'groupId',
});
var rect = new Konva.Rect({
x: 200,
y: 20,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
name: 'rectName',
id: 'rectId',
});
layer.add(group);
group.add(rect);
stage.add(layer);
assert.equal(
stage.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
stage.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
layer.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
layer.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
group.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
group.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
stage.find('.groupName')[0].attrs.id,
'groupId',
'problem with group name selector'
);
assert.equal(
stage.find('#groupId')[0].attrs.id,
'groupId',
'problem with group id selector'
);
assert.equal(
layer.find('.groupName')[0].attrs.id,
'groupId',
'problem with group name selector'
);
assert.equal(
layer.find('#groupId')[0].attrs.id,
'groupId',
'problem with group id selector'
);
assert.equal(
stage.find('.layerName')[0].attrs.id,
'layerId',
'problem with layer name selector'
);
assert.equal(
stage.find('#layerId')[0].attrs.id,
'layerId',
'problem with layer id selector'
);
});
// ======================================================
it('test find() selector by adding group, then layer, then shape', function () {
var stage = addStage();
var layer = new Konva.Layer({
name: 'layerName',
id: 'layerId',
});
var group = new Konva.Group({
name: 'groupName',
id: 'groupId',
});
var rect = new Konva.Rect({
x: 200,
y: 20,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
name: 'rectName',
id: 'rectId',
});
layer.add(group);
stage.add(layer);
group.add(rect);
assert.equal(
stage.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
stage.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
layer.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
layer.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
group.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
group.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
stage.find('.groupName')[0].attrs.id,
'groupId',
'problem with group name selector'
);
assert.equal(
stage.find('#groupId')[0].attrs.id,
'groupId',
'problem with group id selector'
);
assert.equal(
layer.find('.groupName')[0].attrs.id,
'groupId',
'problem with group name selector'
);
assert.equal(
layer.find('#groupId')[0].attrs.id,
'groupId',
'problem with group id selector'
);
assert.equal(
stage.find('.layerName')[0].attrs.id,
'layerId',
'problem with layer name selector'
);
assert.equal(
stage.find('#layerId')[0].attrs.id,
'layerId',
'problem with layer id selector'
);
});
// ======================================================
it('test find() selector by adding layer, then group, then shape', function () {
var stage = addStage();
var layer = new Konva.Layer({
name: 'layerName',
id: 'layerId',
});
var group = new Konva.Group({
name: 'groupName',
id: 'groupId',
});
var rect = new Konva.Rect({
x: 200,
y: 20,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
name: 'rectName',
id: 'rectId',
});
stage.add(layer);
layer.add(group);
group.add(rect);
assert.equal(
stage.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
stage.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
layer.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
layer.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
group.find('.rectName')[0].attrs.id,
'rectId',
'problem with shape name selector'
);
assert.equal(
group.find('#rectId')[0].attrs.id,
'rectId',
'problem with shape id selector'
);
assert.equal(
stage.find('.groupName')[0].attrs.id,
'groupId',
'problem with group name selector'
);
assert.equal(
stage.find('#groupId')[0].attrs.id,
'groupId',
'problem with group id selector'
);
assert.equal(
layer.find('.groupName')[0].attrs.id,
'groupId',
'problem with group name selector'
);
assert.equal(
layer.find('#groupId')[0].attrs.id,
'groupId',
'problem with group id selector'
);
assert.equal(
stage.find('.layerName')[0].attrs.id,
'layerId',
'problem with layer name selector'
);
assert.equal(
stage.find('#layerId')[0].attrs.id,
'layerId',
'problem with layer id selector'
);
layer.draw();
});
it('warn on invalid selector', function () {
var stage = addStage();
var layer = new Konva.Layer({
name: 'layerName',
id: 'layerId',
});
var group = new Konva.Group({
name: 'groupName',
id: 'groupId',
});
var rect = new Konva.Rect({
x: 200,
y: 20,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
name: 'rectName',
id: 'rectId',
});
stage.add(layer);
layer.add(group);
group.add(rect);
layer.draw();
var counter = 0;
var oldWarn = Konva.Util.warn;
Konva.Util.warn = function () {
counter += 1;
};
// forgot dot
group.find('rectName');
assert.equal(counter > 0, true);
Konva.Util.warn = oldWarn;
});
// ======================================================
it('add layer then shape', function () {
var stage = addStage();
var layer = new Konva.Layer();
var circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
name: 'myCircle',
});
stage.add(layer);
layer.add(circle);
layer.draw();
assert(layer.getChildren().length === 1);
});
// ======================================================
it('move blue layer on top of green layer with setZIndex', function () {
var stage = addStage();
var blueLayer = new Konva.Layer();
var greenLayer = new Konva.Layer();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
blueLayer.add(bluecircle);
greenLayer.add(greencircle);
stage.add(blueLayer);
stage.add(greenLayer);
blueLayer.setZIndex(1);
//console.log(greenLayer.getZIndex());
assert.equal(
greenLayer.getZIndex(),
0,
'green layer should have z index of 0'
);
assert.equal(
blueLayer.getZIndex(),
1,
'blue layer should have z index of 1'
);
});
// ======================================================
it('move blue layer on top of green layer with moveToTop', function () {
var stage = addStage();
var blueLayer = new Konva.Layer();
var greenLayer = new Konva.Layer();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
blueLayer.add(bluecircle);
greenLayer.add(greencircle);
stage.add(blueLayer);
stage.add(greenLayer);
blueLayer.moveToTop();
assert(blueLayer.zIndex() === 1);
assert(greenLayer.zIndex() === 0);
});
// ======================================================
it('move green layer below blue layer with moveToBottom', function () {
var stage = addStage();
var blueLayer = new Konva.Layer();
var greenLayer = new Konva.Layer();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
blueLayer.add(bluecircle);
greenLayer.add(greencircle);
stage.add(blueLayer);
stage.add(greenLayer);
greenLayer.moveToBottom();
assert(blueLayer.zIndex() === 1);
assert(greenLayer.zIndex() === 0);
});
// ======================================================
it('move green layer below blue layer with moveDown', function () {
var stage = addStage();
var blueLayer = new Konva.Layer();
var greenLayer = new Konva.Layer();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
blueLayer.add(bluecircle);
greenLayer.add(greencircle);
stage.add(blueLayer);
stage.add(greenLayer);
greenLayer.moveDown();
assert(blueLayer.zIndex() === 1);
assert(greenLayer.zIndex() === 0);
});
// ======================================================
it('move blue layer above green layer with moveUp', function () {
var stage = addStage();
var blueLayer = new Konva.Layer();
var greenLayer = new Konva.Layer();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
blueLayer.add(bluecircle);
greenLayer.add(greencircle);
stage.add(blueLayer);
stage.add(greenLayer);
blueLayer.moveUp();
assert(blueLayer.zIndex() === 1);
assert(greenLayer.zIndex() === 0);
});
// ======================================================
it('move blue circle on top of green circle with moveToTop', function () {
var stage = addStage();
var layer = new Konva.Layer();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
layer.add(bluecircle);
layer.add(greencircle);
stage.add(layer);
assert.equal(
bluecircle.getZIndex(),
0,
'blue circle should have zindex 0 before relayering'
);
assert.equal(
greencircle.getZIndex(),
1,
'green circle should have zindex 1 before relayering'
);
bluecircle.moveToTop();
assert.equal(
bluecircle.getZIndex(),
1,
'blue circle should have zindex 1 after relayering'
);
assert.equal(
greencircle.getZIndex(),
0,
'green circle should have zindex 0 after relayering'
);
layer.draw();
});
// ======================================================
it('move green circle below blue circle with moveDown', function () {
var stage = addStage();
var layer = new Konva.Layer();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
layer.add(bluecircle);
layer.add(greencircle);
stage.add(layer);
assert.equal(
bluecircle.getZIndex(),
0,
'blue circle should have zindex 0 before relayering'
);
assert.equal(
greencircle.getZIndex(),
1,
'green circle should have zindex 1 before relayering'
);
greencircle.moveDown();
assert.equal(
bluecircle.getZIndex(),
1,
'blue circle should have zindex 1 after relayering'
);
assert.equal(
greencircle.getZIndex(),
0,
'green circle should have zindex 0 after relayering'
);
layer.draw();
});
// ======================================================
it('layer layer when only one layer', function () {
var stage = addStage();
var layer = new Konva.Layer();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
layer.add(bluecircle);
stage.add(layer);
assert.equal(layer.getZIndex(), 0, 'layer should have zindex of 0');
layer.moveDown();
assert.equal(layer.getZIndex(), 0, 'layer should have zindex of 0');
layer.moveToBottom();
assert.equal(layer.getZIndex(), 0, 'layer should have zindex of 0');
layer.moveUp();
assert.equal(layer.getZIndex(), 0, 'layer should have zindex of 0');
layer.moveToTop();
assert.equal(layer.getZIndex(), 0, 'layer should have zindex of 0');
});
// ======================================================
it('move blue group on top of green group with moveToTop', function () {
var stage = addStage();
var layer = new Konva.Layer();
var greenGroup = new Konva.Group();
var blueGroup = new Konva.Group();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
blueGroup.add(bluecircle);
greenGroup.add(greencircle);
layer.add(blueGroup);
layer.add(greenGroup);
stage.add(layer);
assert.equal(
blueGroup.getZIndex(),
0,
'blue group should have zindex 0 before relayering'
);
assert.equal(
greenGroup.getZIndex(),
1,
'green group should have zindex 1 before relayering'
);
blueGroup.moveToTop();
assert.equal(
blueGroup.getZIndex(),
1,
'blue group should have zindex 1 after relayering'
);
assert.equal(
greenGroup.getZIndex(),
0,
'green group should have zindex 0 after relayering'
);
layer.draw();
});
// ======================================================
it('move blue group on top of green group with moveUp', function () {
var stage = addStage();
var layer = new Konva.Layer();
var greenGroup = new Konva.Group();
var blueGroup = new Konva.Group();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var greencircle = new Konva.Circle({
x: 280,
y: stage.height() / 2,
radius: 70,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
blueGroup.add(bluecircle);
greenGroup.add(greencircle);
layer.add(blueGroup);
layer.add(greenGroup);
stage.add(layer);
assert.equal(
blueGroup.getZIndex(),
0,
'blue group should have zindex 0 before relayering'
);
assert.equal(
greenGroup.getZIndex(),
1,
'green group should have zindex 1 before relayering'
);
blueGroup.moveUp();
assert.equal(
blueGroup.getZIndex(),
1,
'blue group should have zindex 1 after relayering'
);
assert.equal(
greenGroup.getZIndex(),
0,
'green group should have zindex 0 after relayering'
);
layer.draw();
});
// ======================================================
it('add and moveTo should work same way (depend on parent)', function () {
var stage = addStage();
var layer = new Konva.Layer();
var greenGroup = new Konva.Group();
var blueGroup = new Konva.Group();
var bluecircle = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
bluecircle.moveTo(blueGroup);
layer.add(blueGroup);
layer.add(greenGroup);
stage.add(layer);
assert.equal(
blueGroup.getChildren().length,
1,
'blue group should have only one children'
);
blueGroup.add(bluecircle);
assert.equal(
blueGroup.getChildren().length,
1,
'blue group should have only one children after adding node twice'
);
greenGroup.add(bluecircle);
assert.equal(
blueGroup.getChildren().length,
0,
'blue group should not have children'
);
assert.equal(
greenGroup.getChildren().length,
1,
'green group should have only one children'
);
layer.draw();
});
// ======================================================
it('getChildren may use filter function', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var circle1 = new Konva.Circle({
x: 200,
y: stage.height() / 2,
radius: 70,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
var circle2 = circle1.clone();
group.add(circle1).add(circle2);
var rect = new Konva.Rect({
name: 'test',
});
group.add(rect);
var circles = group.getChildren(function (node) {
return node.getClassName() === 'Circle';
});
assert.equal(circles.length, 2, 'group has two circle children');
assert.equal(circles.indexOf(circle1) > -1, true);
assert.equal(circles.indexOf(circle2) > -1, true);
var testName = group.getChildren(function (node) {
return node.name() === 'test';
});
assert.equal(testName.length, 1, 'group has one children with test name');
layer.add(group);
layer.draw();
});
it('add multiple nodes to container', function () {
var stage = addStage();
var layer = new Konva.Layer();
var circle1 = new Konva.Circle({
x: 0,
y: 0,
radius: 10,
fill: 'red',
});
var circle2 = new Konva.Circle({
x: 0,
y: 0,
radius: 10,
fill: 'white',
});
var circle3 = new Konva.Circle({
x: 0,
y: 0,
radius: 10,
fill: 'blue',
});
layer.add(circle1, circle2, circle3);
assert.equal(
layer.getChildren().length,
3,
'layer has exactly three children'
);
});
it('getClientRect - adding a zero bounds shape should result in zero bounds', function () {
var stage = addStage();
var layer = new Konva.Layer();
stage.add(layer);
var grp = new Konva.Group();
var zeroRect = new Konva.Rect({ x: 0, y: 0, width: 0, height: 0 });
grp.add(zeroRect);
var bounds = grp.getClientRect();
assert.deepEqual(bounds, {
x: 0,
y: 0,
width: 0,
height: 0,
});
});
it('getClientRect - test empty case', function () {
var stage = addStage();
var layer = new Konva.Layer();
stage.add(layer);
var group = new Konva.Group({
x: 10,
y: 10,
});
group.add(new Konva.Group());
assert.deepEqual(group.getClientRect(), {
x: 10,
y: 10,
width: 0,
height: 0,
});
});
it('get client rect with deep nested hidden shape', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group({
draggable: true,
x: 100,
y: 40,
});
var rect = new Konva.Rect({
height: 100,
width: 100,
fill: 'red',
});
group.add(rect);
layer.add(group);
var subGroup = new Konva.Group();
group.add(subGroup);
subGroup.add(
new Konva.Rect({
visible: false,
})
);
stage.add(layer);
stage.draw();
var clientRect = group.getClientRect();
assert.deepEqual(clientRect, {
x: 100,
y: 40,
width: 100,
height: 100,
});
});
it('getClientRect - test group with invisible child', function () {
var stage = addStage();
var layer = new Konva.Layer();
stage.add(layer);
var group = new Konva.Group({
x: 10,
y: 10,
});
layer.add(group);
layer.draw();
group.add(
new Konva.Rect({
x: 0,
y: 0,
width: 50,
height: 50,
})
);
group.add(
new Konva.Rect({
x: 400,
y: 400,
width: 50,
height: 50,
visible: false,
})
);
assert.deepEqual(group.getClientRect(), {
x: 10,
y: 10,
width: 50,
height: 50,
});
});
it('getClientRect - test group with invisible child inside invisible parent', function () {
var stage = addStage();
var layer = new Konva.Layer({
visible: false,
});
stage.add(layer);
var group = new Konva.Group({
x: 10,
y: 10,
});
layer.add(group);
layer.draw();
group.add(
new Konva.Rect({
x: 0,
y: 0,
width: 50,
height: 50,
})
);
group.add(
new Konva.Rect({
x: 400,
y: 400,
width: 50,
height: 50,
visible: false,
})
);
assert.deepEqual(group.getClientRect(), {
x: 10,
y: 10,
width: 50,
height: 50,
});
});
it('getClientRect - test group with visible child inside invisible parent', function () {
var stage = addStage();
var layer = new Konva.Layer({
visible: false,
});
stage.add(layer);
var group = new Konva.Group({
x: 10,
y: 10,
});
layer.add(group);
var subGroup = new Konva.Group({
visible: false,
});
group.add(subGroup);
subGroup.add(
new Konva.Rect({
x: 0,
y: 0,
width: 50,
height: 50,
visible: true,
})
);
subGroup.add(
new Konva.Rect({
x: 400,
y: 400,
width: 50,
height: 50,
visible: true,
})
);
layer.draw();
assert.deepEqual(group.getClientRect(), {
x: 10,
y: 10,
width: 0,
height: 0,
});
});
it('get client rect with deep nested hidden shape 2', function () {
var layer = new Konva.Layer();
var group = new Konva.Group({
visible: false,
x: 100,
y: 40,
});
var rect = new Konva.Rect({
height: 100,
width: 100,
fill: 'red',
});
group.add(rect);
layer.add(group);
var clientRect = layer.getClientRect();
assert.deepEqual(clientRect, {
x: 0,
y: 0,
width: 0,
height: 0,
});
});
it('getClientRect - test layer', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var rect = new Konva.Rect({
x: 50,
y: 100,
width: 200,
height: 75,
fill: 'red',
});
group.add(rect);
layer.add(group);
stage.add(layer);
assert.deepEqual(layer.getClientRect(), {
x: 50,
y: 100,
width: 200,
height: 75,
});
});
it('getClientRect - nested group with a hidden shapes', function () {
var stage = addStage();
var layer = new Konva.Layer();
stage.add(layer);
var group1 = new Konva.Group();
layer.add(group1);
var rect = new Konva.Rect({
x: 50,
y: 100,
width: 200,
height: 75,
fill: 'red',
});
group1.add(rect);
var group2 = new Konva.Group();
layer.add(group2);
var rect2 = new Konva.Rect({
x: 0,
y: 0,
width: 200,
height: 75,
fill: 'red',
visible: false,
});
group1.add(rect2);
assert.deepEqual(layer.getClientRect(), {
x: 50,
y: 100,
width: 200,
height: 75,
});
});
it('clip-cache', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var circle = new Konva.Circle({
x: 50,
y: 50,
radius: 30,
fill: 'red',
});
group.add(circle);
layer.add(group.clip({ x: 25, y: 25, width: 50, height: 50 }));
stage.add(layer);
layer.cache();
stage.draw();
var data = layer.getContext().getImageData(24, 50, 1, 1).data;
var isTransparent = data[3] == 0;
assert.equal(
isTransparent,
true,
'tested pixel (24,50) should be transparent: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getContext().getImageData(50, 24, 1, 1).data;
isTransparent = data[3] == 0;
assert.equal(
isTransparent,
true,
'tested pixel (50,24) should be transparent: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getHitCanvas().getContext().getImageData(76, 50, 1, 1).data;
isTransparent = data[3] == 0;
assert.equal(
isTransparent,
true,
'tested pixel (76,50) should be transparent: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getHitCanvas().getContext().getImageData(50, 76, 1, 1).data;
isTransparent = data[3] == 0;
assert.equal(
isTransparent,
true,
'tested pixel (50,76) should be transparent: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
var ratio = layer.getCanvas().getPixelRatio();
data = layer.getContext().getImageData(26 * ratio, 50 * ratio, 1, 1).data;
var isRed =
data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255;
assert.equal(
isRed,
true,
'tested pixel (26,50) should be red: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getContext().getImageData(50 * ratio, 26 * ratio, 1, 1).data;
isRed = data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255;
assert.equal(
isRed,
true,
'tested pixel (50,26) should be red: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getContext().getImageData(74 * ratio, 50 * ratio, 1, 1).data;
isRed = data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255;
assert.equal(
isRed,
true,
'tested pixel (74,50) should be red: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getContext().getImageData(50 * ratio, 74 * ratio, 1, 1).data;
isRed = data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255;
assert.equal(
isRed,
true,
'tested pixel (50,74) should be red: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
});
it('clip-cache-scale', function () {
var stage = addStage();
var layer = new Konva.Layer();
var group = new Konva.Group();
var circle = new Konva.Circle({
x: 50,
y: 50,
radius: 30,
fill: 'red',
});
group.add(circle);
layer.add(group.clip({ x: 25, y: 25, width: 50, height: 50 }));
stage.add(layer);
layer.cache();
stage.scale({ x: 2, y: 2 });
stage.draw();
var data = layer.getHitCanvas().getContext().getImageData(48, 100, 1, 1)
.data;
var isTransparent = data[3] == 0;
assert.equal(
isTransparent,
true,
'tested pixel (48,100) should be transparent: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getHitCanvas().getContext().getImageData(100, 48, 1, 1).data;
isTransparent = data[3] == 0;
assert.equal(
isTransparent,
true,
'tested pixel (100,48) should be transparent: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getHitCanvas().getContext().getImageData(152, 100, 1, 1).data;
isTransparent = data[3] == 0;
assert.equal(
isTransparent,
true,
'tested pixel (152,100) should be transparent: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getHitCanvas().getContext().getImageData(100, 152, 1, 1).data;
isTransparent = data[3] == 0;
assert.equal(
isTransparent,
true,
'tested pixel (100,152) should be transparent: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
var ratio = layer.getCanvas().getPixelRatio();
data = layer.getContext().getImageData(52 * ratio, 100 * ratio, 1, 1).data;
var isRed =
data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255;
assert.equal(
isRed,
true,
'tested pixel (52,100) should be red: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getContext().getImageData(100 * ratio, 52 * ratio, 1, 1).data;
isRed = data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255;
assert.equal(
isRed,
true,
'tested pixel (100,52) should be red: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getContext().getImageData(148 * ratio, 100 * ratio, 1, 1).data;
isRed = data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255;
assert.equal(
isRed,
true,
'tested pixel (148,100) should be red: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
data = layer.getContext().getImageData(100 * ratio, 148 * ratio, 1, 1).data;
isRed = data[0] == 255 && data[1] == 0 && data[2] == 0 && data[3] == 255;
assert.equal(
isRed,
true,
'tested pixel (100,148) should be red: ' +
data[0] +
'_' +
data[1] +
'_' +
data[2] +
'_' +
data[3]
);
});
}); | the_stack |
import React, { useState } from 'react'
import ArrowRightIcon from 'mdi-react/ArrowRightIcon'
import Layout from '../components/Layout'
import Carousel from 'react-bootstrap/Carousel'
import { ContentSection } from '../components/content/ContentSection'
const CareersPage = props => {
return (
<Layout location={props.location} className="jobs-page">
<div>
<ContentSection className="hero-section">
<div className="row">
<div className="col-lg-10">
<h1 className="display-2 title">Let’s build the future together.</h1>
<h1 className="display-2 font-weight-normal">
We're developing the world's most advanced code search navigation platform with
brilliant dreamers around the globe.
</h1>
</div>
</div>
<a
className="btn btn-primary mt-4"
href="https://boards.greenhouse.io/sourcegraph91"
title="Explore our jobs"
target="_blank"
>
Explore our jobs
<ArrowRightIcon className="ml-3" />
</a>
</ContentSection>
<div>
<img src="../careers/careers_hero_img.png" className="mx-auto hero-image" />
<img src="../careers/careers_hero_img_mobile.jpg" className="mx-auto hero-image-mobile" />
</div>
<div className="benefits">
<div className="row">
<div className="m-auto">
<h2 className="col-lg-10 display-2 text-center mx-auto">
Happy, healthy, and always in the flow.
</h2>
<p className="col-lg-6 text-center mx-auto">
Our Teammates are our most valuable resource. That’s why we provide total rewards that
are highly competitive and allow you to thrive both personally and professionally.
</p>
<p className="text-center mt-3">
Learn more in{' '}
<a
target="_blank"
className="handbook-benefits-link"
href="https://handbook.sourcegraph.com/benefits-pay-perks/benefits-perks"
>
our handbook
</a>
.
</p>
</div>
</div>
<div className="row benefits-row">
<div className="benefit col-lg-3 col-md-5 my-3 text-center">
<img className="icon my-2 mx-auto" src="../careers/Remote.svg" />
<h3 className="my-2">Work fully remote</h3>
<p>Anywhere and at anytime</p>
</div>
<div className="benefit col-lg-3 col-md-5 my-3 text-center">
<img className="icon my-2 mx-auto" src="../careers/PTO.svg" />
<h3 className="my-2">Unlimited PTO</h3>
<p>...with a 30-day minimum</p>
</div>
<div className="benefit col-lg-3 col-md-5 my-3 text-center">
<img className="icon my-2 mx-auto" src="../careers/Travel.svg" />
<h3 className="my-2">Generous travel budgets</h3>
<p>Meet your team across the globe</p>
</div>
<div className="benefit col-lg-3 col-md-5 my-3 text-center">
<img className="icon my-2 mx-auto" src="../careers/Salary.svg" />
<h3 className="my-2">Competitive pay + equity</h3>
<p>So you can live your best life</p>
</div>
<div className="benefit col-lg-3 col-md-5 my-3 text-center">
<img className="icon my-2 mx-auto" src="../careers/Medical.svg" />
<h3 className="my-2">Medical, dental, and vision</h3>
<p>Got you covered 100% (US only)</p>
</div>
<div className="benefit col-lg-3 col-md-5 my-3 text-center">
<img className="icon my-2 mx-auto" src="../careers/ProfessionalDevelopment.svg" />
<h3 className="my-2">Professional development</h3>
<p>Find your thing and we pay for it</p>
</div>
<div className="benefit col-lg-3 col-md-5 my-3 text-center">
<img className="icon my-2 mx-auto" src="../careers/OfficeBudget.svg" />
<h3 className="my-2">Office budget</h3>
<p>Create a space where you thrive</p>
</div>
<div className="benefit col-lg-3 col-md-5 my-3 text-center">
<img className="icon my-2 mx-auto" src="../careers/Wellness.svg" />
<h3 className="my-2">Wellness budget</h3>
<p>Take care of yourself on our dime</p>
</div>
<div className="benefit col-lg-3 col-md-5 my-3 text-center mx-auto">
<img className="icon my-2 mx-auto" src="../careers/FamilyPlanning.svg" />
<h3 className="my-2">Family Planning benefits</h3>
<p>$25K, because family comes first</p>
</div>
</div>
</div>
<Carousel className="culture-carousel">
{/*
<Carousel.Item className="bg-gradient-blue2-blue">
<div className="row">
<h1 className="col-lg-6 my-auto">
<p>
Whether you're early in your career or have written a few books on coding, we have a
spot for you
</p>
</h1>
<div className="col-lg-6 img-container">
<img src="../careers/culture1.png" />
</div>
</div>
</Carousel.Item>
*/}
<Carousel.Item className="bg-gradient-blue-purple">
<div className="row">
<h1 className="col-lg-6 my-auto">
<p>
Just because we’re remote doesn’t mean we’re apart <br />
#life-at-sourcegraph
</p>
</h1>
<div className="col-lg-6 img-container">
<img src="../careers/culture2.png" />
</div>
</div>
</Carousel.Item>
<Carousel.Item className="bg-gradient-purple-yellow">
<div className="row">
<h1 className="col-lg-6 my-auto">
<p>
We’re moving <i>fast</i> to create a world in which everyone can code
</p>
</h1>
<div className="col-lg-6 img-container">
<img src="../careers/culture3.png" />
</div>
</div>
</Carousel.Item>
<Carousel.Item className="bg-gradient-yellow-green2">
<div className="row">
<h1 className="col-lg-6 my-auto">
<p>
Work whenever and wherever <br />
#life-is-beachy
</p>
</h1>
<div className="col-lg-6 img-container">
<img src="../careers/culture4.png" className="landscape" />
</div>
</div>
</Carousel.Item>
<Carousel.Item className="bg-gradient-green2-red">
<div className="row">
<h1 className="col-lg-6 my-auto">
<p>
Our pets are Sourcegraph Teammates, too <br />
#pets-of-sourcegraph
</p>
</h1>
<div className="col-lg-6 img-container">
<img src="../careers/culture5.png" />
</div>
</div>
</Carousel.Item>
{/*
<Carousel.Item className="bg-gradient-red-blue2">
<div className="row">
<h1 className="col-lg-6 my-auto">
<p>
We have fun inside and outside of work <br />
This pic was taken at a team meetup in Berlin
</p>
</h1>
<div className="col-lg-6 img-container">
<img src="../careers/culture6.jpg" className="landscape" />
</div>
</div>
</Carousel.Item>
*/}
<Carousel.Item className="bg-gradient-red-blue2">
<div className="row">
<h1 className="col-lg-6 my-auto">
<p>Creating the next generation of Sourcegraph coders, one baby at a time</p>
</h1>
<div className="col-lg-6 img-container">
<img src="../careers/culture7.png" />
</div>
</div>
</Carousel.Item>
</Carousel>
<div>
<img src="../careers/Culture_8.png" className="culture-section mx-auto" />
<div className="culture-section-mobile mx-auto">
<img src="../careers/01-Zoom.png" className="m-2" />
<img src="../careers/02-Zoom.png" className="m-2" />
<img src="../careers/03-Zoom.png" className="m-2" />
<img src="../careers/04-Zoom.png" className="m-2" />
<img src="../careers/05-Zoom.png" className="m-2" />
<img src="../careers/06-Zoom.png" className="m-2" />
<img src="../careers/07-Zoom.png" className="m-2" />
<img src="../careers/08-Zoom.png" className="m-2" />
</div>
</div>
<Carousel
className="values-carousel"
prevIcon={
<span aria-hidden="true">
<img src="../ArrowLeft.svg" />
</span>
}
nextIcon={
<span aria-hidden="true">
<img src="../ArrowRight.svg" />
</span>
}
>
<Carousel.Item>
<div className="row">
<div>
<p className="subTitle">We value:</p>
<h1>High quality work</h1>
<p className="paragraph">
You are responsible for finding out what high-quality work looks like and producing
that high-quality work iteratively.
</p>
<img src="../careers/1highquality.svg" />
</div>
</div>
</Carousel.Item>
<Carousel.Item>
<div className="row">
<div>
<p className="subTitle">We value:</p>
<h1>Being customer-first</h1>
<p className="paragraph">
You earn and keep the trust of our customers by putting their interests first.
</p>
<img src="../careers/2customerdriven.svg" />
</div>
</div>
</Carousel.Item>
<Carousel.Item>
<div className="row">
<div>
<p className="subTitle">We value:</p>
<h1>Working as a team</h1>
<p className="paragraph">
You work collaboratively with your peers, cross-functional teammates, and leadership
to create shared success, trust, and belonging.
</p>
<img src="../careers/3team.svg" />
</div>
</div>
</Carousel.Item>
<Carousel.Item>
<div className="row">
<div>
<p className="subTitle">We value:</p>
<h1>High agency</h1>
<p className="paragraph">
You have the power and the responsibility to improve Sourcegraph as a company and as
a product. You deliver regardless of the circumstances.
</p>
<img src="../careers/4highagency.svg" />
</div>
</div>
</Carousel.Item>
<Carousel.Item>
<div className="row">
<div>
<p className="subTitle">We value:</p>
<h1>Being welcoming & inclusive</h1>
<p className="paragraph">
You make people from all groups and backgrounds feel comfortable belonging to our
team and community.
</p>
<img src="../careers/5welcoming.svg" />
</div>
</div>
</Carousel.Item>
<Carousel.Item>
<div className="row">
<div>
<p className="subTitle">We value:</p>
<h1>Being open & transparent</h1>
<p className="paragraph">You proactively communicate in an open and transparent way.</p>
<img src="../careers/6open.svg" />
</div>
</div>
</Carousel.Item>
<Carousel.Item>
<div className="row">
<div>
<p className="subTitle">We value:</p>
<h1>Continuous growth</h1>
<p className="paragraph">
You strive to continuously grow and learn by genuinely soliciting feedback early and
often, and humbly reflecting on your past mistakes.
</p>
<img src="../careers/7growth.svg" />
</div>
</div>
</Carousel.Item>
</Carousel>
<div className="bg-white contact-us">
<ContentSection>
<div className="row">
<div className="col-lg-12">
<h2 className="display-2">What you seek is seeking you</h2>
<p>
We're looking forward to reminding you that "you're on mute"{' '}
<img src="../SmileyWink.svg" />
</p>
</div>
</div>
<a
className="btn btn-primary my-2"
href="https://boards.greenhouse.io/sourcegraph91"
title="Explore our jobs"
target="_blank"
>
Explore our jobs
<ArrowRightIcon className="ml-3" />
</a>
</ContentSection>
</div>
</div>
</Layout>
)
}
export default CareersPage | the_stack |
import { Component, OnInit, OnDestroy, HostListener } from '@angular/core';
import { Store } from '@ngrx/store';
import { ActivatedRoute, Router } from '@angular/router';
import { global, authPayload, StorageService } from '../../services/common';
import { AppStore } from '../../app.store';
import { mainAction } from './actions';
import { contactAction } from '../contact/actions';
import { chatAction } from '../chat/actions';
import { md5 } from '../../services/tools';
import { Util } from '../../services/util';
@Component({
selector: 'app-main',
styleUrls: ['./main.component.scss'],
templateUrl: './main.component.html'
})
export class MainComponent implements OnInit, OnDestroy {
private mainStream$;
private global = global;
private listTab = 0;
private selfInfo: any = {
show: false,
info: {
avatarUrl: ''
},
loading: false
};
// 用来标识更新信息成功
private updateSelfInfoFlag = false;
private createGroup = {
show: false,
display: false,
list: []
};
private createGroupNext = {
show: false,
display: false,
info: {}
};
private islogoutShow = false;
private isModifyPasswordShow = false;
private searchUserResult = {
isSearch: false,
result: {
singleArr: [],
groupArr: []
}
};
private tipModal = {
show: false,
info: {
title: '',
tip: ''
}
};
private createSingleChat = {
show: false,
info: ''
};
private blackMenu = {
show: false,
menu: []
};
private chatMenu = {
show: false,
info: [
{
key: 0,
name: '发起单聊'
},
{
key: 1,
name: '发起群聊'
},
{
key: 2,
name: '添加好友'
},
{
key: 3,
name: '加入公开群'
}
]
};
private settingMenu = {
show: false,
info: [
{
key: 0,
name: '修改密码'
},
{
key: 1,
name: '黑名单列表'
},
{
key: 2,
name: '退出登录'
}
]
};
private conversationHover = {
tip: '会话',
position: {
left: 56,
top: 4
},
show: false
};
private contactHover = {
tip: '通讯录',
position: {
left: 56,
top: 4
},
show: false
};
private roomHover = {
tip: '聊天室',
position: {
left: 56,
top: 4
},
show: false
};
private createHover = {
tip: '创建',
position: {
left: 56,
top: 4
},
show: false
};
private moreHover = {
tip: '更多',
position: {
left: 56,
top: 4
},
show: false
};
private logoutKick = {
show: false,
info: {
title: '',
tip: ''
}
};
private badge = {
conversation: 0,
contact: 0
};
private createSingleOption = {
title: '发起单聊',
placeholder: '输入用户名查找'
};
private enterPublicGroup = {
show: false,
info: {}
};
private groupInfo = {
show: false,
info: {}
};
private groupVerifyModal = {
show: false
};
private groupAvatarInfo = {
show: false,
info: {},
src: '',
filename: ''
};
constructor(
private store$: Store<AppStore>,
private storageService: StorageService,
private router: Router
) {
// pass
}
public ngOnInit() {
// 初始化state,避免频繁切换用户时,store的数据依然还保留上一用户的状态
this.store$.dispatch({
type: mainAction.init,
payload: null
});
this.subscribeStore();
this.store$.dispatch({
type: mainAction.getSelfInfo,
payload: null
});
this.store$.dispatch({
type: mainAction.blackMenu,
payload: {
show: false
}
});
}
public ngOnDestroy() {
this.mainStream$.unsubscribe();
}
@HostListener('window:click') private onClickWindow() {
this.settingMenu.show = false;
this.chatMenu.show = false;
}
// 关闭窗口时存cookie,五分钟之内进入页面还可以免登陆
@HostListener('window:beforeunload') private onBeforeunloadWindow() {
const time = 5 * 60 * 1000;
this.storageService.set(md5('afterFiveMinutes-username'), global.user, true, time);
this.storageService.set(md5('afterFiveMinutes-password'), global.password, true, time);
}
private subscribeStore() {
this.mainStream$ = this.store$.select((state) => {
const mainState = state['mainReducer'];
const contactState = state['contactReducer'];
this.stateChanged(mainState, contactState);
return state;
}).subscribe((state) => {
// pass
});
}
private stateChanged(mainState, contactState) {
switch (mainState.actionType) {
case mainAction.init:
this.init();
break;
case contactAction.selectContactItem:
this.listTab = mainState.listTab;
break;
case mainAction.showSelfInfo:
case mainAction.updateSelfInfo:
this.selfInfo = mainState.selfInfo;
this.store$.dispatch({
type: mainAction.updateSelfInfoFlag
});
break;
case mainAction.updateSelfInfoFlag:
this.updateSelfInfoFlag = !this.updateSelfInfoFlag;
break;
case mainAction.changeListTab:
this.listTab = mainState.listTab;
break;
case mainAction.createGroupShow:
this.createGroup = mainState.createGroup;
this.createGroup.list = contactState.friendList;
break;
case mainAction.createGroupSuccess:
this.listTab = mainState.listTab;
this.createGroup = mainState.createGroup;
break;
case mainAction.createGroupNextShow:
this.createGroupNext = mainState.createGroupNext;
if (!this.createGroupNext.show) {
this.groupAvatarInfo = {
show: false,
info: {},
src: '',
filename: ''
};
}
break;
case mainAction.modifyPasswordShow:
this.isModifyPasswordShow = mainState.modifyPasswordShow.show;
if (mainState.modifyPasswordShow.repeatLogin !== '') {
this.repeatLogin(mainState);
}
break;
case chatAction.searchUserSuccess:
this.searchUserResult = mainState.searchUserResult;
break;
case mainAction.selectSearchUser:
this.listTab = mainState.listTab;
this.searchUserResult = mainState.searchUserResult;
break;
case mainAction.selectSearchRoomUser:
this.listTab = mainState.listTab;
this.searchUserResult = mainState.searchUserResult;
break;
case mainAction.hideModalTip:
case mainAction.showModalTip:
case mainAction.deleteMemberSuccess:
case mainAction.exitGroupSuccess:
this.tipModal = mainState.tipModal;
break;
case mainAction.createSingleChatShow:
this.createSingleChat = mainState.createSingleChat;
break;
case mainAction.createSingleChatSuccess:
this.createSingleChat = mainState.createSingleChat;
this.listTab = mainState.listTab;
break;
case mainAction.emptySingleChatTip:
this.createSingleChat.info = mainState.createSingleChat.info;
break;
case mainAction.blackMenuSuccess:
this.blackMenu = mainState.blackMenu;
break;
case mainAction.hideBlackMenu:
this.blackMenu = mainState.blackMenu;
break;
case mainAction.delSingleBlack:
this.blackMenu = mainState.blackMenu;
break;
case mainAction.delSingleBlackSuccess:
this.blackMenu = mainState.blackMenu;
break;
case mainAction.logoutKickShow:
this.logoutKick = mainState.logoutKick;
break;
case contactAction.dispatchContactUnreadNum:
this.badge.contact = mainState.contactUnreadNum;
break;
case chatAction.dispatchConversationUnreadNum:
this.badge.conversation = mainState.conversationUnreadNum;
break;
case chatAction.createOtherChat:
this.listTab = mainState.listTab;
break;
case chatAction.changeHideAll:
this.listTab = mainState.listTab;
break;
case mainAction.enterPublicGroupShow:
this.enterPublicGroup = mainState.enterPublicGroup;
break;
case mainAction.searchPublicGroupSuccess:
this.enterPublicGroup = mainState.enterPublicGroup;
this.groupInfo = mainState.groupInfo;
break;
case mainAction.groupVerifyModal:
this.groupVerifyModal = mainState.groupVerifyModal;
break;
default:
}
}
// 修改密码后重新登录
private repeatLogin(mainState) {
global.password = mainState.modifyPasswordShow.repeatLogin;
const time = 5 * 60 * 1000;
const usernameKey = md5('afterFiveMinutes-username');
const passwordKey = md5('afterFiveMinutes-password');
this.storageService.set(usernameKey, global.user, true, time);
this.storageService.set(passwordKey, global.password, true, time);
this.store$.dispatch({
type: mainAction.login,
payload: {
username: global.user,
password: global.password,
md5: true
}
});
}
// 切换聊天面板和联系人面板
private changeListTab(index) {
if (this.listTab !== index) {
this.store$.dispatch({
type: mainAction.changeListTab,
payload: index
});
}
}
// 获取个人信息
private getSelfInfo(event) {
this.store$.dispatch({
type: mainAction.showSelfInfo,
payload: {
show: true,
loading: false
}
});
}
// 个人信息模态框里传递的事件
private selfInfoEmit(newInfo) {
if (!newInfo) {
this.store$.dispatch({
type: mainAction.showSelfInfo,
payload: {
show: false,
loading: false
}
});
}
if (newInfo && newInfo.info) {
this.store$.dispatch({
type: mainAction.updateSelfInfo,
payload: newInfo
});
}
}
// 显示创建群聊第一步
private createGroupEmit(info) {
if (info && info.add) {
this.store$.dispatch({
type: mainAction.addGroupMember,
payload: info
});
} else if (info && !info.add) {
this.store$.dispatch({
type: mainAction.createGroup,
payload: info
});
} else {
this.store$.dispatch({
type: mainAction.createGroupShow,
payload: {
show: false,
display: false,
info: {}
}
});
this.store$.dispatch({
type: mainAction.createGroupNextShow,
payload: {
show: false,
display: false,
info: {}
}
});
}
}
// 创建群聊第一步点击下一步
private nextCreateGroupEmit(groupInfo) {
this.store$.dispatch({
type: mainAction.createGroupShow,
payload: {
show: true,
display: false,
info: {}
}
});
this.store$.dispatch({
type: mainAction.createGroupNextShow,
payload: {
show: true,
display: true,
info: groupInfo
}
});
}
// 创建群聊第二步点击上一步
private createGroupPrevEmit() {
this.store$.dispatch({
type: mainAction.createGroupShow,
payload: {
show: true,
display: true,
info: {}
}
});
this.store$.dispatch({
type: mainAction.createGroupNextShow,
payload: {
show: true,
display: false
}
});
}
// 关闭创建群聊第二步的模态框
private closeCreateGroupNextEmit() {
this.store$.dispatch({
type: mainAction.createGroupNextShow,
payload: {
show: false,
display: false,
info: {}
}
});
this.store$.dispatch({
type: mainAction.createGroupShow,
payload: {
show: false,
display: false,
info: {}
}
});
}
// 创建群聊点击完成
private completeCreateGroupEmit(groupInfo) {
this.store$.dispatch({
type: mainAction.createGroup,
payload: groupInfo
});
this.store$.dispatch({
type: mainAction.changeListTab,
payload: 0
});
}
// 修改密码
private modifyPasswordEmit(info) {
if (info) {
this.store$.dispatch({
type: mainAction.modifyPassword,
payload: info
});
} else {
this.store$.dispatch({
type: mainAction.modifyPasswordShow,
payload: {
repeatLogin: '',
show: false
}
});
}
}
// 搜索keyup事件
private searchUserEmit(searchInfo) {
this.store$.dispatch({
type: mainAction.searchUser,
payload: searchInfo
});
}
// 点击搜索结果
private selectUserResultEmit(item) {
if (item.gid) {
item.group = true;
item.type = 4;
item.key = item.gid;
}
this.store$.dispatch({
type: mainAction.selectSearchUser,
payload: item
});
}
private selectUserRoomResultEmit(item) {
this.store$.dispatch({
type: mainAction.selectSearchRoomUser,
payload: item
});
}
// 创建单聊/添加好友模态框确定取消按钮
private createSingleChatEmit(info) {
// 点击取消
if (!info) {
this.store$.dispatch({
type: mainAction.createSingleChatShow,
payload: {
show: false,
info: ''
}
});
// 点击确定 输入为空
} else if (info.singleName === '') {
const text = info.type === 'addFriend' ? '请输入要添加好友的用户名' : '请输入要单聊的用户名';
this.store$.dispatch({
type: mainAction.createSingleChatShow,
payload: {
show: true,
info: text
}
});
// 点击确定 如果单聊搜索到自己
} else if (info.singleName === global.user) {
this.store$.dispatch({
type: mainAction.showSelfInfo,
payload: {
show: true,
loading: false
}
});
this.store$.dispatch({
type: mainAction.createSingleChatShow,
payload: {
show: false,
info: ''
}
});
// 点击确定
} else if (info.singleName) {
this.store$.dispatch({
type: mainAction.createSingleChatAction,
payload: info
});
}
}
// 清空单聊模态框错误提示
private emptySingleChatTipEmit() {
this.store$.dispatch({
type: mainAction.emptySingleChatTip,
payload: {
info: ''
}
});
}
// 点击黑名单模态框确定按钮
private blackMenuConfirmEmit() {
this.store$.dispatch({
type: mainAction.hideBlackMenu,
payload: {
menu: [],
show: false
}
});
}
// 加入黑名单列表
private delSingleBlackEmit(user) {
this.store$.dispatch({
type: mainAction.delSingleBlack,
payload: user
});
}
private modalTipEmit(info) {
// 提示模态框点击确定按钮
if (info) {
switch (info.actionType) {
case mainAction.logoutShowConfirmModal:
this.store$.dispatch({
type: mainAction.logoutAction,
payload: null
});
break;
case mainAction.addBlackListConfirmModal:
this.store$.dispatch({
type: mainAction.addBlackListAction,
payload: info.active
});
break;
case mainAction.exitGroupConfirmModal:
this.store$.dispatch({
type: mainAction.exitGroupAction,
payload: info.groupInfo.gid
});
break;
case mainAction.deleteMemberConfirmModal:
this.store$.dispatch({
type: mainAction.deleteMemberAction,
payload: {
deleteItem: info.deleteItem,
group: info.group
}
});
break;
case mainAction.addSingleNoDisturbConfirmModal:
this.store$.dispatch({
type: mainAction.addSingleNoDisturbAction,
payload: info.active
});
break;
case mainAction.deleteFriendConfirmModal:
this.store$.dispatch({
type: mainAction.deleteFriend,
payload: info.active
});
break;
default:
this.store$.dispatch({
type: mainAction.hideModalTip,
payload: {
show: false,
info: {}
}
});
}
// 模态框点击取消按钮
} else {
this.store$.dispatch({
type: mainAction.hideModalTip,
payload: {
show: false,
info: {}
}
});
}
}
// 点击左下角 创建按钮
private chatMenuShow(event) {
event.stopPropagation();
this.settingMenu.show = false;
this.chatMenu.show = !this.chatMenu.show;
}
private selectChatMenuItemEmit(item) {
let type = '';
switch (item.key) {
case 0:
this.createSingleOption = {
title: '发起单聊',
placeholder: '输入用户名查找'
};
this.store$.dispatch({
type: mainAction.createSingleChatShow,
payload: {
show: true,
info: ''
}
});
break;
case 1:
this.store$.dispatch({
type: mainAction.createGroupShow,
payload: {
show: true,
display: true,
info: {}
}
});
break;
case 2:
this.createSingleOption = {
title: '添加好友',
placeholder: '输入用户名'
};
this.store$.dispatch({
type: mainAction.createSingleChatShow,
payload: {
show: true,
info: ''
}
});
break;
case 3:
this.store$.dispatch({
type: mainAction.enterPublicGroupShow,
payload: {
show: true,
info: ''
}
});
break;
default:
}
this.chatMenu.show = false;
}
// 点击左下角设置按钮
private settingMenuShow(event) {
event.stopPropagation();
this.chatMenu.show = false;
this.settingMenu.show = !this.settingMenu.show;
}
private selectSettingItemEmit(item) {
switch (item.key) {
case 0:
this.store$.dispatch({
type: mainAction.modifyPasswordShow,
payload: {
repeatLogin: '',
show: true
}
});
break;
case 1:
this.store$.dispatch({
type: mainAction.blackMenu,
payload: {
show: true
}
});
break;
case 2:
// 展示全局的模态框
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
title: '退出', // 模态框标题
tip: '确定要退出web jchat吗?', // 模态框内容
actionType: mainAction.logoutShowConfirmModal// 哪种操作,点击确定时可以执行对应操作
// success: 1 / 2 // 成功的提示框/失败的提示框,1.5s后会自动消失
}
}
});
break;
default:
}
this.settingMenu.show = false;
}
// 被其他设备登录踢
private logoutKickEmit(info) {
// 重新登录
if (info) {
this.store$.dispatch({
type: mainAction.login,
payload: {
username: global.user,
password: global.password,
md5: true,
reload: true
}
});
// 去登录页面
} else {
this.router.navigate(['/login']);
}
}
// 选择图片出错
private selectImageErrorEmit(tip: string) {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
title: '提示',
tip,
actionType: '[main] must be image',
cancel: true
}
}
});
}
private sendCardEmit(info) {
this.store$.dispatch({
type: mainAction.dispatchSendSelfCard,
payload: info
});
}
private enterGroupComfirmEmit(value) {
this.store$.dispatch({
type: mainAction.searchPublicGroup,
payload: value
});
}
// 显示群组验证模态框
private applyEnterGroupEmit(groupInfo) {
this.store$.dispatch({
type: mainAction.groupVerifyModal,
payload: {
show: true
}
});
}
// 发送群组验证信息
private groupVerifyModalBtnEmit(verifyText) {
this.store$.dispatch({
type: mainAction.sendGroupVerifyMessage,
payload: {
info: this.groupInfo.info,
text: verifyText
}
});
}
// 创建群聊选择头像
private changeCreateGroupAvatarEmit(file) {
this.getImgObj(file.files[0]);
}
// 获取图片对象
private getImgObj(file) {
const isNotImage = '选择的文件必须是图片';
const imageTooSmall = '选择的图片宽或高的尺寸太小,请重新选择图片';
Util.getAvatarImgObj(file,
() => this.selectImageErrorEmit(isNotImage),
() => this.selectImageErrorEmit(imageTooSmall),
(that, pasteFile, img) => {
this.groupAvatarInfo.info = {
src: that.result,
width: img.naturalWidth,
height: img.naturalHeight,
pasteFile
};
this.groupAvatarInfo.src = that.result;
this.groupAvatarInfo.show = true;
this.groupAvatarInfo.filename = file.name;
}
);
}
private groupAvatarEmit(groupInfo) {
this.groupAvatarInfo = groupInfo;
}
// 搜索到已经在群里的群聊,点击发消息进入会话
private changeGroupConversationEmit(group) {
this.store$.dispatch({
type: contactAction.selectContactItem,
payload: group
});
this.store$.dispatch({
type: mainAction.changeListTab,
payload: 0
});
}
// 清空加入公开群的错误提示
private emptyEnterGroupTipEmit() {
this.store$.dispatch({
type: mainAction.enterPublicGroupShow,
payload: {
show: true,
info: {
text: ''
}
}
});
}
private init() {
this.listTab = 0;
this.selfInfo = {
show: false,
info: {
avatarUrl: ''
},
loading: false
};
// 用来标识更新信息成功
this.updateSelfInfoFlag = false;
this.createGroup = {
show: false,
display: false,
list: []
};
this.createGroupNext = {
show: false,
display: false,
info: {}
};
this.islogoutShow = false;
this.isModifyPasswordShow = false;
this.searchUserResult = {
isSearch: false,
result: {
singleArr: [],
groupArr: []
}
};
this.tipModal = {
show: false,
info: {
title: '',
tip: ''
}
};
this.createSingleChat = {
show: false,
info: ''
};
this.blackMenu = {
show: false,
menu: []
};
this.chatMenu = {
show: false,
info: [
{
key: 0,
name: '发起单聊'
},
{
key: 1,
name: '发起群聊'
},
{
key: 2,
name: '添加好友'
},
{
key: 3,
name: '加入公开群'
}
]
};
this.settingMenu = {
show: false,
info: [
{
key: 0,
name: '修改密码'
},
{
key: 1,
name: '黑名单列表'
},
{
key: 2,
name: '退出登录'
}
]
};
this.conversationHover = {
tip: '会话',
position: {
left: 56,
top: 4
},
show: false
};
this.contactHover = {
tip: '通讯录',
position: {
left: 56,
top: 4
},
show: false
};
this.roomHover = {
tip: '聊天室',
position: {
left: 56,
top: 4
},
show: false
};
this.createHover = {
tip: '创建',
position: {
left: 56,
top: 4
},
show: false
};
this.moreHover = {
tip: '更多',
position: {
left: 56,
top: 4
},
show: false
};
this.logoutKick = {
show: false,
info: {
title: '',
tip: ''
}
};
this.badge = {
conversation: 0,
contact: 0
};
this.createSingleOption = {
title: '发起单聊',
placeholder: '输入用户名查找'
};
this.enterPublicGroup = {
show: false,
info: {}
};
this.groupInfo = {
show: false,
info: {}
};
this.groupVerifyModal = {
show: false
};
this.groupAvatarInfo = {
show: false,
info: {},
src: '',
filename: ''
};
}
} | the_stack |
import { Constants } from './Constants';
import { Day, DayInput, DayProperty } from './Day';
import { Unit } from './DayFunctions';
import { Event } from './Event';
import { FrequencyCheck } from './Frequency';
import { Functions as fn } from './Functions';
import { Schedule, ScheduleInput } from './Schedule';
import { ScheduleModifier } from './ScheduleModifier';
import { Time } from './Time';
/**
* The class which takes user input and parses it to specific structures.
*/
export class Parse
{
/**
* Parses a value and converts it to a [[FrequencyCheck]].
*
* @param input The input to parse into a function.
* @param property The [[Day]] property the frequency is for.
* @returns A function which determines whether a value matches a frequency.
* @see [[Schedule]]
*/
public static frequency(input: any, property: DayProperty): FrequencyCheck
{
let check: FrequencyCheck = (value: number) => {
return true;
};
check.given = false;
if (fn.isFrequencyValueEvery(input))
{
const every: number = input.every;
const offset: number = (input.offset || 0) % every;
check = (value: number) => {
return value % every === offset;
};
check.given = true;
}
if (fn.isFrequencyValueOneOf(input))
{
const map: { [value: number]: true | undefined } = {};
for (const i of input) {
map[ i ] = true;
}
check = (value: number) => {
return !!map[ value ];
};
check.given = true;
}
if (fn.isFrequencyValueEquals(input))
{
check = (value: number) => {
return value === input;
};
check.given = true;
}
check.input = fn.coalesce( input, null );
check.property = property;
return check;
}
/**
* Parses [[DayInput]] into a [[Day]] instance.
*
* ```typescript
* Parse.day( 65342300 ); // UTC timestamp
* Parse.day( '01/02/2014' ); // strings in many formats
* Parse.day( day ); // return a passed instance
* Parse.day( [2018, 0, 2] ); // array: 01/02/2018
* Parse.day( {year: 2018, month: 2} ); // object: 03/01/2018
* Parse.day( true ); // today
* ```
*
* @param input The input to parse.
* @returns The Day parsed or `null` if the value is not valid.
*/
public static day(input: DayInput): Day
{
if (fn.isNumber(input))
{
return Day.unix( input );
}
else if (fn.isString(input))
{
return Day.fromString( input );
}
else if (input instanceof Day)
{
return input;
}
else if (fn.isArray<number>( input ))
{
return Day.fromArray( input );
}
else if (fn.isObject<object>( input ))
{
return Day.fromObject( input );
}
else if (input === true)
{
return Day.today();
}
return null;
}
/**
* Parses a value and tries to convert it to a Time instance.
*
* ```typescript
* Parse.time( time ); // return a passed instance
* Parse.time( 9 ); // 09:00:00.000
* Parse.time( 3009 ); // 09:30:00.000
* Parse.time( 593009 ); // 09:30:59.000
* Parsetime( '09' ); // 09:00:00.000
* Parse.time( '9:30' ); // 09:30:00.000
* Parse.time( '9:30:59' ); // 09:30:59.000
* Parse.time( {hour: 2} ); // 02:00:00.000
* ```
*
* @param input The input to parse.
* @returns The instance parsed or `null` if it was invalid.
* @see [[Time.fromIdentifier]]
* @see [[Time.fromString]]
*/
public static time(input: any): Time
{
if (input instanceof Time)
{
return input;
}
if (fn.isNumber(input))
{
return Time.fromIdentifier( input );
}
if (fn.isString(input))
{
return Time.fromString( input );
}
if (fn.isObject<any>(input) && fn.isNumber(input.hour))
{
return new Time(input.hour, input.minute, input.second, input.millisecond);
}
return null;
}
/**
* Parses a value and tries to convert it to an array of Time instances.
* If any of the given values are not a valid time value then the resulting
* array will not contain a time instance.
*
* @param input The input to parse.
* @returns A non-null array of time instances.
* @see [[Parse.time]]
*/
public static times(input: any): Time[]
{
const times: Time[] = [];
if (fn.isArray(input))
{
for (const timeInput of input)
{
const time = this.time( timeInput );
if (time)
{
times.push( time );
}
}
// Sort times from earliest to latest.
times.sort((a, b) =>
{
return a.toMilliseconds() - b.toMilliseconds();
});
}
return times;
}
/**
* Parses an array of excluded days into a map of excluded days where the
* array value and returned object key are [[Day.dayIdentifier]].
*
* ```typescript
* Parse.modifier( [ 20180101, 20140506 ] ); // {'20180101': true, '20140506': true}
* Parse.modifier( [ 20180101, Day.build(2014,4,6) ] ); // {'20180101': true, '20140506': true}
* ```
*
* @param input The input to parse.
* @param value The default value if the input given is an array of identifiers.
* @param parseMeta A function to use to parse a modifier.
* @param out The modifier to set the identifiers and values of and return.
* @returns The object with identifier keys and `true` values.
* @see [[Day.dayIdentifier]]
*/
public static modifier<T>(input: any, value: T,
parseMeta: (input: any) => T = (x => x),
out: ScheduleModifier<T> = new ScheduleModifier<T>()): ScheduleModifier<T>
{
const map = {};
if (fn.isArray(input))
{
for (const identifier of input)
{
if (identifier instanceof Day)
{
map[ identifier.dayIdentifier ] = value;
}
else if (fn.isNumber(identifier))
{
map[ identifier ] = value;
}
else if (fn.isString(identifier))
{
map[ identifier ] = value;
}
}
}
if (fn.isObject(input))
{
for (const identifier in input)
{
map[ identifier ] = parseMeta( input[ identifier ] );
}
}
out.map = map;
return out;
}
/**
*
*/
public static unit (input: string, all: boolean = false): Unit
{
if (typeof input !== 'string')
{
return Constants.DURATION_DEFAULT_UNIT(all);
}
switch (input.toLowerCase()) {
case 'ms':
case 'milli':
case 'millis':
case 'millisecond':
case 'milliseconds':
return 'millis';
case 's':
case 'sec':
case 'secs':
case 'second':
case 'seconds':
return 'second';
case 'm':
case 'min':
case 'mins':
case 'minute':
case 'minutes':
return 'minute';
case 'h':
case 'hr':
case 'hour':
case 'hours':
return 'hour';
case 'd':
case 'day':
case 'days':
return 'day';
case 'w':
case 'wk':
case 'week':
case 'weeks':
return 'week';
case 'mon':
case 'month':
case 'months':
return 'month';
case 'q':
case 'quarter':
case 'quarters':
return 'quarter';
case 'y':
case 'yr':
case 'yrs':
case 'year':
case 'years':
return 'year';
}
return Constants.DURATION_DEFAULT_UNIT(all);
}
/**
* Parses an object which specifies a schedule where events may or may not
* repeat and they may be all day events or at specific times.
*
* @param input The input to parse into a schedule.
* @param parseMeta A function to use when parsing meta input into the desired type.
* @param out The schedule to set the values of and return.
* @returns An instance of the parsed [[Schedule]].
*/
public static schedule<M>(input: ScheduleInput<M> | Schedule<M>,
parseMeta: (input: any) => M = (x => x),
out: Schedule<M> = new Schedule<M>()): Schedule<M>
{
if (input instanceof Schedule)
{
return input;
}
const on: Day = this.day( input.on );
const times: Time[] = this.times( input.times );
const fullDay: boolean = times.length === 0;
if (on)
{
input.start = on.startOf('day');
input.end = on.endOf('day');
input.year = [on.year];
input.month = [on.month];
input.dayOfMonth = [on.dayOfMonth];
}
out.times = times;
out.duration = fn.coalesce( input.duration, Constants.DURATION_DEFAULT );
out.durationUnit = this.unit( input.durationUnit, fullDay );
out.start = this.day( input.start );
out.end = this.day( input.end );
out.maxOccurrences = fn.coalesce( input.maxOccurrences, 0 );
out.exclude = this.modifier( input.exclude, true, undefined, out.exclude );
out.include = this.modifier( input.include, true, undefined, out.include );
out.cancel = this.modifier( input.cancel, true, undefined, out.cancel );
out.meta = this.modifier( input.meta, null, parseMeta, out.meta );
out.year = this.frequency( input.year, 'year' );
out.month = this.frequency( input.month, 'month' );
out.day = this.frequency( input.day, 'day' );
out.quarter = this.frequency( input.quarter, 'quarter' );
out.week = this.frequency( input.week, 'week' );
out.weekOfYear = this.frequency( input.weekOfYear, 'weekOfYear' );
out.weekspanOfYear = this.frequency( input.weekspanOfYear, 'weekspanOfYear' );
out.fullWeekOfYear = this.frequency( input.fullWeekOfYear, 'fullWeekOfYear' );
out.lastWeekspanOfYear = this.frequency( input.lastWeekspanOfYear, 'lastWeekspanOfYear' );
out.lastFullWeekOfYear = this.frequency( input.lastFullWeekOfYear, 'lastFullWeekOfYear' );
out.weekOfMonth = this.frequency( input.weekOfMonth, 'weekOfMonth' );
out.weekspanOfMonth = this.frequency( input.weekspanOfMonth, 'weekspanOfMonth' );
out.fullWeekOfMonth = this.frequency( input.fullWeekOfMonth, 'fullWeekOfMonth' );
out.lastWeekspanOfMonth = this.frequency( input.lastWeekspanOfMonth, 'lastWeekspanOfMonth' );
out.lastFullWeekOfMonth = this.frequency( input.lastFullWeekOfMonth, 'lastFullWeekOfMonth' );
out.dayOfWeek = this.frequency( input.dayOfWeek, 'dayOfWeek' );
out.dayOfMonth = this.frequency( input.dayOfMonth, 'dayOfMonth' );
out.lastDayOfMonth = this.frequency( input.lastDayOfMonth, 'lastDayOfMonth' );
out.dayOfYear = this.frequency( input.dayOfYear, 'dayOfYear' );
out.updateDurationInDays();
out.updateChecks();
out.updateEnd();
return out;
}
/**
* Parses an array of [[FrequencyCheck]] functions and returns an array of
* functions for only the checks that were specified by the user.
*
* @param checks The array of check functions to filter through.
* @returns The array of user specified checks.
*/
public static givenFrequency(checks: FrequencyCheck[]): FrequencyCheck[]
{
const out: FrequencyCheck[] = [];
for (const check of checks)
{
if (check.given)
{
out.push( check );
}
}
return out;
}
/**
* Parses [[EventInput]] and returns an [[Event]].
*
* @param input The input to parse.
* @param parseData A function to use when parsing data input into the desired type.
* @param parseMeta A function to use when parsing meta input into the desired type.
* @returns The parsed value.
*/
public static event<T, M>(input: any,
parseData: (input: any) => T = (x => x),
parseMeta: (input: any) => M = (x => x)): Event<T, M>
{
if (input instanceof Event)
{
return input;
}
if (!input.schedule)
{
return null;
}
const schedule: Schedule<M> = this.schedule<M>( input.schedule, parseMeta );
return new Event( schedule, parseData( input.data ), input.id, input.visible );
}
/**
* Parses a schedule from a CRON pattern. TODO
*/
public static cron<M>(pattern: string, out: Schedule<M> = new Schedule<M>()): Schedule<M>
{
return out;
}
} | the_stack |
import * as Random from './random';
import * as Shrink from './shrink';
import * as RoseTree from './rosetree';
import * as Iter from './iterable';
import * as Util from './utilities';
import * as is from './is';
import { sample } from './sample';
import { Shrinker } from './shrink';
import { Generator } from './random';
import { Rose } from './rosetree';
import { Awaitable } from './types';
import invariant = require('invariant');
export class Fuzzer<A> {
constructor(public generator: Generator<Rose<A>>) {}
map<B>(fn: (a: A) => Awaitable<B>): Fuzzer<B> {
return map(fn, this);
}
flatMap<B>(fn: (a: A) => Awaitable<Fuzzer<B>>): Fuzzer<B> {
return flatMap(fn, this);
}
filter(fn: (a: A) => Awaitable<boolean>): Fuzzer<A> {
return filter(fn, this);
}
maybe(): Fuzzer<A | void> {
return maybe(this);
}
noShrink(): Fuzzer<A> {
return noShrink(this);
}
}
export const custom = <A>(generator: Generator<A>, shrinker: Shrinker<A>): Fuzzer<A> => {
const shrinkTree = (a: A): Rose<A> => RoseTree.rose(a, Iter.lazy(() => Iter.map(shrinkTree, shrinker(a))));
return new Fuzzer(Random.map(shrinkTree, generator));
};
export const frequency = <A, B>(pairs: [number, Fuzzer<A>][]): Fuzzer<A> => {
const genPairs = pairs.map((x): [number, Generator<Rose<A>>] => [x[0], x[1].generator]);
const generator = Random.frequency(genPairs);
return new Fuzzer(generator);
};
const numberHelper = (
createGenerator: (low: number, high: number) => Generator<number>,
createShrinker: (min: number) => Shrinker<number>,
) => (props: Partial<{ minSize: number; maxSize: number }> = {}): Fuzzer<number> => {
const { minSize = -1e9, maxSize = 1e9 } = props;
invariant(is.number(minSize), 'minSize (%s) is not a number', minSize);
invariant(is.number(maxSize), 'minSize (%s) is not a number', maxSize);
invariant(
maxSize >= minSize,
'Number generator must have minSize (%s) less than or equal to maxSize (%s)',
minSize,
maxSize,
);
const gens: [number, Generator<number>][] = [[1, Random.constant(minSize)], [1, Random.constant(maxSize)]];
if (maxSize > 50) {
if (minSize >= 0) {
gens.push([3, createGenerator(minSize, 50)]);
} else {
gens.push([3, createGenerator(0, 50)]);
}
}
if (minSize < -50) {
if (maxSize >= 0) {
gens.push([3, createGenerator(-50, 0)]);
} else {
gens.push([3, createGenerator(-50, maxSize)]);
}
}
if (minSize < 0 && maxSize > 0) {
gens.push([1, Random.constant(0)]);
gens.push([7, createGenerator(minSize, 0)]);
gens.push([7, createGenerator(0, maxSize)]);
} else {
gens.push([15, createGenerator(minSize, maxSize)]);
}
const pivot = minSize >= 0 ? minSize : Math.min(0, maxSize);
const shrinker = createShrinker(pivot);
return custom<number>(Random.frequency(gens), shrinker);
};
const stringHelper = (
createGenerator: (minLen: number, maxLen: number) => Generator<string>,
shrinker: Shrinker<string>,
) => (props: Partial<{ maxSize: number }> = {}): Fuzzer<string> => {
const { maxSize = 1e2 } = props;
invariant(is.number(maxSize), 'maxSize (%s) is not a number', maxSize);
invariant(maxSize >= 0, 'maxSize (%s) greater than or equal to zero', maxSize);
const gens: [number, Generator<string>][] = [
[1, createGenerator(maxSize, maxSize)],
[1, Random.constant('')],
[1, Random.whitespace],
];
if (maxSize < 10) {
gens.push([8, createGenerator(1, maxSize)]);
} else if (maxSize < 50) {
gens.push([4, createGenerator(1, 10)]);
gens.push([4, createGenerator(11, maxSize)]);
} else {
gens.push([4, createGenerator(1, 10)]);
gens.push([3, createGenerator(11, 50)]);
gens.push([1, createGenerator(50, maxSize)]);
}
return custom(Random.frequency(gens), shrinker);
};
const arrayHelper = <A>(trees: Rose<A>[]): Rose<A[]> => {
const len = trees.length;
const root = Promise.all(trees.map(RoseTree.root));
let halved: AsyncIterable<Rose<A[]>>;
if (len >= 8) {
halved = Iter.lazy(() => {
const firstHalf = arrayHelper<A>(Util.take(Math.round(len / 2), trees));
const secondHalf = arrayHelper<A>(Util.drop(Math.round(len / 2), trees));
return Iter.from([firstHalf, secondHalf]);
});
} else {
halved = Iter.empty();
}
const shrinkOne = (prefix: Rose<A>[], suffix: Rose<A>[]): AsyncIterable<Rose<A[]>> => {
if (suffix.length === 0) {
return Iter.empty();
}
const [head, ...tail] = suffix;
const children = RoseTree.children(head);
return Iter.map(kid => arrayHelper([...prefix, kid, ...tail]), children);
};
const remove = <B>(index: number, list: B[]) => [...Util.take(index, list), ...Util.drop(index + 1, list)];
const shrunkValues = Iter.flatMap<number, Rose<A[]>>(
i => Iter.lazy(() => shrinkOne(Util.take(i, trees), Util.drop(i, trees))),
Iter.range(0, len + 1),
);
const shortened = Iter.map(xs => arrayHelper(xs), Iter.map(i => remove(i, trees), Iter.range(0, len - 1)));
/**
* make sure that the children include an empty iterator so that we can try it on fail as the
* minimum base case.
*/
const empty = Iter.of(RoseTree.singleton([]));
return RoseTree.rose(root, Iter.concat4(empty, halved, shortened, shrunkValues));
};
export const boolean = () => custom<boolean>(Random.boolean, Shrink.boolean);
export const constant = <A>(value: A) => custom<A>(Random.constant(value as A), () => Iter.of(value));
export const string = stringHelper(Random.string, Shrink.string);
export const asciiString = stringHelper(Random.asciiString, Shrink.string);
export const integer = numberHelper(Random.integer, Shrink.atLeastInteger);
export const float = numberHelper(Random.float, Shrink.atLeastFloat);
export const number = (props: Partial<{ minSize: number; maxSize: number }> = {}) =>
frequency([[3, integer(props)], [1, float(props)]]);
export const posInteger = (props: Partial<{ maxSize: number }> = {}) => integer({ ...props, minSize: 0 });
export const negInteger = (props: Partial<{ minSize: number }> = {}) => integer({ ...props, maxSize: -0 });
export const posFloat = (props: Partial<{ maxSize: number }> = {}) => float({ ...props, minSize: 0 });
export const negFloat = (props: Partial<{ minSize: number }> = {}) => float({ ...props, maxSize: -0 });
export const posNumber = (props: Partial<{ maxSize: number }> = {}) => number({ ...props, minSize: 0 });
export const negNumber = (props: Partial<{ minSize: number }> = {}) => number({ ...props, maxSize: -0 });
export const array = <A>(fuzzer: Fuzzer<A>, props: Partial<{ maxSize: number }> = {}): Fuzzer<A[]> => {
const { maxSize = 1e2 } = props;
invariant(is.number(maxSize), 'maxSize (%s) is not a number', maxSize);
invariant(maxSize >= 0, 'maxSize (%s) greater than or equal to zero', maxSize);
const gens: [number, Generator<number>][] = [[1, Random.constant(0)], [1, Random.constant(1)]];
if (maxSize > 1 && maxSize < 10) {
gens.push([6, Random.integer(2, maxSize)]);
} else if (maxSize >= 10 && maxSize < 100) {
gens.push([6, Random.integer(2, 10)]);
gens.push([4, Random.integer(10, maxSize)]);
} else if (maxSize >= 100) {
gens.push([6, Random.integer(2, 10)]);
gens.push([4, Random.integer(10, 100)]);
gens.push([2, Random.integer(100, maxSize)]);
}
const generator = Random.map<Rose<A>[], Rose<A[]>>(
arrayHelper,
Random.flatMap(len => Random.array(len, fuzzer.generator), Random.frequency(gens)),
);
return new Fuzzer(generator);
};
export const object = <A>(obj: { [K in keyof A]: Fuzzer<A[K]> }): Fuzzer<A> => {
if (Object.keys(obj).length === 0) {
return constant({}) as Fuzzer<A>;
}
const keys = Object.keys(obj) as (keyof A)[];
const fuzzers = keys.map(key => map(ak => ({ [key]: ak } as { [K in typeof key]: A[K] }), obj[key]));
return fuzzers.reduce((prev, next) => map2((a, b) => Object.assign({}, a, b), prev, next));
};
export const zip = <A, B>(a: Fuzzer<A>, b: Fuzzer<B>): Fuzzer<[A, B]> => {
const generator = Random.map2<Rose<A>, Rose<B>, Rose<[A, B]>>(RoseTree.zip, a.generator, b.generator);
return new Fuzzer(generator);
};
export const zip3 = <A, B, C>(a: Fuzzer<A>, b: Fuzzer<B>, c: Fuzzer<C>): Fuzzer<[A, B, C]> =>
map2((arr, val) => [...arr, val] as [A, B, C], zip(a, b), c);
export const zip4 = <A, B, C, D>(a: Fuzzer<A>, b: Fuzzer<B>, c: Fuzzer<C>, d: Fuzzer<D>): Fuzzer<[A, B, C, D]> =>
map2((arr, val) => [...arr, val] as [A, B, C, D], zip3(a, b, c), d);
export const zip5 = <A, B, C, D, E>(
a: Fuzzer<A>,
b: Fuzzer<B>,
c: Fuzzer<C>,
d: Fuzzer<D>,
e: Fuzzer<E>,
): Fuzzer<[A, B, C, D, E]> => map2((arr, val) => [...arr, val] as [A, B, C, D, E], zip4(a, b, c, d), e);
export const map = <A, B>(fn: (a: A) => Awaitable<B>, a: Fuzzer<A>): Fuzzer<B> => {
const generator = Random.map(a_ => RoseTree.map(fn, a_), a.generator);
return new Fuzzer(generator);
};
export const map2 = <A, B, C>(fn: (a: A, b: B) => Awaitable<C>, a: Fuzzer<A>, b: Fuzzer<B>): Fuzzer<C> => {
const generator = Random.map2((a_, b_) => RoseTree.map2(fn, a_, b_), a.generator, b.generator);
return new Fuzzer(generator);
};
export const filter = <A>(fn: (a: A) => Awaitable<boolean>, a: Fuzzer<A>) => {
const generator = Random.filterMap(a_ => RoseTree.filter(fn, a_), a.generator);
return new Fuzzer(generator);
};
export const maybe = <A>(a: Fuzzer<A>): Fuzzer<A | void> => frequency([[3, a], [1, constant(undefined)]]);
export const noShrink = <A>(a: Fuzzer<A>): Fuzzer<A> => {
const generator = Random.flatMap(tree => {
const root = RoseTree.root(tree);
return Random.constant(RoseTree.singleton(root));
}, a.generator);
return new Fuzzer(generator);
};
export const oneOf = <A>(fuzzers: Fuzzer<A>[]) =>
frequency(fuzzers.map((fuzzer: Fuzzer<A>): [1, Fuzzer<A>] => [1, fuzzer]));
const flatMapRunAll = <A>(a: AsyncIterable<Fuzzer<Rose<A>>>): Generator<AsyncIterable<Rose<Rose<A>>>> => async seed => {
let seed_ = seed;
const value = Iter.map<Fuzzer<Rose<A>>, Rose<Rose<A>>>(async fuzz => {
const { value, nextSeed } = await fuzz.generator(seed_);
seed_ = nextSeed;
return value;
}, a);
return {
value,
nextSeed: seed_,
};
};
const flatMapSequenceRose = async <A>(a: Rose<Fuzzer<A>>): Promise<Fuzzer<Rose<A>>> => {
const root: Fuzzer<A> = await RoseTree.root(a);
const children: AsyncIterable<Fuzzer<Rose<A>>> = Iter.map(a_ => flatMapSequenceRose(a_), RoseTree.children(a));
const generator = Random.map2((a_, b_) => RoseTree.rose(a_, b_), root.generator, flatMapRunAll(children));
return new Fuzzer(generator);
};
export const flatMap = <A, B>(fn: (a: A) => Awaitable<Fuzzer<B>>, a: Fuzzer<A>): Fuzzer<B> => {
const generator = Random.flatMap<Rose<A>, Rose<B>>(async roseA => {
const roseGenA = RoseTree.map(fn, roseA);
const trees = await flatMapSequenceRose<B>(roseGenA);
return Random.map<Rose<Rose<B>>, Rose<B>>(RoseTree.flatten, trees.generator);
}, a.generator);
return new Fuzzer(generator);
}; | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Accounts
* __NOTE__: An instance of this class is automatically created for an
* instance of the DataLakeStoreAccountManagementClient.
*/
export interface Accounts {
/**
* Lists the Data Lake Store accounts within the subscription. The response
* includes a link to the next page of results, if any.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccountListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccountListResult>>;
/**
* Lists the Data Lake Store accounts within the subscription. The response
* includes a link to the next page of results, if any.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccountListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccountListResult} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccountListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccountListResult>;
list(callback: ServiceCallback<models.DataLakeStoreAccountListResult>): void;
list(options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccountListResult>): void;
/**
* Lists the Data Lake Store accounts within a specific resource group. The
* response includes a link to the next page of results, if any.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] A Boolean value of true or false to request
* a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccountListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccountListResult>>;
/**
* Lists the Data Lake Store accounts within a specific resource group. The
* response includes a link to the next page of results, if any.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] A Boolean value of true or false to request
* a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccountListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccountListResult} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccountListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccountListResult>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.DataLakeStoreAccountListResult>): void;
listByResourceGroup(resourceGroupName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccountListResult>): void;
/**
* Creates the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} parameters Parameters supplied to create the Data Lake Store
* account.
*
* @param {string} parameters.location The resource location.
*
* @param {object} [parameters.tags] The resource tags.
*
* @param {object} [parameters.identity] The Key Vault encryption identity, if
* any.
*
* @param {string} [parameters.defaultGroup] The default owner group for all
* new folders and files created in the Data Lake Store account.
*
* @param {object} [parameters.encryptionConfig] The Key Vault encryption
* configuration.
*
* @param {string} parameters.encryptionConfig.type The type of encryption
* configuration being used. Currently the only supported types are
* 'UserManaged' and 'ServiceManaged'. Possible values include: 'UserManaged',
* 'ServiceManaged'
*
* @param {object} [parameters.encryptionConfig.keyVaultMetaInfo] The Key Vault
* information for connecting to user managed encryption keys.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.keyVaultResourceId The resource
* identifier for the user managed Key Vault being used to encrypt.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyName The name of
* the user managed encryption key.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyVersion The
* version of the user managed encryption key.
*
* @param {string} [parameters.encryptionState] The current state of encryption
* for this Data Lake Store account. Possible values include: 'Enabled',
* 'Disabled'
*
* @param {array} [parameters.firewallRules] The list of firewall rules
* associated with this Data Lake Store account.
*
* @param {array} [parameters.virtualNetworkRules] The list of virtual network
* rules associated with this Data Lake Store account.
*
* @param {string} [parameters.firewallState] The current state of the IP
* address firewall for this Data Lake Store account. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {string} [parameters.firewallAllowAzureIps] The current state of
* allowing or disallowing IPs originating within Azure through the firewall.
* If the firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {array} [parameters.trustedIdProviders] The list of trusted identity
* providers associated with this Data Lake Store account.
*
* @param {string} [parameters.trustedIdProviderState] The current state of the
* trusted identity provider feature for this Data Lake Store account. Possible
* values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.newTier] The commitment tier to use for next
* month. Possible values include: 'Consumption', 'Commitment_1TB',
* 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB',
* 'Commitment_5PB'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccount>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createWithHttpOperationResponse(resourceGroupName: string, accountName: string, parameters: models.CreateDataLakeStoreAccountParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccount>>;
/**
* Creates the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} parameters Parameters supplied to create the Data Lake Store
* account.
*
* @param {string} parameters.location The resource location.
*
* @param {object} [parameters.tags] The resource tags.
*
* @param {object} [parameters.identity] The Key Vault encryption identity, if
* any.
*
* @param {string} [parameters.defaultGroup] The default owner group for all
* new folders and files created in the Data Lake Store account.
*
* @param {object} [parameters.encryptionConfig] The Key Vault encryption
* configuration.
*
* @param {string} parameters.encryptionConfig.type The type of encryption
* configuration being used. Currently the only supported types are
* 'UserManaged' and 'ServiceManaged'. Possible values include: 'UserManaged',
* 'ServiceManaged'
*
* @param {object} [parameters.encryptionConfig.keyVaultMetaInfo] The Key Vault
* information for connecting to user managed encryption keys.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.keyVaultResourceId The resource
* identifier for the user managed Key Vault being used to encrypt.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyName The name of
* the user managed encryption key.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyVersion The
* version of the user managed encryption key.
*
* @param {string} [parameters.encryptionState] The current state of encryption
* for this Data Lake Store account. Possible values include: 'Enabled',
* 'Disabled'
*
* @param {array} [parameters.firewallRules] The list of firewall rules
* associated with this Data Lake Store account.
*
* @param {array} [parameters.virtualNetworkRules] The list of virtual network
* rules associated with this Data Lake Store account.
*
* @param {string} [parameters.firewallState] The current state of the IP
* address firewall for this Data Lake Store account. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {string} [parameters.firewallAllowAzureIps] The current state of
* allowing or disallowing IPs originating within Azure through the firewall.
* If the firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {array} [parameters.trustedIdProviders] The list of trusted identity
* providers associated with this Data Lake Store account.
*
* @param {string} [parameters.trustedIdProviderState] The current state of the
* trusted identity provider feature for this Data Lake Store account. Possible
* values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.newTier] The commitment tier to use for next
* month. Possible values include: 'Consumption', 'Commitment_1TB',
* 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB',
* 'Commitment_5PB'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccount} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccount} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccount} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
create(resourceGroupName: string, accountName: string, parameters: models.CreateDataLakeStoreAccountParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccount>;
create(resourceGroupName: string, accountName: string, parameters: models.CreateDataLakeStoreAccountParameters, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
create(resourceGroupName: string, accountName: string, parameters: models.CreateDataLakeStoreAccountParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
/**
* Gets the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccount>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccount>>;
/**
* Gets the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccount} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccount} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccount} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccount>;
get(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
get(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
/**
* Updates the specified Data Lake Store account information.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} parameters Parameters supplied to update the Data Lake Store
* account.
*
* @param {object} [parameters.tags] Resource tags
*
* @param {string} [parameters.defaultGroup] The default owner group for all
* new folders and files created in the Data Lake Store account.
*
* @param {object} [parameters.encryptionConfig] Used for rotation of user
* managed Key Vault keys. Can only be used to rotate a user managed encryption
* Key Vault key.
*
* @param {object} [parameters.encryptionConfig.keyVaultMetaInfo] The updated
* Key Vault key to use in user managed key rotation.
*
* @param {string}
* [parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyVersion] The
* version of the user managed encryption key to update through a key rotation.
*
* @param {array} [parameters.firewallRules] The list of firewall rules
* associated with this Data Lake Store account.
*
* @param {array} [parameters.virtualNetworkRules] The list of virtual network
* rules associated with this Data Lake Store account.
*
* @param {string} [parameters.firewallState] The current state of the IP
* address firewall for this Data Lake Store account. Disabling the firewall
* does not remove existing rules, they will just be ignored until the firewall
* is re-enabled. Possible values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.firewallAllowAzureIps] The current state of
* allowing or disallowing IPs originating within Azure through the firewall.
* If the firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {array} [parameters.trustedIdProviders] The list of trusted identity
* providers associated with this Data Lake Store account.
*
* @param {string} [parameters.trustedIdProviderState] The current state of the
* trusted identity provider feature for this Data Lake Store account.
* Disabling trusted identity provider functionality does not remove the
* providers, they will just be ignored until this feature is re-enabled.
* Possible values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.newTier] The commitment tier to use for next
* month. Possible values include: 'Consumption', 'Commitment_1TB',
* 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB',
* 'Commitment_5PB'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccount>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, parameters: models.UpdateDataLakeStoreAccountParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccount>>;
/**
* Updates the specified Data Lake Store account information.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} parameters Parameters supplied to update the Data Lake Store
* account.
*
* @param {object} [parameters.tags] Resource tags
*
* @param {string} [parameters.defaultGroup] The default owner group for all
* new folders and files created in the Data Lake Store account.
*
* @param {object} [parameters.encryptionConfig] Used for rotation of user
* managed Key Vault keys. Can only be used to rotate a user managed encryption
* Key Vault key.
*
* @param {object} [parameters.encryptionConfig.keyVaultMetaInfo] The updated
* Key Vault key to use in user managed key rotation.
*
* @param {string}
* [parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyVersion] The
* version of the user managed encryption key to update through a key rotation.
*
* @param {array} [parameters.firewallRules] The list of firewall rules
* associated with this Data Lake Store account.
*
* @param {array} [parameters.virtualNetworkRules] The list of virtual network
* rules associated with this Data Lake Store account.
*
* @param {string} [parameters.firewallState] The current state of the IP
* address firewall for this Data Lake Store account. Disabling the firewall
* does not remove existing rules, they will just be ignored until the firewall
* is re-enabled. Possible values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.firewallAllowAzureIps] The current state of
* allowing or disallowing IPs originating within Azure through the firewall.
* If the firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {array} [parameters.trustedIdProviders] The list of trusted identity
* providers associated with this Data Lake Store account.
*
* @param {string} [parameters.trustedIdProviderState] The current state of the
* trusted identity provider feature for this Data Lake Store account.
* Disabling trusted identity provider functionality does not remove the
* providers, they will just be ignored until this feature is re-enabled.
* Possible values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.newTier] The commitment tier to use for next
* month. Possible values include: 'Consumption', 'Commitment_1TB',
* 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB',
* 'Commitment_5PB'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccount} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccount} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccount} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, accountName: string, parameters: models.UpdateDataLakeStoreAccountParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccount>;
update(resourceGroupName: string, accountName: string, parameters: models.UpdateDataLakeStoreAccountParameters, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
update(resourceGroupName: string, accountName: string, parameters: models.UpdateDataLakeStoreAccountParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
/**
* Deletes the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, accountName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Attempts to enable a user managed Key Vault for encryption of the specified
* Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
enableKeyVaultWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Attempts to enable a user managed Key Vault for encryption of the specified
* Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
enableKeyVault(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
enableKeyVault(resourceGroupName: string, accountName: string, callback: ServiceCallback<void>): void;
enableKeyVault(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Checks whether the specified account name is available or taken.
*
* @param {string} location The resource location without whitespace.
*
* @param {object} parameters Parameters supplied to check the Data Lake Store
* account name availability.
*
* @param {string} parameters.name The Data Lake Store name to check
* availability for.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<NameAvailabilityInformation>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
checkNameAvailabilityWithHttpOperationResponse(location: string, parameters: models.CheckNameAvailabilityParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NameAvailabilityInformation>>;
/**
* Checks whether the specified account name is available or taken.
*
* @param {string} location The resource location without whitespace.
*
* @param {object} parameters Parameters supplied to check the Data Lake Store
* account name availability.
*
* @param {string} parameters.name The Data Lake Store name to check
* availability for.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {NameAvailabilityInformation} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {NameAvailabilityInformation} [result] - The deserialized result object if an error did not occur.
* See {@link NameAvailabilityInformation} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
checkNameAvailability(location: string, parameters: models.CheckNameAvailabilityParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NameAvailabilityInformation>;
checkNameAvailability(location: string, parameters: models.CheckNameAvailabilityParameters, callback: ServiceCallback<models.NameAvailabilityInformation>): void;
checkNameAvailability(location: string, parameters: models.CheckNameAvailabilityParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NameAvailabilityInformation>): void;
/**
* Creates the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} parameters Parameters supplied to create the Data Lake Store
* account.
*
* @param {string} parameters.location The resource location.
*
* @param {object} [parameters.tags] The resource tags.
*
* @param {object} [parameters.identity] The Key Vault encryption identity, if
* any.
*
* @param {string} [parameters.defaultGroup] The default owner group for all
* new folders and files created in the Data Lake Store account.
*
* @param {object} [parameters.encryptionConfig] The Key Vault encryption
* configuration.
*
* @param {string} parameters.encryptionConfig.type The type of encryption
* configuration being used. Currently the only supported types are
* 'UserManaged' and 'ServiceManaged'. Possible values include: 'UserManaged',
* 'ServiceManaged'
*
* @param {object} [parameters.encryptionConfig.keyVaultMetaInfo] The Key Vault
* information for connecting to user managed encryption keys.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.keyVaultResourceId The resource
* identifier for the user managed Key Vault being used to encrypt.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyName The name of
* the user managed encryption key.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyVersion The
* version of the user managed encryption key.
*
* @param {string} [parameters.encryptionState] The current state of encryption
* for this Data Lake Store account. Possible values include: 'Enabled',
* 'Disabled'
*
* @param {array} [parameters.firewallRules] The list of firewall rules
* associated with this Data Lake Store account.
*
* @param {array} [parameters.virtualNetworkRules] The list of virtual network
* rules associated with this Data Lake Store account.
*
* @param {string} [parameters.firewallState] The current state of the IP
* address firewall for this Data Lake Store account. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {string} [parameters.firewallAllowAzureIps] The current state of
* allowing or disallowing IPs originating within Azure through the firewall.
* If the firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {array} [parameters.trustedIdProviders] The list of trusted identity
* providers associated with this Data Lake Store account.
*
* @param {string} [parameters.trustedIdProviderState] The current state of the
* trusted identity provider feature for this Data Lake Store account. Possible
* values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.newTier] The commitment tier to use for next
* month. Possible values include: 'Consumption', 'Commitment_1TB',
* 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB',
* 'Commitment_5PB'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccount>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginCreateWithHttpOperationResponse(resourceGroupName: string, accountName: string, parameters: models.CreateDataLakeStoreAccountParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccount>>;
/**
* Creates the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} parameters Parameters supplied to create the Data Lake Store
* account.
*
* @param {string} parameters.location The resource location.
*
* @param {object} [parameters.tags] The resource tags.
*
* @param {object} [parameters.identity] The Key Vault encryption identity, if
* any.
*
* @param {string} [parameters.defaultGroup] The default owner group for all
* new folders and files created in the Data Lake Store account.
*
* @param {object} [parameters.encryptionConfig] The Key Vault encryption
* configuration.
*
* @param {string} parameters.encryptionConfig.type The type of encryption
* configuration being used. Currently the only supported types are
* 'UserManaged' and 'ServiceManaged'. Possible values include: 'UserManaged',
* 'ServiceManaged'
*
* @param {object} [parameters.encryptionConfig.keyVaultMetaInfo] The Key Vault
* information for connecting to user managed encryption keys.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.keyVaultResourceId The resource
* identifier for the user managed Key Vault being used to encrypt.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyName The name of
* the user managed encryption key.
*
* @param {string}
* parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyVersion The
* version of the user managed encryption key.
*
* @param {string} [parameters.encryptionState] The current state of encryption
* for this Data Lake Store account. Possible values include: 'Enabled',
* 'Disabled'
*
* @param {array} [parameters.firewallRules] The list of firewall rules
* associated with this Data Lake Store account.
*
* @param {array} [parameters.virtualNetworkRules] The list of virtual network
* rules associated with this Data Lake Store account.
*
* @param {string} [parameters.firewallState] The current state of the IP
* address firewall for this Data Lake Store account. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {string} [parameters.firewallAllowAzureIps] The current state of
* allowing or disallowing IPs originating within Azure through the firewall.
* If the firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {array} [parameters.trustedIdProviders] The list of trusted identity
* providers associated with this Data Lake Store account.
*
* @param {string} [parameters.trustedIdProviderState] The current state of the
* trusted identity provider feature for this Data Lake Store account. Possible
* values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.newTier] The commitment tier to use for next
* month. Possible values include: 'Consumption', 'Commitment_1TB',
* 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB',
* 'Commitment_5PB'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccount} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccount} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccount} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginCreate(resourceGroupName: string, accountName: string, parameters: models.CreateDataLakeStoreAccountParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccount>;
beginCreate(resourceGroupName: string, accountName: string, parameters: models.CreateDataLakeStoreAccountParameters, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
beginCreate(resourceGroupName: string, accountName: string, parameters: models.CreateDataLakeStoreAccountParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
/**
* Updates the specified Data Lake Store account information.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} parameters Parameters supplied to update the Data Lake Store
* account.
*
* @param {object} [parameters.tags] Resource tags
*
* @param {string} [parameters.defaultGroup] The default owner group for all
* new folders and files created in the Data Lake Store account.
*
* @param {object} [parameters.encryptionConfig] Used for rotation of user
* managed Key Vault keys. Can only be used to rotate a user managed encryption
* Key Vault key.
*
* @param {object} [parameters.encryptionConfig.keyVaultMetaInfo] The updated
* Key Vault key to use in user managed key rotation.
*
* @param {string}
* [parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyVersion] The
* version of the user managed encryption key to update through a key rotation.
*
* @param {array} [parameters.firewallRules] The list of firewall rules
* associated with this Data Lake Store account.
*
* @param {array} [parameters.virtualNetworkRules] The list of virtual network
* rules associated with this Data Lake Store account.
*
* @param {string} [parameters.firewallState] The current state of the IP
* address firewall for this Data Lake Store account. Disabling the firewall
* does not remove existing rules, they will just be ignored until the firewall
* is re-enabled. Possible values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.firewallAllowAzureIps] The current state of
* allowing or disallowing IPs originating within Azure through the firewall.
* If the firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {array} [parameters.trustedIdProviders] The list of trusted identity
* providers associated with this Data Lake Store account.
*
* @param {string} [parameters.trustedIdProviderState] The current state of the
* trusted identity provider feature for this Data Lake Store account.
* Disabling trusted identity provider functionality does not remove the
* providers, they will just be ignored until this feature is re-enabled.
* Possible values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.newTier] The commitment tier to use for next
* month. Possible values include: 'Consumption', 'Commitment_1TB',
* 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB',
* 'Commitment_5PB'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccount>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, parameters: models.UpdateDataLakeStoreAccountParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccount>>;
/**
* Updates the specified Data Lake Store account information.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} parameters Parameters supplied to update the Data Lake Store
* account.
*
* @param {object} [parameters.tags] Resource tags
*
* @param {string} [parameters.defaultGroup] The default owner group for all
* new folders and files created in the Data Lake Store account.
*
* @param {object} [parameters.encryptionConfig] Used for rotation of user
* managed Key Vault keys. Can only be used to rotate a user managed encryption
* Key Vault key.
*
* @param {object} [parameters.encryptionConfig.keyVaultMetaInfo] The updated
* Key Vault key to use in user managed key rotation.
*
* @param {string}
* [parameters.encryptionConfig.keyVaultMetaInfo.encryptionKeyVersion] The
* version of the user managed encryption key to update through a key rotation.
*
* @param {array} [parameters.firewallRules] The list of firewall rules
* associated with this Data Lake Store account.
*
* @param {array} [parameters.virtualNetworkRules] The list of virtual network
* rules associated with this Data Lake Store account.
*
* @param {string} [parameters.firewallState] The current state of the IP
* address firewall for this Data Lake Store account. Disabling the firewall
* does not remove existing rules, they will just be ignored until the firewall
* is re-enabled. Possible values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.firewallAllowAzureIps] The current state of
* allowing or disallowing IPs originating within Azure through the firewall.
* If the firewall is disabled, this is not enforced. Possible values include:
* 'Enabled', 'Disabled'
*
* @param {array} [parameters.trustedIdProviders] The list of trusted identity
* providers associated with this Data Lake Store account.
*
* @param {string} [parameters.trustedIdProviderState] The current state of the
* trusted identity provider feature for this Data Lake Store account.
* Disabling trusted identity provider functionality does not remove the
* providers, they will just be ignored until this feature is re-enabled.
* Possible values include: 'Enabled', 'Disabled'
*
* @param {string} [parameters.newTier] The commitment tier to use for next
* month. Possible values include: 'Consumption', 'Commitment_1TB',
* 'Commitment_10TB', 'Commitment_100TB', 'Commitment_500TB', 'Commitment_1PB',
* 'Commitment_5PB'
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccount} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccount} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccount} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginUpdate(resourceGroupName: string, accountName: string, parameters: models.UpdateDataLakeStoreAccountParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccount>;
beginUpdate(resourceGroupName: string, accountName: string, parameters: models.UpdateDataLakeStoreAccountParameters, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
beginUpdate(resourceGroupName: string, accountName: string, parameters: models.UpdateDataLakeStoreAccountParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccount>): void;
/**
* Deletes the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the specified Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteMethod(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
beginDeleteMethod(resourceGroupName: string, accountName: string, callback: ServiceCallback<void>): void;
beginDeleteMethod(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists the Data Lake Store accounts within the subscription. The response
* includes a link to the next page of results, if any.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccountListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccountListResult>>;
/**
* Lists the Data Lake Store accounts within the subscription. The response
* includes a link to the next page of results, if any.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccountListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccountListResult} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccountListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccountListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.DataLakeStoreAccountListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccountListResult>): void;
/**
* Lists the Data Lake Store accounts within a specific resource group. The
* response includes a link to the next page of results, if any.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<DataLakeStoreAccountListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DataLakeStoreAccountListResult>>;
/**
* Lists the Data Lake Store accounts within a specific resource group. The
* response includes a link to the next page of results, if any.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {DataLakeStoreAccountListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {DataLakeStoreAccountListResult} [result] - The deserialized result object if an error did not occur.
* See {@link DataLakeStoreAccountListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DataLakeStoreAccountListResult>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.DataLakeStoreAccountListResult>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DataLakeStoreAccountListResult>): void;
}
/**
* @class
* FirewallRules
* __NOTE__: An instance of this class is automatically created for an
* instance of the DataLakeStoreAccountManagementClient.
*/
export interface FirewallRules {
/**
* Lists the Data Lake Store firewall rules within the specified Data Lake
* Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FirewallRuleListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByAccountWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FirewallRuleListResult>>;
/**
* Lists the Data Lake Store firewall rules within the specified Data Lake
* Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {FirewallRuleListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {FirewallRuleListResult} [result] - The deserialized result object if an error did not occur.
* See {@link FirewallRuleListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByAccount(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FirewallRuleListResult>;
listByAccount(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.FirewallRuleListResult>): void;
listByAccount(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FirewallRuleListResult>): void;
/**
* Creates or updates the specified firewall rule. During update, the firewall
* rule with the specified name will be replaced with this new firewall rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} firewallRuleName The name of the firewall rule to create or
* update.
*
* @param {object} parameters Parameters supplied to create or update the
* firewall rule.
*
* @param {string} parameters.startIpAddress The start IP address for the
* firewall rule. This can be either ipv4 or ipv6. Start and End should be in
* the same protocol.
*
* @param {string} parameters.endIpAddress The end IP address for the firewall
* rule. This can be either ipv4 or ipv6. Start and End should be in the same
* protocol.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FirewallRule>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, firewallRuleName: string, parameters: models.CreateOrUpdateFirewallRuleParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FirewallRule>>;
/**
* Creates or updates the specified firewall rule. During update, the firewall
* rule with the specified name will be replaced with this new firewall rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} firewallRuleName The name of the firewall rule to create or
* update.
*
* @param {object} parameters Parameters supplied to create or update the
* firewall rule.
*
* @param {string} parameters.startIpAddress The start IP address for the
* firewall rule. This can be either ipv4 or ipv6. Start and End should be in
* the same protocol.
*
* @param {string} parameters.endIpAddress The end IP address for the firewall
* rule. This can be either ipv4 or ipv6. Start and End should be in the same
* protocol.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {FirewallRule} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {FirewallRule} [result] - The deserialized result object if an error did not occur.
* See {@link FirewallRule} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, accountName: string, firewallRuleName: string, parameters: models.CreateOrUpdateFirewallRuleParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FirewallRule>;
createOrUpdate(resourceGroupName: string, accountName: string, firewallRuleName: string, parameters: models.CreateOrUpdateFirewallRuleParameters, callback: ServiceCallback<models.FirewallRule>): void;
createOrUpdate(resourceGroupName: string, accountName: string, firewallRuleName: string, parameters: models.CreateOrUpdateFirewallRuleParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FirewallRule>): void;
/**
* Gets the specified Data Lake Store firewall rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} firewallRuleName The name of the firewall rule to retrieve.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FirewallRule>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, accountName: string, firewallRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FirewallRule>>;
/**
* Gets the specified Data Lake Store firewall rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} firewallRuleName The name of the firewall rule to retrieve.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {FirewallRule} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {FirewallRule} [result] - The deserialized result object if an error did not occur.
* See {@link FirewallRule} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, accountName: string, firewallRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FirewallRule>;
get(resourceGroupName: string, accountName: string, firewallRuleName: string, callback: ServiceCallback<models.FirewallRule>): void;
get(resourceGroupName: string, accountName: string, firewallRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FirewallRule>): void;
/**
* Updates the specified firewall rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} firewallRuleName The name of the firewall rule to update.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.parameters] Parameters supplied to update the
* firewall rule.
*
* @param {string} [options.parameters.startIpAddress] The start IP address for
* the firewall rule. This can be either ipv4 or ipv6. Start and End should be
* in the same protocol.
*
* @param {string} [options.parameters.endIpAddress] The end IP address for the
* firewall rule. This can be either ipv4 or ipv6. Start and End should be in
* the same protocol.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FirewallRule>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, firewallRuleName: string, options?: { parameters? : models.UpdateFirewallRuleParameters, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FirewallRule>>;
/**
* Updates the specified firewall rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} firewallRuleName The name of the firewall rule to update.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.parameters] Parameters supplied to update the
* firewall rule.
*
* @param {string} [options.parameters.startIpAddress] The start IP address for
* the firewall rule. This can be either ipv4 or ipv6. Start and End should be
* in the same protocol.
*
* @param {string} [options.parameters.endIpAddress] The end IP address for the
* firewall rule. This can be either ipv4 or ipv6. Start and End should be in
* the same protocol.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {FirewallRule} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {FirewallRule} [result] - The deserialized result object if an error did not occur.
* See {@link FirewallRule} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, accountName: string, firewallRuleName: string, options?: { parameters? : models.UpdateFirewallRuleParameters, customHeaders? : { [headerName: string]: string; } }): Promise<models.FirewallRule>;
update(resourceGroupName: string, accountName: string, firewallRuleName: string, callback: ServiceCallback<models.FirewallRule>): void;
update(resourceGroupName: string, accountName: string, firewallRuleName: string, options: { parameters? : models.UpdateFirewallRuleParameters, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FirewallRule>): void;
/**
* Deletes the specified firewall rule from the specified Data Lake Store
* account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} firewallRuleName The name of the firewall rule to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, firewallRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the specified firewall rule from the specified Data Lake Store
* account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} firewallRuleName The name of the firewall rule to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, accountName: string, firewallRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, accountName: string, firewallRuleName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, firewallRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists the Data Lake Store firewall rules within the specified Data Lake
* Store account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<FirewallRuleListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FirewallRuleListResult>>;
/**
* Lists the Data Lake Store firewall rules within the specified Data Lake
* Store account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {FirewallRuleListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {FirewallRuleListResult} [result] - The deserialized result object if an error did not occur.
* See {@link FirewallRuleListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FirewallRuleListResult>;
listByAccountNext(nextPageLink: string, callback: ServiceCallback<models.FirewallRuleListResult>): void;
listByAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FirewallRuleListResult>): void;
}
/**
* @class
* VirtualNetworkRules
* __NOTE__: An instance of this class is automatically created for an
* instance of the DataLakeStoreAccountManagementClient.
*/
export interface VirtualNetworkRules {
/**
* Lists the Data Lake Store virtual network rules within the specified Data
* Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<VirtualNetworkRuleListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByAccountWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VirtualNetworkRuleListResult>>;
/**
* Lists the Data Lake Store virtual network rules within the specified Data
* Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {VirtualNetworkRuleListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {VirtualNetworkRuleListResult} [result] - The deserialized result object if an error did not occur.
* See {@link VirtualNetworkRuleListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByAccount(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VirtualNetworkRuleListResult>;
listByAccount(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.VirtualNetworkRuleListResult>): void;
listByAccount(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VirtualNetworkRuleListResult>): void;
/**
* Creates or updates the specified virtual network rule. During update, the
* virtual network rule with the specified name will be replaced with this new
* virtual network rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} virtualNetworkRuleName The name of the virtual network rule
* to create or update.
*
* @param {object} parameters Parameters supplied to create or update the
* virtual network rule.
*
* @param {string} parameters.subnetId The resource identifier for the subnet.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<VirtualNetworkRule>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, parameters: models.CreateOrUpdateVirtualNetworkRuleParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VirtualNetworkRule>>;
/**
* Creates or updates the specified virtual network rule. During update, the
* virtual network rule with the specified name will be replaced with this new
* virtual network rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} virtualNetworkRuleName The name of the virtual network rule
* to create or update.
*
* @param {object} parameters Parameters supplied to create or update the
* virtual network rule.
*
* @param {string} parameters.subnetId The resource identifier for the subnet.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {VirtualNetworkRule} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {VirtualNetworkRule} [result] - The deserialized result object if an error did not occur.
* See {@link VirtualNetworkRule} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, parameters: models.CreateOrUpdateVirtualNetworkRuleParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VirtualNetworkRule>;
createOrUpdate(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, parameters: models.CreateOrUpdateVirtualNetworkRuleParameters, callback: ServiceCallback<models.VirtualNetworkRule>): void;
createOrUpdate(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, parameters: models.CreateOrUpdateVirtualNetworkRuleParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VirtualNetworkRule>): void;
/**
* Gets the specified Data Lake Store virtual network rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} virtualNetworkRuleName The name of the virtual network rule
* to retrieve.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<VirtualNetworkRule>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VirtualNetworkRule>>;
/**
* Gets the specified Data Lake Store virtual network rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} virtualNetworkRuleName The name of the virtual network rule
* to retrieve.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {VirtualNetworkRule} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {VirtualNetworkRule} [result] - The deserialized result object if an error did not occur.
* See {@link VirtualNetworkRule} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VirtualNetworkRule>;
get(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, callback: ServiceCallback<models.VirtualNetworkRule>): void;
get(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VirtualNetworkRule>): void;
/**
* Updates the specified virtual network rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} virtualNetworkRuleName The name of the virtual network rule
* to update.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.parameters] Parameters supplied to update the
* virtual network rule.
*
* @param {string} [options.parameters.subnetId] The resource identifier for
* the subnet.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<VirtualNetworkRule>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options?: { parameters? : models.UpdateVirtualNetworkRuleParameters, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VirtualNetworkRule>>;
/**
* Updates the specified virtual network rule.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} virtualNetworkRuleName The name of the virtual network rule
* to update.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.parameters] Parameters supplied to update the
* virtual network rule.
*
* @param {string} [options.parameters.subnetId] The resource identifier for
* the subnet.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {VirtualNetworkRule} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {VirtualNetworkRule} [result] - The deserialized result object if an error did not occur.
* See {@link VirtualNetworkRule} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options?: { parameters? : models.UpdateVirtualNetworkRuleParameters, customHeaders? : { [headerName: string]: string; } }): Promise<models.VirtualNetworkRule>;
update(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, callback: ServiceCallback<models.VirtualNetworkRule>): void;
update(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options: { parameters? : models.UpdateVirtualNetworkRuleParameters, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VirtualNetworkRule>): void;
/**
* Deletes the specified virtual network rule from the specified Data Lake
* Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} virtualNetworkRuleName The name of the virtual network rule
* to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the specified virtual network rule from the specified Data Lake
* Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} virtualNetworkRuleName The name of the virtual network rule
* to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, virtualNetworkRuleName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists the Data Lake Store virtual network rules within the specified Data
* Lake Store account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<VirtualNetworkRuleListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VirtualNetworkRuleListResult>>;
/**
* Lists the Data Lake Store virtual network rules within the specified Data
* Lake Store account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {VirtualNetworkRuleListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {VirtualNetworkRuleListResult} [result] - The deserialized result object if an error did not occur.
* See {@link VirtualNetworkRuleListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VirtualNetworkRuleListResult>;
listByAccountNext(nextPageLink: string, callback: ServiceCallback<models.VirtualNetworkRuleListResult>): void;
listByAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VirtualNetworkRuleListResult>): void;
}
/**
* @class
* TrustedIdProviders
* __NOTE__: An instance of this class is automatically created for an
* instance of the DataLakeStoreAccountManagementClient.
*/
export interface TrustedIdProviders {
/**
* Lists the Data Lake Store trusted identity providers within the specified
* Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TrustedIdProviderListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByAccountWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TrustedIdProviderListResult>>;
/**
* Lists the Data Lake Store trusted identity providers within the specified
* Data Lake Store account.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TrustedIdProviderListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TrustedIdProviderListResult} [result] - The deserialized result object if an error did not occur.
* See {@link TrustedIdProviderListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByAccount(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TrustedIdProviderListResult>;
listByAccount(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.TrustedIdProviderListResult>): void;
listByAccount(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TrustedIdProviderListResult>): void;
/**
* Creates or updates the specified trusted identity provider. During update,
* the trusted identity provider with the specified name will be replaced with
* this new provider
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} trustedIdProviderName The name of the trusted identity
* provider. This is used for differentiation of providers in the account.
*
* @param {object} parameters Parameters supplied to create or replace the
* trusted identity provider.
*
* @param {string} parameters.idProvider The URL of this trusted identity
* provider.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TrustedIdProvider>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, trustedIdProviderName: string, parameters: models.CreateOrUpdateTrustedIdProviderParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TrustedIdProvider>>;
/**
* Creates or updates the specified trusted identity provider. During update,
* the trusted identity provider with the specified name will be replaced with
* this new provider
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} trustedIdProviderName The name of the trusted identity
* provider. This is used for differentiation of providers in the account.
*
* @param {object} parameters Parameters supplied to create or replace the
* trusted identity provider.
*
* @param {string} parameters.idProvider The URL of this trusted identity
* provider.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TrustedIdProvider} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TrustedIdProvider} [result] - The deserialized result object if an error did not occur.
* See {@link TrustedIdProvider} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, accountName: string, trustedIdProviderName: string, parameters: models.CreateOrUpdateTrustedIdProviderParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TrustedIdProvider>;
createOrUpdate(resourceGroupName: string, accountName: string, trustedIdProviderName: string, parameters: models.CreateOrUpdateTrustedIdProviderParameters, callback: ServiceCallback<models.TrustedIdProvider>): void;
createOrUpdate(resourceGroupName: string, accountName: string, trustedIdProviderName: string, parameters: models.CreateOrUpdateTrustedIdProviderParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TrustedIdProvider>): void;
/**
* Gets the specified Data Lake Store trusted identity provider.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} trustedIdProviderName The name of the trusted identity
* provider to retrieve.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TrustedIdProvider>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TrustedIdProvider>>;
/**
* Gets the specified Data Lake Store trusted identity provider.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} trustedIdProviderName The name of the trusted identity
* provider to retrieve.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TrustedIdProvider} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TrustedIdProvider} [result] - The deserialized result object if an error did not occur.
* See {@link TrustedIdProvider} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TrustedIdProvider>;
get(resourceGroupName: string, accountName: string, trustedIdProviderName: string, callback: ServiceCallback<models.TrustedIdProvider>): void;
get(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TrustedIdProvider>): void;
/**
* Updates the specified trusted identity provider.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} trustedIdProviderName The name of the trusted identity
* provider. This is used for differentiation of providers in the account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.parameters] Parameters supplied to update the
* trusted identity provider.
*
* @param {string} [options.parameters.idProvider] The URL of this trusted
* identity provider.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TrustedIdProvider>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options?: { parameters? : models.UpdateTrustedIdProviderParameters, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TrustedIdProvider>>;
/**
* Updates the specified trusted identity provider.
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} trustedIdProviderName The name of the trusted identity
* provider. This is used for differentiation of providers in the account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.parameters] Parameters supplied to update the
* trusted identity provider.
*
* @param {string} [options.parameters.idProvider] The URL of this trusted
* identity provider.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TrustedIdProvider} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TrustedIdProvider} [result] - The deserialized result object if an error did not occur.
* See {@link TrustedIdProvider} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options?: { parameters? : models.UpdateTrustedIdProviderParameters, customHeaders? : { [headerName: string]: string; } }): Promise<models.TrustedIdProvider>;
update(resourceGroupName: string, accountName: string, trustedIdProviderName: string, callback: ServiceCallback<models.TrustedIdProvider>): void;
update(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options: { parameters? : models.UpdateTrustedIdProviderParameters, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TrustedIdProvider>): void;
/**
* Deletes the specified trusted identity provider from the specified Data Lake
* Store account
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} trustedIdProviderName The name of the trusted identity
* provider to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the specified trusted identity provider from the specified Data Lake
* Store account
*
* @param {string} resourceGroupName The name of the Azure resource group.
*
* @param {string} accountName The name of the Data Lake Store account.
*
* @param {string} trustedIdProviderName The name of the trusted identity
* provider to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, accountName: string, trustedIdProviderName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, trustedIdProviderName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists the Data Lake Store trusted identity providers within the specified
* Data Lake Store account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TrustedIdProviderListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TrustedIdProviderListResult>>;
/**
* Lists the Data Lake Store trusted identity providers within the specified
* Data Lake Store account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TrustedIdProviderListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TrustedIdProviderListResult} [result] - The deserialized result object if an error did not occur.
* See {@link TrustedIdProviderListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TrustedIdProviderListResult>;
listByAccountNext(nextPageLink: string, callback: ServiceCallback<models.TrustedIdProviderListResult>): void;
listByAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TrustedIdProviderListResult>): void;
}
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the DataLakeStoreAccountManagementClient.
*/
export interface Operations {
/**
* Lists all of the available Data Lake Store REST API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available Data Lake Store REST API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
list(callback: ServiceCallback<models.OperationListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
}
/**
* @class
* Locations
* __NOTE__: An instance of this class is automatically created for an
* instance of the DataLakeStoreAccountManagementClient.
*/
export interface Locations {
/**
* Gets subscription-level properties and limits for Data Lake Store specified
* by resource location.
*
* @param {string} location The resource location without whitespace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<CapabilityInformation>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getCapabilityWithHttpOperationResponse(location: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CapabilityInformation>>;
/**
* Gets subscription-level properties and limits for Data Lake Store specified
* by resource location.
*
* @param {string} location The resource location without whitespace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {CapabilityInformation} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {CapabilityInformation} [result] - The deserialized result object if an error did not occur.
* See {@link CapabilityInformation} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getCapability(location: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CapabilityInformation>;
getCapability(location: string, callback: ServiceCallback<models.CapabilityInformation>): void;
getCapability(location: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CapabilityInformation>): void;
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [batch](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsbatch.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Batch extends PolicyStatement {
public servicePrefix = 'batch';
/**
* Statement provider for service [batch](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsbatch.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to cancel a job in an AWS Batch job queue in your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_CancelJob.html
*/
public toCancelJob() {
return this.to('CancelJob');
}
/**
* Grants permission to create an AWS Batch compute environment in your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_CreateComputeEnvironment.html
*/
public toCreateComputeEnvironment() {
return this.to('CreateComputeEnvironment');
}
/**
* Grants permission to create an AWS Batch job queue in your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_CreateJobQueue.html
*/
public toCreateJobQueue() {
return this.to('CreateJobQueue');
}
/**
* Grants permission to delete an AWS Batch compute environment in your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_DeleteComputeEnvironment.html
*/
public toDeleteComputeEnvironment() {
return this.to('DeleteComputeEnvironment');
}
/**
* Grants permission to delete an AWS Batch job queue in your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_DeleteJobQueue.html
*/
public toDeleteJobQueue() {
return this.to('DeleteJobQueue');
}
/**
* Grants permission to deregister an AWS Batch job definition in your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_DeregisterJobDefinition.html
*/
public toDeregisterJobDefinition() {
return this.to('DeregisterJobDefinition');
}
/**
* Grants permission to describe one or more AWS Batch compute environments in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeComputeEnvironments.html
*/
public toDescribeComputeEnvironments() {
return this.to('DescribeComputeEnvironments');
}
/**
* Grants permission to describe one or more AWS Batch job definitions in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobDefinitions.html
*/
public toDescribeJobDefinitions() {
return this.to('DescribeJobDefinitions');
}
/**
* Grants permission to describe one or more AWS Batch job queues in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobQueues.html
*/
public toDescribeJobQueues() {
return this.to('DescribeJobQueues');
}
/**
* Grants permission to describe a list of AWS Batch jobs in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html
*/
public toDescribeJobs() {
return this.to('DescribeJobs');
}
/**
* Grants permission to list jobs for a specified AWS Batch job queue in your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_ListJobs.html
*/
public toListJobs() {
return this.to('ListJobs');
}
/**
* Grants permission to list tags for an AWS Batch resource in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to register an AWS Batch job definition in your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifUser()
* - .ifPrivileged()
* - .ifImage()
* - .ifLogDriver()
* - .ifAWSLogsGroup()
* - .ifAWSLogsRegion()
* - .ifAWSLogsStreamPrefix()
* - .ifAWSLogsCreateGroup()
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_RegisterJobDefinition.html
*/
public toRegisterJobDefinition() {
return this.to('RegisterJobDefinition');
}
/**
* Grants permission to submit an AWS Batch job from a job definition in your account
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_SubmitJob.html
*/
public toSubmitJob() {
return this.to('SubmitJob');
}
/**
* Grants permission to tag an AWS Batch resource in your account
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to terminate a job in an AWS Batch job queue in your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_TerminateJob.html
*/
public toTerminateJob() {
return this.to('TerminateJob');
}
/**
* Grants permission to untag an AWS Batch resource in your account
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update an AWS Batch compute environment in your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_UpdateComputeEnvironment.html
*/
public toUpdateComputeEnvironment() {
return this.to('UpdateComputeEnvironment');
}
/**
* Grants permission to update an AWS Batch job queue in your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/batch/latest/APIReference/API_UpdateJobQueue.html
*/
public toUpdateJobQueue() {
return this.to('UpdateJobQueue');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CancelJob",
"CreateComputeEnvironment",
"CreateJobQueue",
"DeleteComputeEnvironment",
"DeleteJobQueue",
"DeregisterJobDefinition",
"RegisterJobDefinition",
"SubmitJob",
"TerminateJob",
"UpdateComputeEnvironment",
"UpdateJobQueue"
],
"Read": [
"DescribeComputeEnvironments",
"DescribeJobDefinitions",
"DescribeJobQueues",
"DescribeJobs",
"ListTagsForResource"
],
"List": [
"ListJobs"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type compute-environment to the statement
*
* https://docs.aws.amazon.com/batch/latest/userguide/compute_environments.html
*
* @param computeEnvironmentName - Identifier for the computeEnvironmentName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onComputeEnvironment(computeEnvironmentName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:batch:${Region}:${Account}:compute-environment/${ComputeEnvironmentName}';
arn = arn.replace('${ComputeEnvironmentName}', computeEnvironmentName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type job-queue to the statement
*
* https://docs.aws.amazon.com/batch/latest/userguide/job_queues.html
*
* @param jobQueueName - Identifier for the jobQueueName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onJobQueue(jobQueueName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:batch:${Region}:${Account}:job-queue/${JobQueueName}';
arn = arn.replace('${JobQueueName}', jobQueueName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type job-definition to the statement
*
* https://docs.aws.amazon.com/batch/latest/userguide/job_definitions.html
*
* @param jobDefinitionName - Identifier for the jobDefinitionName.
* @param revision - Identifier for the revision.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onJobDefinition(jobDefinitionName: string, revision: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:batch:${Region}:${Account}:job-definition/${JobDefinitionName}:${Revision}';
arn = arn.replace('${JobDefinitionName}', jobDefinitionName);
arn = arn.replace('${Revision}', revision);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type job to the statement
*
* https://docs.aws.amazon.com/batch/latest/userguide/jobs.html
*
* @param jobId - Identifier for the jobId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onJob(jobId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:batch:${Region}:${Account}:job/${JobId}';
arn = arn.replace('${JobId}', jobId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access based on the specified logging driver to determine whether awslogs group will be created for the logs
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsbatch.html#awsbatch-policy-keys
*
* Applies to actions:
* - .toRegisterJobDefinition()
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifAWSLogsCreateGroup(value?: boolean) {
return this.if(`AWSLogsCreateGroup`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access based on the awslogs group where the logs are located
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsbatch.html#awsbatch-policy-keys
*
* Applies to actions:
* - .toRegisterJobDefinition()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifAWSLogsGroup(value: string | string[], operator?: Operator | string) {
return this.if(`AWSLogsGroup`, value, operator || 'StringLike');
}
/**
* Filters access based on the region where the logs are sent to
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsbatch.html#awsbatch-policy-keys
*
* Applies to actions:
* - .toRegisterJobDefinition()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifAWSLogsRegion(value: string | string[], operator?: Operator | string) {
return this.if(`AWSLogsRegion`, value, operator || 'StringLike');
}
/**
* Filters access based on the awslogs log stream prefix
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsbatch.html#awsbatch-policy-keys
*
* Applies to actions:
* - .toRegisterJobDefinition()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifAWSLogsStreamPrefix(value: string | string[], operator?: Operator | string) {
return this.if(`AWSLogsStreamPrefix`, value, operator || 'StringLike');
}
/**
* Filters access based on the image used to start a container
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsbatch.html#awsbatch-policy-keys
*
* Applies to actions:
* - .toRegisterJobDefinition()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifImage(value: string | string[], operator?: Operator | string) {
return this.if(`Image`, value, operator || 'StringLike');
}
/**
* Filters access based on the log driver used for the container
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsbatch.html#awsbatch-policy-keys
*
* Applies to actions:
* - .toRegisterJobDefinition()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifLogDriver(value: string | string[], operator?: Operator | string) {
return this.if(`LogDriver`, value, operator || 'StringLike');
}
/**
* Filter access based on the specified privileged parameter value that determines whether the container is given elevated privileges on the host container instance (similar to the root user)
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsbatch.html#awsbatch-policy-keys
*
* Applies to actions:
* - .toRegisterJobDefinition()
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifPrivileged(value?: boolean) {
return this.if(`Privileged`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access based on the user name or numeric uid used inside the container
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awsbatch.html#awsbatch-policy-keys
*
* Applies to actions:
* - .toRegisterJobDefinition()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifUser(value: string | string[], operator?: Operator | string) {
return this.if(`User`, value, operator || 'StringLike');
}
} | the_stack |
/*
* Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info.
*/
namespace LiteMol.Visualization {
export class MaterialsHelper {
private static pickVertexShader = [
"attribute vec4 pColor;",
"varying vec4 pC;",
"void main() {",
"pC = pColor;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"].join('\n');
private static pickFragmentShader = [
"varying vec4 pC;",
"void main() {",
"gl_FragColor = pC;",
"}"].join('\n');
static getPickMaterial() {
return new THREE.ShaderMaterial({
attributes: { pColor: { type: 'v4', value: [] } },
vertexShader: MaterialsHelper.pickVertexShader,
fragmentShader: MaterialsHelper.pickFragmentShader,
blending: THREE.NoBlending,
shading: THREE.FlatShading,
side: THREE.DoubleSide
});
}
static getPickExcludeMaterial() {
return new THREE.MeshBasicMaterial({ color: THREE.ColorKeywords.white, side: THREE.DoubleSide });
}
static shader = {
uniforms: THREE.UniformsUtils.merge([
THREE.UniformsLib["common"],
THREE.UniformsLib["bump"],
THREE.UniformsLib["normalmap"],
THREE.UniformsLib["fog"],
THREE.UniformsLib["lights"],
THREE.UniformsLib["shadowmap"],
{
"emissive": { type: "c", value: new THREE.Color(0x000000) },
"specular": { type: "c", value: new THREE.Color(0x111111) },
"shininess": { type: "f", value: 2 },
"wrapRGB": { type: "v3", value: new THREE.Vector3(1, 1, 1) },
"highlightColor": { type: "v3", value: new THREE.Vector3(1, 1, 0) },
"selectionColor": { type: "v3", value: new THREE.Vector3(1, 0, 0) },
}
]),
vertexShader: [
"#define PHONG",
"varying vec3 vViewPosition;",
"#ifndef FLAT_SHADED",
" varying vec3 vNormal;",
"#endif",
THREE.ShaderChunk["common"],
THREE.ShaderChunk["map_pars_vertex"],
THREE.ShaderChunk["lightmap_pars_vertex"],
THREE.ShaderChunk["envmap_pars_vertex"],
THREE.ShaderChunk["lights_phong_pars_vertex"],
THREE.ShaderChunk["color_pars_vertex"],
THREE.ShaderChunk["morphtarget_pars_vertex"],
THREE.ShaderChunk["skinning_pars_vertex"],
THREE.ShaderChunk["shadowmap_pars_vertex"],
THREE.ShaderChunk["logdepthbuf_pars_vertex"],
"attribute float vState;",
"varying float vS;",
"void main() {",
" vS = vState;",
THREE.ShaderChunk["map_vertex"],
THREE.ShaderChunk["lightmap_vertex"],
THREE.ShaderChunk["color_vertex"],
THREE.ShaderChunk["morphnormal_vertex"],
THREE.ShaderChunk["skinbase_vertex"],
THREE.ShaderChunk["skinnormal_vertex"],
THREE.ShaderChunk["defaultnormal_vertex"],
"#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
" vNormal = normalize( transformedNormal );",
"#endif",
THREE.ShaderChunk["morphtarget_vertex"],
THREE.ShaderChunk["skinning_vertex"],
THREE.ShaderChunk["default_vertex"],
THREE.ShaderChunk["logdepthbuf_vertex"],
" vViewPosition = -mvPosition.xyz;",
THREE.ShaderChunk["worldpos_vertex"],
THREE.ShaderChunk["envmap_vertex"],
THREE.ShaderChunk["lights_phong_vertex"],
THREE.ShaderChunk["shadowmap_vertex"],
"}"
].join("\n"),
fragmentShader: [
"#define PHONG",
"uniform vec3 diffuse;",
"uniform vec3 emissive;",
"uniform vec3 specular;",
"uniform float shininess;",
"uniform float opacity;",
"uniform vec3 highlightColor;",
"uniform vec3 selectionColor;",
THREE.ShaderChunk["common"],
THREE.ShaderChunk["color_pars_fragment"],
THREE.ShaderChunk["map_pars_fragment"],
THREE.ShaderChunk["alphamap_pars_fragment"],
THREE.ShaderChunk["lightmap_pars_fragment"],
THREE.ShaderChunk["envmap_pars_fragment"],
THREE.ShaderChunk["fog_pars_fragment"],
THREE.ShaderChunk["lights_phong_pars_fragment"],
THREE.ShaderChunk["shadowmap_pars_fragment"],
THREE.ShaderChunk["bumpmap_pars_fragment"],
THREE.ShaderChunk["normalmap_pars_fragment"],
THREE.ShaderChunk["specularmap_pars_fragment"],
THREE.ShaderChunk["logdepthbuf_pars_fragment"],
"varying float vS;",
"void main() {",
" vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
" vec4 diffuseColor;",// = vec4( vColor, opacity );",
" if (vS < 0.33) { diffuseColor = vec4( vColor, opacity ); }",
" else if (vS - floor(vS + 0.1) > 0.33) { diffuseColor = vec4(highlightColor, opacity); }",
" else { diffuseColor = vec4(selectionColor, opacity); }",
THREE.ShaderChunk["logdepthbuf_fragment"],
THREE.ShaderChunk["map_fragment"],
//THREE.ShaderChunk["color_fragment"],
THREE.ShaderChunk["alphamap_fragment"],
THREE.ShaderChunk["alphatest_fragment"],
THREE.ShaderChunk["specularmap_fragment"],
THREE.ShaderChunk["lights_phong_fragment"],
THREE.ShaderChunk["lightmap_fragment"],
THREE.ShaderChunk["envmap_fragment"],
THREE.ShaderChunk["shadowmap_fragment"],
THREE.ShaderChunk["linear_to_gamma_fragment"],
THREE.ShaderChunk["fog_fragment"],
"#ifdef USE_FOG",
" if (diffuseColor.a > 0.99) { gl_FragColor = vec4( outgoingLight, diffuseColor.a ); }",
" else { gl_FragColor = vec4( outgoingLight, (1.0 - fogFactor) * diffuseColor.a ); }",
"#else",
" gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
"#endif",
"}"
].join("\n")
};
private static compareVectorAndColor(v: THREE.Vector3, c: Color) {
return v.x === c.r && v.y === c.g && v.z === c.b;
}
static updateMaterial(material: THREE.ShaderMaterial | THREE.MeshPhongMaterial, theme: Theme, object: THREE.Object3D) {
let changed = false;
if (MaterialsHelper.updateTransparencyAndFog(material, theme, object)) changed = true;
if (material instanceof THREE.ShaderMaterial && MaterialsHelper.updateHighlightColor(material, theme)) changed = true;
if (changed) material.needsUpdate = true;
}
private static updateHighlightColor(material: THREE.ShaderMaterial, theme: Theme): boolean {
let changed = false;
let color = (<any> material.uniforms).selectionColor.value as THREE.Vector3;
let selectionColor = Theme.getColor(theme, 'Selection', Theme.Default.SelectionColor);
if (!MaterialsHelper.compareVectorAndColor(color, selectionColor)) {
(<any>material.uniforms).selectionColor.value = Color.toVector(selectionColor);
changed = true;
}
color = (<any> material.uniforms).highlightColor.value as THREE.Vector3;
let highlightColor = Theme.getColor(theme, 'Highlight', Theme.Default.HighlightColor);
if (!MaterialsHelper.compareVectorAndColor(color, highlightColor)) {
(<any>material.uniforms).highlightColor.value = Color.toVector(highlightColor);
changed = true;
}
return changed;
}
private static updateTransparencyAndFog(material: THREE.Material,
theme: Theme, object: THREE.Object3D): boolean {
let transparency = theme.transparency;
let opacity = +transparency.alpha!;
if (isNaN(opacity)) opacity = 1.0;
let isTransparent = opacity <= 0.999;
let writeDepth = !!transparency.writeDepth;
if (!isTransparent) {
opacity = 1.0;
writeDepth = true;
}
if (object) object.renderOrder = isTransparent ? 1 : 0;
let changed = false;
if (material instanceof THREE.MeshPhongMaterial || material instanceof THREE.MeshBasicMaterial || material instanceof THREE.ShaderMaterial) {
if (material.transparent !== isTransparent) {
material.transparent = isTransparent;
changed = true;
}
if (material.depthWrite !== writeDepth) {
material.depthWrite = writeDepth;
changed = true;
}
if (material.opacity !== opacity) {
material.opacity = opacity;
changed = true;
}
if (material.fog !== !theme.disableFog) {
material.fog = !theme.disableFog;
changed = true;
}
if (material instanceof THREE.ShaderMaterial) {
if (material.uniforms.opacity) {
material.uniforms.opacity.value = opacity;
}
}
}
return changed;
}
static getMeshMaterial(shading = THREE.SmoothShading, isWireframe = false) {
let shader = MaterialsHelper.shader;
let ret = new THREE.ShaderMaterial({
uniforms: THREE.UniformsUtils.clone(shader.uniforms),
attributes: { "vState": { type: 'f', value: [] } },
lights: true,
fog: true,
vertexShader: shader.vertexShader,
fragmentShader: shader.fragmentShader,
shading,
side: THREE.DoubleSide,
vertexColors: THREE.VertexColors,
blending: THREE.NormalBlending,
wireframe: isWireframe,
linewidth: 1
});
return ret;
}
static getPhongVertexColorMaterial() {
return new THREE.MeshPhongMaterial({ specular: 0xAAAAAA, /*ambient: 0xffffff, */shininess: 2, shading: THREE.SmoothShading, vertexColors: THREE.VertexColors, side: THREE.DoubleSide, metal: true });
}
static getDefaultHighlightMaterial() {
return new THREE.MeshPhongMaterial({ color: 0xFFFFFF, specular: 0xAAAAAA,/* ambient: 0xffffff,*/ shininess: 2, shading: THREE.SmoothShading, side: THREE.DoubleSide, metal: true });
}
static applyColorToBuffer(bufferAttribute: THREE.BufferAttribute, color: Color) {
let buffer = bufferAttribute.array;
for (let i = 0, __i = buffer.length; i < __i; i += 3) {
buffer[i] = color.r;
buffer[i + 1] = color.g;
buffer[i + 2] = color.b;
}
bufferAttribute.needsUpdate = true;
}
static applyColorToMap(map: Selection.VertexMap, bufferAttribute: THREE.BufferAttribute, getter: (i: number, c: Color) => void) {
let buffer = bufferAttribute.array,
color = { r: 0.45, g: 0.45, b: 0.45 },
vertexRanges = map.vertexRanges;
for (let elementIndex of map.elementIndices) {
let elementOffset = map.elementMap.get(elementIndex)!;
let rangeStart = map.elementRanges[2 * elementOffset],
rangeEnd = map.elementRanges[2 * elementOffset + 1];
if (rangeStart === rangeEnd) continue;
getter(elementIndex, color);
for (let i = rangeStart; i < rangeEnd; i += 2) {
let vStart = vertexRanges[i], vEnd = vertexRanges[i + 1];
for (let j = vStart; j < vEnd; j++) {
buffer[j * 3] = color.r,
buffer[j * 3 + 1] = color.g,
buffer[j * 3 + 2] = color.b;
}
}
}
bufferAttribute.needsUpdate = true;
}
}
} | the_stack |
import Notifications from '../lib/collections/notifications/collection';
import Conversations from '../lib/collections/conversations/collection';
import { subscriptionTypes } from '../lib/collections/subscriptions/schema';
import Localgroups from '../lib/collections/localgroups/collection';
import Users from '../lib/collections/users/collection';
import { getUserEmail } from '../lib/collections/users/helpers';
import { Posts } from '../lib/collections/posts';
import { postStatuses } from '../lib/collections/posts/constants';
import { postGetPageUrl, postIsApproved } from '../lib/collections/posts/helpers';
import { Comments } from '../lib/collections/comments/collection'
import { reasonUserCantReceiveEmails, wrapAndSendEmail } from './emails/renderEmail';
import './emailComponents/EmailWrapper';
import './emailComponents/NewPostEmail';
import './emailComponents/PostNominatedEmail';
import './emailComponents/PrivateMessagesEmail';
import { EventDebouncer } from './debouncer';
import * as _ from 'underscore';
import { Components } from '../lib/vulcan-lib/components';
import { updateMutator } from './vulcan-lib/mutators';
import { getCollectionHooks } from './mutationCallbacks';
import { asyncForeachSequential } from '../lib/utils/asyncUtils';
import { CallbackHook } from '../lib/vulcan-lib/callbacks';
import React from 'react';
import TagRels from '../lib/collections/tagRels/collection';
import { RSVPType } from '../lib/collections/posts/schema';
import { forumTypeSetting } from '../lib/instanceSettings';
import { getSubscribedUsers, createNotifications, getUsersWhereLocationIsInNotificationRadius } from './notificationCallbacksHelpers'
import moment from 'moment';
// Callback for a post being published. This is distinct from being created in
// that it doesn't fire on draft posts, and doesn't fire on posts that are awaiting
// moderator approval because they're a user's first post (but does fire when
// they're approved).
export const postPublishedCallback = new CallbackHook<[DbPost]>("post.published");
const removeNotification = async (notificationId: string) => {
await updateMutator({
collection: Notifications,
documentId: notificationId,
data: { deleted: true },
validate: false
})
}
const sendPostByEmail = async (users: Array<DbUser>, postId: string, reason: string) => {
let post = await Posts.findOne(postId);
if (!post) throw Error(`Can't find post to send by email: ${postId}`)
for(let user of users) {
if(!reasonUserCantReceiveEmails(user)) {
await wrapAndSendEmail({
user,
subject: post.title,
body: <Components.NewPostEmail documentId={post._id} reason={reason}/>
});
} else {
//eslint-disable-next-line no-console
console.log(`Skipping user ${user.username} when emailing: ${reasonUserCantReceiveEmails(user)}`);
}
}
}
// Add notification callback when a post is approved
getCollectionHooks("Posts").editAsync.add(function PostsEditRunPostApprovedAsyncCallbacks(post, oldPost) {
if (postIsApproved(post) && !postIsApproved(oldPost)) {
void createNotifications({userIds: [post.userId], notificationType: 'postApproved', documentType: 'post', documentId: post._id});
}
});
function postIsPublic (post: DbPost) {
return !post.draft && post.status === postStatuses.STATUS_APPROVED
}
// Export for testing
/** create notifications for a new post being published */
export async function postsNewNotifications (post: DbPost) {
if (postIsPublic(post)) {
// track the users who we've notified, so that we only do so once per user, even if they qualify for more than one notification -
// start by excluding the post author
let userIdsNotified: string[] = [post.userId];
// first, if the post is in a group, notify all users who are subscribed to the group
if (post.groupId) {
// Load the group, so we know who the organizers are
const group = await Localgroups.findOne(post.groupId);
if (group) {
const organizerIds = group.organizerIds;
const groupSubscribedUsers = await getSubscribedUsers({
documentId: post.groupId,
collectionName: "Localgroups",
type: subscriptionTypes.newEvents,
potentiallyDefaultSubscribedUserIds: organizerIds,
userIsDefaultSubscribed: u => u.autoSubscribeAsOrganizer,
});
const userIdsToNotify = _.difference(groupSubscribedUsers.map(user => user._id), userIdsNotified)
if (post.isEvent) {
await createNotifications({userIds: userIdsToNotify, notificationType: 'newEvent', documentType: 'post', documentId: post._id});
} else {
await createNotifications({userIds: userIdsToNotify, notificationType: 'newGroupPost', documentType: 'post', documentId: post._id});
}
// don't notify these users again
userIdsNotified = _.union(userIdsNotified, userIdsToNotify)
}
}
// then notify all users who want to be notified of events in a radius
if (post.isEvent && post.mongoLocation) {
const radiusNotificationUsers = await getUsersWhereLocationIsInNotificationRadius(post.mongoLocation)
const userIdsToNotify = _.difference(radiusNotificationUsers.map(user => user._id), userIdsNotified)
await createNotifications({userIds: userIdsToNotify, notificationType: "newEventInRadius", documentType: "post", documentId: post._id})
// don't notify these users again
userIdsNotified = _.union(userIdsNotified, userIdsToNotify)
}
// finally notify all users who are subscribed to the post's author
let authorSubscribedUsers = await getSubscribedUsers({
documentId: post.userId,
collectionName: "Users",
type: subscriptionTypes.newPosts
})
const userIdsToNotify = _.difference(authorSubscribedUsers.map(user => user._id), userIdsNotified)
await createNotifications({userIds: userIdsToNotify, notificationType: 'newPost', documentType: 'post', documentId: post._id});
}
}
postPublishedCallback.add(postsNewNotifications);
getCollectionHooks("Posts").updateAsync.add(async function eventUpdatedNotifications ({document: newPost, oldDocument: oldPost}: {document: DbPost, oldDocument: DbPost}) {
// don't bother notifying people about past or unscheduled events
const isUpcomingEvent = newPost.startTime && moment().isBefore(moment(newPost.startTime))
// only send notifications if the event was already published *before* being edited
const alreadyPublished = !oldPost.draft && !newPost.draft && !oldPost.authorIsUnreviewed && !newPost.authorIsUnreviewed
if (
(
!_.isEqual(newPost.mongoLocation, oldPost.mongoLocation) ||
(newPost.joinEventLink !== oldPost.joinEventLink) ||
!moment(newPost.startTime).isSame(moment(oldPost.startTime)) ||
!moment(newPost.endTime).isSame(moment(oldPost.endTime))
)
&& newPost.isEvent && isUpcomingEvent && alreadyPublished)
{
// track the users who we've notified, so that we only do so once per user, even if they qualify for more than one notification
let userIdsNotified: string[] = []
// first email everyone who RSVP'd to the event
const rsvpUsers = await getUsersToNotifyAboutEvent(newPost)
for (let {userId,email} of rsvpUsers) {
if (!email) continue
const user = await Users.findOne(userId)
if (userId) {
userIdsNotified.push(userId)
}
await wrapAndSendEmail({
user: user,
to: email,
subject: `Event updated: ${newPost.title}`,
body: <Components.EventUpdatedEmail postId={newPost._id} />
});
}
// then notify all users who want to be notified of events in a radius
if (newPost.mongoLocation) {
const radiusNotificationUsers = await getUsersWhereLocationIsInNotificationRadius(newPost.mongoLocation)
const userIdsToNotify = _.difference(radiusNotificationUsers.map(user => user._id), userIdsNotified)
await createNotifications({userIds: userIdsToNotify, notificationType: "editedEventInRadius", documentType: "post", documentId: newPost._id})
}
}
});
getCollectionHooks("Posts").editAsync.add(async function RemoveRedraftNotifications(newPost: DbPost, oldPost: DbPost) {
if (!postIsPublic(newPost) && postIsPublic(oldPost)) {
//eslint-disable-next-line no-console
console.info("Post redrafted, removing notifications");
// delete post notifications
const postNotifications = await Notifications.find({documentId: newPost._id}).fetch()
postNotifications.forEach(notification => removeNotification(notification._id))
// delete tagRel notifications
const tagRels = await TagRels.find({postId:newPost._id}).fetch()
await asyncForeachSequential(tagRels, async (tagRel) => {
const tagRelNotifications = await Notifications.find({documentId: tagRel._id}).fetch()
tagRelNotifications.forEach(notification => removeNotification(notification._id))
})
}
});
async function findUsersToEmail(filter: MongoSelector<DbUser>) {
let usersMatchingFilter = await Users.find(filter).fetch();
if (forumTypeSetting.get() === 'EAForum') {
return usersMatchingFilter
}
let usersToEmail = usersMatchingFilter.filter(u => {
if (u.email && u.emails && u.emails.length) {
let primaryAddress = u.email;
for(let i=0; i<u.emails.length; i++)
{
if(u.emails[i].address === primaryAddress && u.emails[i].verified)
return true;
}
return false;
} else {
return false;
}
});
return usersToEmail
}
const curationEmailDelay = new EventDebouncer<string,null>({
name: "curationEmail",
defaultTiming: {
type: "delayed",
delayMinutes: 20,
},
callback: async (postId) => {
const post = await Posts.findOne(postId);
// Still curated? If it was un-curated during the 20 minute delay, don't
// send emails.
if (post?.curatedDate) {
// Email only non-admins (admins get emailed immediately, without the
// delay).
let usersToEmail = await findUsersToEmail({'emailSubscribedToCurated': true, isAdmin: false});
await sendPostByEmail(usersToEmail, postId, "you have the \"Email me new posts in Curated\" option enabled");
} else {
//eslint-disable-next-line no-console
console.log(`Not sending curation notice for ${post?.title} because it was un-curated during the delay period.`);
}
}
});
getCollectionHooks("Posts").editAsync.add(async function PostsCurateNotification (post: DbPost, oldPost: DbPost) {
if(post.curatedDate && !oldPost.curatedDate) {
// Email admins immediately, everyone else after a 20-minute delay, so that
// we get a chance to catch formatting issues with the email.
const adminsToEmail = await findUsersToEmail({'emailSubscribedToCurated': true, isAdmin: true});
await sendPostByEmail(adminsToEmail, post._id, "you have the \"Email me new posts in Curated\" option enabled");
await curationEmailDelay.recordEvent({
key: post._id,
data: null,
af: false
});
}
});
getCollectionHooks("TagRels").newAsync.add(async function TaggedPostNewNotifications(tagRel: DbTagRel) {
const subscribedUsers = await getSubscribedUsers({
documentId: tagRel.tagId,
collectionName: "Tags",
type: subscriptionTypes.newTagPosts
})
const post = await Posts.findOne({_id:tagRel.postId})
if (post && postIsPublic(post)) {
const subscribedUserIds = _.map(subscribedUsers, u=>u._id);
// Don't notify the person who created the tagRel
let tagSubscriberIdsToNotify = _.difference(subscribedUserIds, [tagRel.userId])
//eslint-disable-next-line no-console
console.info("Post tagged, creating notifications");
await createNotifications({userIds: tagSubscriberIdsToNotify, notificationType: 'newTagPosts', documentType: 'tagRel', documentId: tagRel._id});
}
});
async function getEmailFromRsvp({email, userId}: RSVPType): Promise<string | undefined> {
if (email) {
// Email is free text
// eslint-disable-next-line
const matches = email.match(/(([^<>()\[\]\\.,;:\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,}))/)
const foundEmail = matches?.[0]
if (foundEmail) {
return foundEmail
}
}
if (userId) {
const user = await Users.findOne(userId)
if (user) {
return getUserEmail(user)
}
}
}
export async function getUsersToNotifyAboutEvent(post: DbPost): Promise<{rsvp: RSVPType, userId: string|null, email: string|undefined}[]> {
if (!post.rsvps || !post.rsvps.length) {
return [];
}
return await Promise.all(post.rsvps
.filter(r => r.response !== "no")
.map(async (r: RSVPType) => ({
rsvp: r,
userId: r.userId,
email: await getEmailFromRsvp(r),
}))
);
}
async function notifyRsvps(comment: DbComment, post: DbPost) {
if (!post.rsvps || !post.rsvps.length) {
return;
}
const emailsToNotify = await getUsersToNotifyAboutEvent(post);
const postLink = postGetPageUrl(post, true);
for (let {userId,email} of emailsToNotify) {
if (!email) continue;
const user = await Users.findOne(userId);
await wrapAndSendEmail({
user: user,
to: email,
subject: `New comment on ${post.title}`,
body: <Components.EmailComment commentId={comment._id}/>,
});
}
}
// TODO: Make sure this notification is working properly, and re-enable it. In practice this was sending out notifications in a confusing way (some people getting notified late into the review). This might just be because this was implemented partway into the review, and some posts slipped through that hadn't previously gotten voted on. But I don't have time to think about it right now. Turning it off for now (-- Raymond Jan 2022)
// getCollectionHooks("ReviewVotes").newAsync.add(async function PositiveReviewVoteNotifications(reviewVote: DbReviewVote) {
// const post = reviewVote.postId ? await Posts.findOne(reviewVote.postId) : null;
// if (post && post.positiveReviewVoteCount > 1) {
// const notifications = await Notifications.find({documentId:post._id, type: "postNominated" }).fetch()
// if (!notifications.length) {
// await createNotifications({userIds: [post.userId], notificationType: "postNominated", documentType: "post", documentId: post._id})
// }
// }
// })
// add new comment notification callback on comment submit
getCollectionHooks("Comments").newAsync.add(async function CommentsNewNotifications(comment: DbComment) {
const post = comment.postId ? await Posts.findOne(comment.postId) : null;
if (post?.isEvent) {
await notifyRsvps(comment, post);
}
// keep track of whom we've notified (so that we don't notify the same user twice for one comment,
// if e.g. they're both the author of the post and the author of a comment being replied to)
let notifiedUsers: Array<string> = [];
// 1. Notify users who are subscribed to the parent comment
if (comment.parentCommentId) {
const parentComment = await Comments.findOne(comment.parentCommentId)
if (parentComment) {
const subscribedUsers = await getSubscribedUsers({
documentId: comment.parentCommentId,
collectionName: "Comments",
type: subscriptionTypes.newReplies,
potentiallyDefaultSubscribedUserIds: [parentComment.userId],
userIsDefaultSubscribed: u => u.auto_subscribe_to_my_comments
})
const subscribedUserIds = _.map(subscribedUsers, u=>u._id);
// Don't notify the author of their own comment, and filter out the author
// of the parent-comment to be treated specially (with a newReplyToYou
// notification instead of a newReply notification).
let parentCommentSubscriberIdsToNotify = _.difference(subscribedUserIds, [comment.userId, parentComment.userId])
await createNotifications({userIds: parentCommentSubscriberIdsToNotify, notificationType: 'newReply', documentType: 'comment', documentId: comment._id});
// Separately notify author of comment with different notification, if
// they are subscribed, and are NOT the author of the comment
if (subscribedUserIds.includes(parentComment.userId) && parentComment.userId !== comment.userId) {
await createNotifications({userIds: [parentComment.userId], notificationType: 'newReplyToYou', documentType: 'comment', documentId: comment._id});
notifiedUsers = [...notifiedUsers, parentComment.userId];
}
}
}
// 2. Notify users who are subscribed to the post (which may or may not include the post's author)
let userIdsSubscribedToPost: Array<string> = [];
const usersSubscribedToPost = await getSubscribedUsers({
documentId: comment.postId,
collectionName: "Posts",
type: subscriptionTypes.newComments,
potentiallyDefaultSubscribedUserIds: post ? [post.userId] : [],
userIsDefaultSubscribed: u => u.auto_subscribe_to_my_posts
})
userIdsSubscribedToPost = _.map(usersSubscribedToPost, u=>u._id);
// if the post is associated with a group, also (potentially) notify the group organizers
if (post && post.groupId) {
const group = await Localgroups.findOne(post.groupId)
if (group?.organizerIds && group.organizerIds.length) {
const subsWithOrganizers = await getSubscribedUsers({
documentId: comment.postId,
collectionName: "Posts",
type: subscriptionTypes.newComments,
potentiallyDefaultSubscribedUserIds: group.organizerIds,
userIsDefaultSubscribed: u => u.autoSubscribeAsOrganizer
})
userIdsSubscribedToPost = _.union(userIdsSubscribedToPost, _.map(subsWithOrganizers, u=>u._id))
}
}
// Notify users who are subscribed to shortform posts
if (!comment.topLevelCommentId && comment.shortform) {
const usersSubscribedToShortform = await getSubscribedUsers({
documentId: comment.postId,
collectionName: "Posts",
type: subscriptionTypes.newShortform
})
const userIdsSubscribedToShortform = _.map(usersSubscribedToShortform, u=>u._id);
await createNotifications({userIds: userIdsSubscribedToShortform, notificationType: 'newShortform', documentType: 'comment', documentId: comment._id});
notifiedUsers = [ ...userIdsSubscribedToShortform, ...notifiedUsers]
}
// remove userIds of users that have already been notified
// and of comment author (they could be replying in a thread they're subscribed to)
const postSubscriberIdsToNotify = _.difference(userIdsSubscribedToPost, [...notifiedUsers, comment.userId])
if (postSubscriberIdsToNotify.length > 0) {
await createNotifications({userIds: postSubscriberIdsToNotify, notificationType: 'newComment', documentType: 'comment', documentId: comment._id})
}
});
getCollectionHooks("Messages").newAsync.add(async function messageNewNotification(message: DbMessage) {
const conversationId = message.conversationId;
const conversation = await Conversations.findOne(conversationId);
if (!conversation) throw Error(`Can't find conversation for message: ${message}`)
// For on-site notifications, notify everyone except the sender of the
// message. For email notifications, notify everyone including the sender
// (since if there's a back-and-forth in the grouped notifications, you want
// to see your own messages.)
const recipientIds = conversation.participantIds.filter((id) => (id !== message.userId));
// Create notification
await createNotifications({userIds: recipientIds, notificationType: 'newMessage', documentType: 'message', documentId: message._id, noEmail: message.noEmail});
});
export async function bellNotifyEmailVerificationRequired (user: DbUser) {
await createNotifications({userIds: [user._id], notificationType: 'emailVerificationRequired', documentType: null, documentId: null});
}
getCollectionHooks("Posts").editAsync.add(async function PostsEditNotifyUsersSharedOnPost (newPost: DbPost, oldPost: DbPost) {
if (!_.isEqual(newPost.shareWithUsers, oldPost.shareWithUsers)) {
// Right now this only creates notifications when users are shared (and not when they are "unshared")
// because currently notifications are hidden from you if you don't have view-access to a post.
// TODO: probably fix that, such that users can see when they've lost access to post. [but, eh, I'm not sure this matters that much]
const sharedUsers = _.difference(newPost.shareWithUsers || [], oldPost.shareWithUsers || [])
await createNotifications({userIds: sharedUsers, notificationType: "postSharedWithUser", documentType: "post", documentId: newPost._id})
}
});
getCollectionHooks("Posts").newAsync.add(async function PostsNewNotifyUsersSharedOnPost (post: DbPost) {
const { _id, shareWithUsers = [], coauthorStatuses = [] } = post;
const coauthors = coauthorStatuses.filter(({ confirmed }) => confirmed).map(({ userId }) => userId);
const userIds = shareWithUsers.filter((user) => !coauthors.includes(user));
await createNotifications({userIds, notificationType: "postSharedWithUser", documentType: "post", documentId: _id})
});
getCollectionHooks("Posts").newAsync.add(async function CoauthorRequestNotifications(post: DbPost) {
const { _id, coauthorStatuses = [], hasCoauthorPermission } = post;
if (hasCoauthorPermission) {
return;
}
const userIds = coauthorStatuses.filter(({ requested }) => !requested).map(({ userId }) => userId);
await createNotifications({userIds, notificationType: "coauthorRequestNotification", documentType: "post", documentId: _id});
await updateMutator({
collection: Posts,
documentId: _id,
data: {
coauthorStatuses: coauthorStatuses.map((status) => ({ ...status, requested: true })),
},
validate: false,
})
});
const AlignmentSubmissionApprovalNotifyUser = async (newDocument: DbPost|DbComment, oldDocument: DbPost|DbComment) => {
const newlyAF = newDocument.af && !oldDocument.af
const userSubmitted = oldDocument.suggestForAlignmentUserIds && oldDocument.suggestForAlignmentUserIds.includes(oldDocument.userId)
const reviewed = !!newDocument.reviewForAlignmentUserId
const documentType = newDocument.hasOwnProperty("answer") ? 'comment' : 'post'
if (newlyAF && userSubmitted && reviewed) {
await createNotifications({userIds: [newDocument.userId], notificationType: "alignmentSubmissionApproved", documentType, documentId: newDocument._id})
}
}
getCollectionHooks("Posts").editAsync.add(AlignmentSubmissionApprovalNotifyUser)
getCollectionHooks("Comments").editAsync.add(AlignmentSubmissionApprovalNotifyUser) | the_stack |
import PlayerComponent from '../interfaces/component';
import Player from '../player';
import { EVENT_OPTIONS, IS_ANDROID, IS_IPHONE } from '../utils/constants';
import { removeElement } from '../utils/general';
/**
* Fullscreen element.
*
* @description Following the Fullscreen API, this class toggles media dimensions to present video
* using the user's entire screen, even when the player is playing Ads.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
* @see https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/cross_browser_video_player#Fullscreen
* @class Fullscreen
* @implements PlayerComponent
*/
class Fullscreen implements PlayerComponent {
/**
* Flag to determine if fullscreen is available natively.
*
* @type boolean
* @memberof Fullscreen
*/
public fullScreenEnabled: boolean;
/**
* Instance of OpenPlayer.
*
* @private
* @type Player
* @memberof Fullscreen
*/
#player: Player;
/**
* Flag to determine if media is currently being played in fullscreen mode.
*
* @private
* @type boolean
* @memberof Fullscreen
*/
#isFullscreen: boolean;
/**
* Button to toggle fullscreen effect.
*
* @private
* @type HTMLButtonElement
* @memberof Fullscreen
*/
#button: HTMLButtonElement;
/**
* List of events when fullscreen change is fired.
*
* @private
* @type string[]
* @memberof Fullscreen
*/
#fullscreenEvents: string[] = [];
/**
* Storage for user's full screen width.
*
* @private
* @type number
* @memberof Fullscreen
*/
#fullscreenWidth = 0;
/**
* Storage for user's full screen height.
*
* @private
* @type number
* @memberof Fullscreen
*/
#fullscreenHeight = 0;
/**
* Callback when user clicks Fullscreen button.
*
* @private
* @memberof Fullscreen
*/
#clickEvent: () => void;
/**
* Default labels from player's config
*
* @private
* @type object
* @memberof Fullscreen
*/
#labels: any;
/**
* Position of the button to be indicated as part of its class name
*
* @private
* @type {string}
* @memberof Fullscreen
*/
#position: string;
/**
* Layer where the control item will be placed
*
* @private
* @type {string}
* @memberof Captions
*/
#layer: string;
/**
* Create an instance of Fullscreen.
*
* @param {Player} player
* @returns {Fullscreen}
* @memberof Fullscreen
*/
constructor(player: Player, position: string, layer: string) {
this.#player = player;
this.#labels = player.getOptions().labels;
this.#position = position;
this.#layer = layer;
this.#isFullscreen = document.body.classList.contains('op-fullscreen__on');
const target = (document as any);
// Check if fullscreen is supported
this.fullScreenEnabled = !!(target.fullscreenEnabled || target.mozFullScreenEnabled || target.msFullscreenEnabled
|| target.webkitSupportsFullscreen || target.webkitFullscreenEnabled
|| (document.createElement('video') as any).webkitRequestFullScreen);
this._keydownEvent = this._keydownEvent.bind(this);
this._fullscreenChange = this._fullscreenChange.bind(this);
this.#fullscreenEvents = [
'fullscreenchange',
'mozfullscreenchange',
'webkitfullscreenchange',
'msfullscreenchange',
];
this.#fullscreenEvents.forEach(event => {
document.addEventListener(event, this._fullscreenChange, EVENT_OPTIONS);
});
this._setFullscreenData(false);
this.#player.getContainer().addEventListener('keydown', this._keydownEvent, EVENT_OPTIONS);
// Since iPhone still doesn't accept the regular Fullscreen API, use the following events
if (IS_IPHONE) {
this.#player.getElement().addEventListener('webkitbeginfullscreen', () => {
this.#isFullscreen = true;
this._setFullscreenData(true);
document.body.classList.add('op-fullscreen__on');
}, EVENT_OPTIONS);
this.#player.getElement().addEventListener('webkitendfullscreen', () => {
this.#isFullscreen = false;
this._setFullscreenData(false);
document.body.classList.remove('op-fullscreen__on');
}, EVENT_OPTIONS);
}
return this;
}
/**
* Create a button and set global events to toggle fullscreen.
*
* @inheritDoc
* @memberof Fullscreen
*/
public create(): void {
this.#button = document.createElement('button');
this.#button.type = 'button';
this.#button.className = `op-controls__fullscreen op-control__${this.#position}`;
this.#button.tabIndex = 0;
this.#button.title = this.#labels.fullscreen;
this.#button.setAttribute('aria-controls', this.#player.id);
this.#button.setAttribute('aria-pressed', 'false');
this.#button.setAttribute('aria-label', this.#labels.fullscreen);
this.#button.innerHTML = `<span class="op-sr">${this.#labels.fullscreen}</span>`;
this.#clickEvent = () => {
this.#button.setAttribute('aria-pressed', 'true');
this.toggleFullscreen();
};
this.#clickEvent = this.#clickEvent.bind(this);
this.#button.addEventListener('click', this.#clickEvent, EVENT_OPTIONS);
this.#player.getControls().getLayer(this.#layer).appendChild(this.#button);
}
/**
*
* @inheritDoc
* @memberof Fullscreen
*/
public destroy(): void {
this.#player.getContainer().removeEventListener('keydown', this._keydownEvent);
this.#fullscreenEvents.forEach(event => {
document.removeEventListener(event, this._fullscreenChange);
});
if (IS_IPHONE) {
this.#player.getElement().removeEventListener('webkitbeginfullscreen', () => {
this.#isFullscreen = true;
this._setFullscreenData(false);
document.body.classList.add('op-fullscreen__on');
});
this.#player.getElement().removeEventListener('webkitendfullscreen', () => {
this.#isFullscreen = false;
this._setFullscreenData(true);
document.body.classList.remove('op-fullscreen__on');
});
}
this.#button.removeEventListener('click', this.#clickEvent);
removeElement(this.#button);
}
/**
* Enter/cancel fullscreen depending of browser's capabilities.
*
* If browser does not support native Fullscreen API, player will adjust the video
* and its parent container's dimensions via width and height styles.
* @memberof Fullscreen
*/
public toggleFullscreen(): void {
// The video is currently in fullscreen mode
if (this.#isFullscreen) {
const target = (document as any);
if (target.exitFullscreen) {
target.exitFullscreen();
} else if (target.mozCancelFullScreen) {
target.mozCancelFullScreen();
} else if ((document as any).webkitCancelFullScreen) {
target.webkitCancelFullScreen();
} else if (target.msExitFullscreen) {
target.msExitFullscreen();
} else {
this._fullscreenChange();
}
document.body.classList.remove('op-fullscreen__on');
} else {
const video = (this.#player.getElement() as any);
this.#fullscreenWidth = window.screen.width;
this.#fullscreenHeight = window.screen.height;
if (video.requestFullscreen) {
video.parentElement.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.parentElement.mozRequestFullScreen();
} else if (video.webkitRequestFullScreen) {
video.parentElement.webkitRequestFullScreen();
} else if (video.msRequestFullscreen) {
video.parentElement.msRequestFullscreen();
} else if (video.webkitEnterFullscreen) {
video.webkitEnterFullscreen();
} else {
this._fullscreenChange();
}
document.body.classList.add('op-fullscreen__on');
}
if (typeof window !== 'undefined' && (IS_ANDROID || IS_IPHONE)) {
const screen = window.screen;
if (screen.orientation) {
if (!this.#isFullscreen) {
screen.orientation.lock('landscape');
}
}
}
}
/**
* Callback to toggle fullscreen for browsers that do not support native Fullscreen API.
*
* @private
* @memberof Fullscreen
*/
private _fullscreenChange(): void {
const width = this.#isFullscreen ? undefined : this.#fullscreenWidth;
const height = this.#isFullscreen ? undefined : this.#fullscreenHeight;
this._setFullscreenData(!this.#isFullscreen);
if (this.#player.isAd()) {
this.#player.getAd().resizeAds(width, height);
}
this.#isFullscreen = !this.#isFullscreen;
if (this.#isFullscreen) {
document.body.classList.add('op-fullscreen__on');
} else {
document.body.classList.remove('op-fullscreen__on');
}
this._resize(width, height);
}
/**
* Update the `data-fullscreen` of the player's container and toggle button's class
* depending if player is on fullscreen mode or not.
*
* @private
* @param {boolean} state Whether media is fullscreen or not
* @memberof Fullscreen
*/
private _setFullscreenData(state: boolean): void {
this.#player.getContainer().setAttribute('data-fullscreen', (!!state).toString());
if (this.#button) {
if (state) {
this.#button.classList.add('op-controls__fullscreen--out');
} else {
this.#button.classList.remove('op-controls__fullscreen--out');
}
}
}
/**
* Set dimensions for the video tag and player's container.
*
* @private
* @param {?number} width The width of the media
* @param {?number} height The height of the media
* @memberof Fullscreen
*/
private _resize(width?: number, height?: number): void {
const wrapper = this.#player.getContainer();
const video = this.#player.getElement();
const options = this.#player.getOptions();
let styles = '';
if (width) {
wrapper.style.width = '100%';
video.style.width = '100%';
} else if (options.width) {
const defaultWidth = typeof options.width === 'number' ? `${options.width}px` : options.width;
styles += `width: ${defaultWidth} !important;`;
video.style.removeProperty('width');
} else {
video.style.removeProperty('width');
wrapper.style.removeProperty('width');
}
if (height) {
video.style.height = '100%';
wrapper.style.height = '100%';
} else if (options.height) {
const defaultHeight = typeof options.height === 'number' ? `${options.height}px` : options.height;
styles += `height: ${defaultHeight} !important;`;
video.style.removeProperty('height');
} else {
video.style.removeProperty('height');
wrapper.style.removeProperty('height');
}
if (styles) {
wrapper.setAttribute('style', styles);
}
}
/**
* Use the `Enter` and space bar keys to go fullscreen if the focus is on player.
*
* @private
* @param {KeyboardEvent} e
* @memberof Fullscreen
*/
private _keydownEvent(e: KeyboardEvent) {
const key = e.which || e.keyCode || 0;
const fullscreenBtnFocused = document?.activeElement?.classList.contains('op-controls__fullscreen');
if (fullscreenBtnFocused && (key === 13 || key === 32)) {
this.toggleFullscreen();
e.preventDefault();
e.stopPropagation();
}
}
}
export default Fullscreen; | the_stack |
import { QuestionOutlineIcon } from '@chakra-ui/icons';
import {
Box,
Button,
Flex,
Input,
Spacer,
Tooltip,
useToast,
} from '@chakra-ui/react';
import { css } from '@emotion/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import Cookies from 'js-cookie';
import React, {
Fragment,
useState,
} from 'react';
import ReactSelect from 'react-select';
import { useUserSession } from '../hooks/useUserSession';
import { UserModel } from '../lib/faunadb/models/userModel';
import settings from '../settings';
import { UserSession } from '../types/auth/UserSession';
import { Project } from '../types/graphql/graphql';
import { ReactSelectDefaultOption } from '../types/ReactSelect';
import { humanizeEmail } from '../utils/user';
import {
mutateLocalUser,
mutateLocalUserActiveProjectLabel,
} from '../utils/userSession';
import AuthFormModal from './AuthFormModal';
type Props = {}
const Nav: React.FunctionComponent<Props> = (props) => {
const userSession = useUserSession();
const [projectFormMode, setProjectFormMode] = useState<'display' | 'edit' | 'create'>('display');
console.log('user', userSession);
const toast = useToast({
isClosable: true,
duration: 5000,
position: 'bottom-right',
});
const projectAsReactSelectOptions: ReactSelectDefaultOption[] = userSession?.projects?.map((project: Project) => {
return {
value: project?.id as string,
label: project?.label as string,
};
}) as ReactSelectDefaultOption[];
return (
<header
css={css`
.nav {
height: ${settings.layout.nav.height}px;
a {
margin-left: 10px;
margin-right: 10px;
}
.select-active-project {
width: 200px;
}
}
`}
>
<nav className={'nav'}>
<Flex>
<Box
p="2"
fontSize="sm"
>
{
userSession?.isAuthenticated ? (
<Fragment>
Welcome <b><Tooltip label={userSession?.email}>{humanizeEmail(userSession?.email as string)}</Tooltip></b>!<br />
You are currently working on your personal document.
</Fragment>
) : (
<Fragment>
You are currently <b>anonymous</b> and working on a shared document.
</Fragment>
)
}
</Box>
<Spacer />
<Box p="2">
{
userSession?.isAuthenticated ? (
<Flex>
{
projectFormMode === 'edit' && (
<Input
defaultValue={userSession?.activeProject?.label}
placeholder={'Project name'}
onKeyPress={async (e) => {
if (e.code === 'Enter') {
const label: string = (e?.target as HTMLInputElement)?.value;
// Save the new project label
const userModel = new UserModel();
try {
// Update local cache immediately to given a feeling of instantaneousness
mutateLocalUserActiveProjectLabel(userSession as UserSession, label);
// Update the project in the DB, if this fails the error will be caught
const updatedProject = await userModel.updateProjectLabel(userSession as UserSession, userSession?.activeProject?.id as string, label);
toast({
title: `Project updated`,
description: `The project "${userSession?.activeProject?.label}" has been renamed to "${updatedProject?.label}"`,
status: 'success',
});
} catch (e) {
toast({
title: `Error`,
description: `The project "${userSession?.activeProject?.label}" couldn't be renamed. Error: "${e.message}"`,
status: 'error',
duration: null,
});
} finally {
// Refresh our local cache to make sure it's up-to-date
userSession?.refresh?.();
}
setProjectFormMode('display');
}
}}
autoFocus={true}
/>
)
}
{
projectFormMode === 'create' && (
<Input
placeholder={'New project name'}
onKeyPress={async (e) => {
if (e.code === 'Enter') {
const label: string = (e?.target as HTMLInputElement)?.value;
// Save the new project label
const userModel = new UserModel();
try {
// Update local cache immediately
// mutateLocalUserActiveProjectLabel(userSession as UserSession, label);
// Create the project in the DB, if this fails the error will be caught
const { project: createdProject } = await userModel.createProjectWithCanvas(userSession as UserSession, label);
// Change the active project
Cookies.set('activeProjectId', createdProject?.id);
toast({
title: `Project created`,
description: `The project "${createdProject?.label}" has been created."`,
status: 'success',
});
} catch (e) {
toast({
title: `Error`,
description: `The project "${label}" couldn't be created. Error: "${e.message}"`,
status: 'error',
duration: null,
});
} finally {
// Refresh our local cache to make sure it's up-to-date
userSession?.refresh?.();
}
setProjectFormMode('display');
}
}}
autoFocus={true}
/>
)
}
{
projectFormMode === 'display' && (
<ReactSelect
className={'select-active-project'}
isMulti={false}
value={projectAsReactSelectOptions?.find((option: ReactSelectDefaultOption) => option?.value === userSession?.activeProject?.id)}
options={projectAsReactSelectOptions}
onChange={((selectedOption: ReactSelectDefaultOption) => {
const selectedProjectId = selectedOption?.value;
// Update local cache immediately to given a feeling of instantaneousness
mutateLocalUser(userSession as UserSession, {
...userSession as UserSession,
activeProject: userSession?.projects?.find((project: Project) => project?.id === selectedProjectId),
});
// Change the active project
Cookies.set('activeProjectId', selectedProjectId);
// Refresh our local cache to make sure it's up-to-date
// This will force the user API endpoint to refresh the active project which will be resolved using the cookie's value
userSession?.refresh?.();
}) as any}
/>
)
}
<Tooltip label={`Edit active project's title`}>
<Button
size={'xs'}
variant={'ghost'}
onClick={() => {
// Toggle display/edit
projectFormMode === 'display' ? setProjectFormMode('edit') : setProjectFormMode('display');
}}
>
<FontAwesomeIcon icon={projectFormMode === 'display' ? 'edit' : 'times-circle'} />
</Button>
</Tooltip>
{
projectFormMode === 'display' && (
<Tooltip label={`Add a new project`}>
<Button
size={'xs'}
variant={'ghost'}
onClick={() => setProjectFormMode('create')}
>
<FontAwesomeIcon icon={'plus-circle'} />
</Button>
</Tooltip>
)
}
</Flex>
) : (
null
)
}
</Box>
<Spacer />
<Box p="2">
{
userSession?.isAuthenticated ? (
<a href="/api/logout">
<Button>Logout</Button>
</a>
) : (
<Fragment>
<AuthFormModal
mode={'login'}
/>
<AuthFormModal
mode={'create-account'}
/>
<Tooltip label="Creating an account will allow you to work on your own document" fontSize="md">
<QuestionOutlineIcon />
</Tooltip>
</Fragment>
)
}
</Box>
</Flex>
</nav>
</header>
);
};
export default Nav; | the_stack |
import {
IAttributes, IAugmentedJQuery, ICompileService, IDocumentService, IParseService, IPromise, IScope,
ITimeoutService
} from 'angular';
import * as ng1 from 'angular';
import {
DataResult, DataResults, DataRowGroup, GroupedDataResults, NgTableParams, NgTableEventsChannel,
PageButton
} from '../core';
import { ColumnDef, ColumnDefPartial, DynamicTableColDef, SelectData, TableHtmlAttributes } from './public-interfaces';
import { NgTableColumn } from './ngTableColumn';
/**
* @private
*/
export interface TableScope<T> extends IScope {
$columns: ColumnDef[];
$loading: boolean;
$filterRow: {
disabled: boolean;
};
$data?: DataResults<T>;
$groups?: GroupedDataResults<T>;
$groupRow: {
show: boolean;
};
show_filter: boolean;
pages: PageButton[];
templates: {
header: string;
pagination: string;
},
params: NgTableParams<T>
}
/**
* The controller for the {@link ngTable ngTable} and {@link ngTableDynamic ngTableDynamic} directives
*/
export class NgTableController<TParams, TCol extends ColumnDefPartial | DynamicTableColDef> {
static $inject = [
'$scope', '$timeout', '$parse', '$compile', '$attrs', '$element', '$document', 'ngTableColumn', 'ngTableEventsChannel'
];
private delayFilter: (callback: () => void, ms: number) => void;
private get hasVisibleFilterColumn() {
if (!this.$scope.$columns) return false;
return this.some(this.$scope.$columns, ($column) => {
return $column.show(this.$scope) && !!$column.filter(this.$scope);
});
}
constructor(
private $scope: TableScope<TParams>,
$timeout: ITimeoutService,
private $parse: IParseService,
private $compile: ICompileService,
private $attrs: IAttributes & TableHtmlAttributes,
private $element: IAugmentedJQuery,
private $document: IDocumentService,
private ngTableColumn: NgTableColumn<TCol>,
private ngTableEventsChannel: NgTableEventsChannel) {
const isFirstTimeLoad = true;
$scope.$filterRow = { disabled: false };
$scope.$loading = false;
// until such times as the directive uses an isolated scope, we need to ensure that the check for
// the params field only consults the "own properties" of the $scope. This is to avoid seeing the params
// field on a $scope higher up in the prototype chain
if (!$scope.hasOwnProperty("params")) {
$scope.params = new NgTableParams<TParams>(true);
}
this.delayFilter = (function () {
let timer: IPromise<any>;
return (callback: () => void, ms: number) => {
$timeout.cancel(timer);
timer = $timeout(callback, ms);
};
})();
// watch for when a new NgTableParams is bound to the scope
// CRITICAL: the watch must be for reference and NOT value equality; this is because NgTableParams maintains
// the current data page as a field. Checking this for value equality would be terrible for performance
// and potentially cause an error if the items in that array has circular references
this.$scope.$watch<NgTableParams<TParams>>('params', (newParams, oldParams) => {
if (newParams === oldParams || !newParams) {
return;
}
newParams.reload();
}, false);
this.subscribeToTableEvents();
}
private onDataReloadStatusChange(newStatus: boolean/*, oldStatus*/) {
if (!newStatus || this.$scope.params.hasErrorState()) {
return;
}
const currentParams = this.$scope.params;
const filterOptions = currentParams.settings().filterOptions;
if (currentParams.hasFilterChanges()) {
const applyFilter = () => {
currentParams.page(1);
currentParams.reload();
};
if (filterOptions.filterDelay) {
this.delayFilter(applyFilter, filterOptions.filterDelay);
} else {
applyFilter();
}
} else {
currentParams.reload();
}
}
compileDirectiveTemplates() {
if (!this.$element.hasClass('ng-table')) {
this.$scope.templates = {
header: (this.$attrs.templateHeader ? this.$attrs.templateHeader : 'ng-table/header.html'),
pagination: (this.$attrs.templatePagination ? this.$attrs.templatePagination : 'ng-table/pager.html')
};
this.$element.addClass('ng-table');
let headerTemplate: IAugmentedJQuery | undefined;
// $element.find('> thead').length === 0 doesn't work on jqlite
let theadFound = false;
ng1.forEach(this.$element.children(), (e) => {
if (e.tagName === 'THEAD') {
theadFound = true;
}
});
if (!theadFound) {
headerTemplate = ng1.element('<thead ng-include="templates.header"></thead>', this.$document);
this.$element.prepend(headerTemplate);
}
const paginationTemplate = ng1.element(
'<div ng-table-pagination="params" template-url="templates.pagination"></div>',
this.$document
);
this.$element.after(paginationTemplate);
if (headerTemplate) {
this.$compile(headerTemplate)(this.$scope);
}
this.$compile(paginationTemplate)(this.$scope);
}
}
loadFilterData($columns: ColumnDef[]) {
ng1.forEach($columns, ($column) => {
const result = $column.filterData(this.$scope);
if (!result) {
delete $column.filterData;
return undefined;
}
if (isPromiseLike(result)) {
delete $column.filterData;
return result.then(data => {
// our deferred can eventually return arrays, functions and objects
if (!ng1.isArray(data) && !ng1.isFunction(data) && !ng1.isObject(data)) {
// if none of the above was found - we just want an empty array
data = [];
}
$column.data = data;
});
}
// otherwise, we just return what the user gave us. It could be a function, array, object, whatever
else {
return $column.data = result;
}
});
function isPromiseLike(val: any): val is IPromise<SelectData> {
return val && typeof val === 'object' && typeof val.then === 'function';
}
}
buildColumns(columns: TCol[]): ColumnDef[] {
// todo: use strictNullChecks and remove guard clause
const result: ColumnDef[] = [];
(columns || []).forEach(col => {
result.push(this.ngTableColumn.buildColumn(col, this.$scope, result));
});
return result
}
parseNgTableDynamicExpr(attr: string) {
if (!attr || attr.indexOf(" with ") > -1) {
const parts = attr.split(/\s+with\s+/);
return {
tableParams: parts[0],
columns: parts[1]
};
} else {
throw new Error('Parse error (expected example: ng-table-dynamic=\'tableParams with cols\')');
}
}
setupBindingsToInternalScope(tableParamsExpr: string) {
// note: this we're setting up watches to simulate angular's isolated scope bindings
// note: is REALLY important to watch for a change to the ngTableParams *reference* rather than
// $watch for value equivalence. This is because ngTableParams references the current page of data as
// a field and it's important not to watch this
this.$scope.$watch<NgTableParams<TParams>>(tableParamsExpr, (params) => {
if (params === undefined) {
return;
}
this.$scope.params = params;
}, false);
this.setupFilterRowBindingsToInternalScope();
this.setupGroupRowBindingsToInternalScope();
}
private setupFilterRowBindingsToInternalScope() {
if (this.$attrs.showFilter) {
this.$scope.$parent.$watch<boolean>(this.$attrs.showFilter, (value) => {
this.$scope.show_filter = value;
});
} else {
this.$scope.$watch(() => this.hasVisibleFilterColumn, (value) => {
this.$scope.show_filter = value;
})
}
if (this.$attrs.disableFilter) {
this.$scope.$parent.$watch<boolean>(this.$attrs.disableFilter, (value) => {
this.$scope.$filterRow.disabled = value;
});
}
}
private setupGroupRowBindingsToInternalScope() {
this.$scope.$groupRow = { show: false };
if (this.$attrs.showGroup) {
const showGroupGetter = this.$parse(this.$attrs.showGroup);
this.$scope.$parent.$watch<boolean>(showGroupGetter, (value) => {
this.$scope.$groupRow.show = value;
});
if (showGroupGetter.assign) {
// setup two-way databinding thus allowing ngTableGrowRow to assign to the showGroup expression
this.$scope.$watch<boolean>('$groupRow.show', (value) => {
showGroupGetter.assign(this.$scope.$parent, value);
});
}
} else {
this.$scope.$watch<boolean>('params.hasGroup()', (newValue) => {
this.$scope.$groupRow.show = newValue;
});
}
}
private getVisibleColumns() {
return (this.$scope.$columns || []).filter((c) => {
return c.show(this.$scope);
});
}
private subscribeToTableEvents() {
this.$scope.$watch('params.isDataReloadRequired()', (newStatus: boolean/*, oldStatus*/) => {
this.onDataReloadStatusChange(newStatus);
});
this.ngTableEventsChannel.onAfterReloadData<TParams>(
(params, newDatapage) => {
const visibleColumns = this.getVisibleColumns();
if (params.hasGroup()) {
this.$scope.$groups = (newDatapage || []) as GroupedDataResults<TParams>;
this.$scope.$groups.visibleColumnCount = visibleColumns.length;
} else {
this.$scope.$data = (newDatapage || []) as DataResults<TParams>;
this.$scope.$data.visibleColumnCount = visibleColumns.length;
}
},
this.$scope,
(publisher) => this.$scope.params === publisher
);
this.ngTableEventsChannel.onPagesChanged<TParams>(
(params, newPages) => {
this.$scope.pages = newPages;
},
this.$scope,
(publisher) => this.$scope.params === publisher
);
}
private some<T>(array: T[], predicate: (item: T) => boolean) {
let found = false;
for (let i = 0; i < array.length; i++) {
const obj = array[i];
if (predicate(obj)) {
found = true;
break;
}
}
return found;
}
} | the_stack |
import Parser, { DocEntry as DefaultDocEntry } from "./Parser";
import { Config } from "./config";
export { Config };
export interface DocEntry extends DefaultDocEntry {
rowIndex?: number;
columnIndex?: number;
isRef?: boolean;
fileWidth?: number;
fileHeight?: number;
tableWidth?: number;
tableHeight?: number;
memberLayouts?: any;
exportLayouts?: any;
}
const reType = /(\w+)(\[\])*/i;
const findMaxLetter = (docEntry: DocEntry, config: Config) => {
const headerCount = docEntry.name.length + (docEntry.type.length > config.maxShowTypeLength ? config.maxShowTypeLength : docEntry.type.length);
if (docEntry.members && docEntry.members.length > 0) {
const maxCount = docEntry.members.reduce((prev, current) => {
const letterCount = current.name ? current.name.length : 0 + (
current.type ? (current.type.length > config.maxShowTypeLength ? config.maxShowTypeLength : current.type.length) : 0
);
return letterCount > prev ? letterCount : prev;
}, 0);
return headerCount > maxCount ? headerCount : maxCount;
} else {
return headerCount;
}
};
const getTableWidth = (docEntry: DocEntry, config: Config) => {
const { textPadding, itemPadding } = config.tableStyle;
return findMaxLetter(docEntry, config) * 12; // + textPadding + itemPadding * 2;
};
const getTableHeight = (docEntry: DocEntry, config: Config) => {
const { headerHeight, itemHeight } = config.tableStyle;
return headerHeight + itemHeight * (docEntry.members ? docEntry.members.length : 0);
};
let allDocEntry: DocEntry[] = [];
export function getFileDocEntries(currFileName: string, startRowIndex: number = 0, config: Config, isInit = true) {
if (isInit) {
allDocEntry = [];
}
const alreadyHadFile = allDocEntry.some(fileDocEntry => fileDocEntry.filename && fileDocEntry.filename.toLowerCase() === currFileName.toLowerCase());
if (alreadyHadFile) return;
const _p = new Parser();
_p.getAllLocalMembers = Boolean(config.getAllLocalMembers);
const fileDocEntry: DocEntry = _p.parse(currFileName);
setLayouts(currFileName, startRowIndex, config, fileDocEntry);
setLayouts(currFileName, startRowIndex, config, fileDocEntry, true);
if (fileDocEntry.filename) {
allDocEntry.push(fileDocEntry);
}
return allDocEntry;
}
export function setLayouts(currFileName: string, startRowIndex: number = 0, config: Config, fileDocEntry: DocEntry, setExportLayouts = false) {
let currMembers = fileDocEntry.members ? [...fileDocEntry.members] : [];
if (setExportLayouts) {
currMembers = currMembers.filter(member => {
return fileDocEntry.exportMembers.includes(member.name)
});
}
let prevFileTop = 0;
const alreadyHadFile = allDocEntry.some(fileDocEntry => fileDocEntry.filename && fileDocEntry.filename.toLowerCase() === currFileName.toLowerCase());
if (alreadyHadFile && !setExportLayouts) return;
const memberRowDepth = {
maxDepth: 0,
depths: {} as any
};
function setDefaultMember(name: string) {
if (!currMembers.some(member => member.name === name)) return;
if (memberRowDepth.depths[name] === void 0) {
memberRowDepth.depths[name] = 0;
}
}
function setMemberRef(name: string, refKey: string) {
if (!currMembers.some(member => member.name === refKey)) return;
setDefaultMember(refKey);
refKey = refKey; //`${refKey} + 1`
if (memberRowDepth.depths[name] === void 0 || typeof memberRowDepth.depths[name] === "number") {
memberRowDepth.depths[name] = refKey;
} else if (typeof memberRowDepth.depths[name] === "string") {
memberRowDepth.depths[name] = [memberRowDepth.depths[name], refKey];
} else if (Array.isArray(memberRowDepth.depths[name])) {
memberRowDepth.depths[name].push(refKey);
}
}
const { fileMaxDepth } = config;
const getNewFileDocEntry = (newFileName: string) => {
if (!newFileName) return;
if ((typeof fileMaxDepth === "number" && startRowIndex < fileMaxDepth) || typeof fileMaxDepth !== "number") {
if (!alreadyHadFile) {
getFileDocEntries(newFileName, startRowIndex + 1, config, false);
}
}
}
fileDocEntry.rowIndex = startRowIndex;
fileDocEntry.fileWidth = 0;
fileDocEntry.fileHeight = 0;
if (fileDocEntry.resolvedModules) {
fileDocEntry.resolvedModules.forEach(({ resolvedFileName, isExternalLibraryImport }) => {
if (resolvedFileName && !isExternalLibraryImport) {
getNewFileDocEntry(resolvedFileName);
}
})
}
if (currMembers) {
currMembers.forEach((memberDocEntry: DocEntry, index) => {
const { members, type } = memberDocEntry;
setDefaultMember(memberDocEntry.name);
// set columnIndex
memberDocEntry.columnIndex = index;
// set tableWidth
memberDocEntry.tableWidth = getTableWidth(memberDocEntry, config);
memberDocEntry.tableHeight = getTableHeight(memberDocEntry, config);
if (memberDocEntry.extends) {
(memberDocEntry.extends as DefaultDocEntry[]).forEach(member => {
const { escapedName, name } = member;
const typeName = escapedName || name;
// Get ReactComponent Extends
if (typeName === "Component") {
const reComponent = /(?:React\.)?(?:Component)\<?((\w+\,?\s?)+)\>?/im;
const result = reComponent.exec(memberDocEntry.valueDeclarationText);
if (result[1]) {
const statePropsTypes = result[1].split(",").map(str => str.trim());
statePropsTypes.forEach(statePropsType => {
setDefaultMember(statePropsType);
setMemberRef(memberDocEntry.name, statePropsType);
});
}
} else {
setMemberRef(memberDocEntry.name, typeName);
}
});
}
// set local ref
if (type === "Interface" || type === "Class") {
if (!members) return;
members.forEach((member: DocEntry, index) => {
const escapedName = reType.test(member.type) ? member.type.match(reType)[1] : member.name;
let localIndex = -1;
if (escapedName) {
for (const index in fileDocEntry.locals) {
if (fileDocEntry.locals[index].name === escapedName) {
localIndex = Number(index);
setDefaultMember(escapedName);
setMemberRef(memberDocEntry.name, escapedName);
break;
}
}
}
if (localIndex > -1) {
const { filename } = fileDocEntry.locals[localIndex];
member.filename = filename;
member.isRef = true;
getNewFileDocEntry(filename);
}
});
}
});
const memberNames = Object.keys(memberRowDepth.depths);
while(memberNames.some(key => typeof memberRowDepth.depths[key] !== "number")) {
memberNames.forEach(key => {
const refKey = memberRowDepth.depths[key];
if (refKey === 0) {
}
else if (typeof refKey === "string") {
if (typeof memberRowDepth.depths[refKey] === "number") {
memberRowDepth.depths[key] = memberRowDepth.depths[refKey] + 1;
}
}
else if (Array.isArray(refKey)) {
if (refKey.some(key => typeof key === "string")) {
refKey.forEach((newKey, index) => {
if (typeof newKey === "string") {
if (typeof memberRowDepth.depths[newKey] === "number") {
memberRowDepth.depths[key][index] = memberRowDepth.depths[newKey] + 1;
}
}
});
} else {
memberRowDepth.depths[key] = refKey.reduce((prev, current) => current > prev ? current : prev, 0)
}
}
});
}
// find row maxDepth
memberRowDepth.maxDepth = memberNames.map(key => memberRowDepth[key]).reduce((prev, current) => current > prev ? current: prev, 0);
// get layout
function getTableRect(memberName: string) {
let result = { tableWidth: 0, tableHeight: 0 };
if (fileDocEntry && currMembers) {
for (const member of (currMembers as DocEntry[])) {
if (member.name === memberName) {
result = { tableWidth: member.tableWidth, tableHeight: member.tableHeight };
break;
}
}
}
return result;
}
const memberLayouts: {
memberPositions?: {
[key: string]: { x: number; y: number, rowIndex: number };
},
rows?: {
heihgt?: number;
maxWidth?: number;
maxCloumn?: number;
}[]
} = {
memberPositions: {},
rows: []
};
memberNames.forEach((memberName, index) => {
const memberRowIndex = memberRowDepth.depths[memberName];
if (memberLayouts.rows[memberRowIndex] === void 0) {
memberLayouts.rows[memberRowIndex] = {
heihgt: -config.fileStyle.tableOffset,
maxWidth: 0,
maxCloumn: -1
}
}
const rect = getTableRect(memberName);
memberLayouts.memberPositions[memberName] = { x: 0, y: (prevFileTop + config.fileStyle.headerHeight + config.fileStyle.heightPadding) + (memberLayouts.rows[memberRowIndex].heihgt + config.fileStyle.tableOffset), rowIndex: memberRowIndex };
memberLayouts.rows[memberRowIndex].heihgt += rect.tableHeight + config.fileStyle.tableOffset;
memberLayouts.rows[memberRowIndex].maxCloumn += 1;
if (rect.tableWidth > memberLayouts.rows[memberRowIndex].maxWidth) {
memberLayouts.rows[memberRowIndex].maxWidth = rect.tableWidth;
}
});
// set x position
for (const memberName in memberLayouts.memberPositions) {
const position = memberLayouts.memberPositions[memberName];
position.x = (
position.rowIndex === 0 ? 0 : (
memberLayouts.rows.slice(0, position.rowIndex).reduce((prev, current) => prev + current.maxWidth, 0)
)
) + position.rowIndex * config.fileStyle.tableOffset;
}
// calculator file padding
fileDocEntry.fileHeight += memberLayouts.rows.reduce((prev, current) => prev < current.heihgt ? current.heihgt : prev, 0) + (
config.fileStyle.headerHeight + config.fileStyle.heightPadding * 2
);
fileDocEntry.fileWidth += memberLayouts.rows.reduce((prev, current) => prev + current.maxWidth, 0) + (
config.fileStyle.tableOffset * (memberRowDepth.maxDepth) + config.fileStyle.widthPadding * 2
);
if (setExportLayouts) {
fileDocEntry.exportLayouts = memberLayouts;
} else {
fileDocEntry.memberLayouts = memberLayouts;
}
// fileDocEntry["memberTreeDepth"] = memberRowDepth;
prevFileTop = fileDocEntry.fileHeight + config.fileStyle.fileOffset;
} else {
fileDocEntry.fileHeight = config.fileStyle.headerHeight;
fileDocEntry.fileWidth = 500;
}
}
export default getFileDocEntries; | the_stack |
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { AbstractClient } from "../../../common/abstract_client"
import { ClientConfig } from "../../../common/interface"
import {
DescribeUserCmdTasksResponse,
RunUserCmdRequest,
CreatePsaRegulationRequest,
DescribeDeviceInventoryResponse,
DescribeOsInfoResponse,
DescribeOsInfoRequest,
DescribeTaskOperationLogResponse,
CreateCustomImageRequest,
DescribeCustomImagesRequest,
DescribeUserCmdTaskInfoResponse,
DescribeDevicesResponse,
ModifyLanIpRequest,
DeviceClass,
DescribeRepairTaskConstantRequest,
DeletePsaRegulationRequest,
DescribeCustomImageProcessRequest,
CpuInfo,
CustomImage,
ModifyDeviceAutoRenewFlagRequest,
StartDevicesResponse,
BindPsaTagRequest,
DescribeRegionsResponse,
DevicePartition,
OfflineDevicesResponse,
ModifyPsaRegulationRequest,
RecoverDevicesRequest,
DescribeDeviceClassPartitionRequest,
ZoneInfo,
CreateSpotDeviceResponse,
BuyDevicesRequest,
DescribeHardwareSpecificationRequest,
Tag,
CreateCustomImageResponse,
HostedDeviceOutBandInfo,
ReturnDevicesRequest,
ModifyDeviceAliasesResponse,
PsaRegulation,
DescribeDevicePartitionResponse,
DescribeHostedDeviceOutBandInfoRequest,
RebootDevicesResponse,
ResetDevicePasswordRequest,
SubtaskStatus,
DescribeDeviceInventoryRequest,
DescribeCustomImagesResponse,
DeviceAlias,
DeleteCustomImagesRequest,
PartitionInfo,
DescribeDevicePositionRequest,
UserCmdTaskInfo,
ShutdownDevicesResponse,
TaskType,
DeleteUserCmdsRequest,
DeviceDiskSizeInfo,
AttachCamRoleRequest,
DescribeDeviceClassResponse,
DescribeDeviceHardwareInfoResponse,
ModifyUserCmdRequest,
DescribeDevicePriceInfoResponse,
ReloadDeviceOsResponse,
RunUserCmdResponse,
ReloadDeviceOsRequest,
DescribeUserCmdsRequest,
DescribeTaskInfoRequest,
RepairTaskControlResponse,
DescribeRegionsRequest,
DescribePsaRegulationsRequest,
UnbindPsaTagResponse,
DescribeDevicePriceInfoRequest,
DescribeDevicePartitionRequest,
TaskInfo,
ModifyPsaRegulationResponse,
UserCmdTask,
TaskOperationLog,
FailedTaskInfo,
DescribeDevicePositionResponse,
DeleteUserCmdsResponse,
ModifyDeviceAliasesRequest,
ModifyPayModePre2PostResponse,
SuccessTaskInfo,
SetOutBandVpnAuthPasswordRequest,
OfflineDevicesRequest,
DeviceHardwareInfo,
DiskInfo,
SetOutBandVpnAuthPasswordResponse,
DescribeTaskInfoResponse,
DescribeUserCmdTaskInfoRequest,
CreateUserCmdResponse,
ModifyUserCmdResponse,
ModifyPayModePre2PostRequest,
DeviceOperationLog,
DescribeRepairTaskConstantResponse,
BuyDevicesResponse,
ModifyLanIpResponse,
DescribePsaRegulationsResponse,
StartDevicesRequest,
DescribeUserCmdsResponse,
ModifyDeviceAutoRenewFlagResponse,
DescribeOperationResultResponse,
DescribeDeviceClassRequest,
ModifyCustomImageAttributeRequest,
DeletePsaRegulationResponse,
DeviceClassPartitionInfo,
DescribeTaskOperationLogRequest,
DescribeDeviceOperationLogRequest,
DescribeOperationResultRequest,
AttachCamRoleResponse,
RecoverDevicesResponse,
DetachCamRoleResponse,
ShutdownDevicesRequest,
UnbindPsaTagRequest,
ModifyCustomImageAttributeResponse,
RegionInfo,
UserCmd,
CustomImageProcess,
CreateSpotDeviceRequest,
OsInfo,
CreateUserCmdRequest,
ReturnDevicesResponse,
BindPsaTagResponse,
DescribeHostedDeviceOutBandInfoResponse,
DevicePriceInfo,
RebootDevicesRequest,
DeleteCustomImagesResponse,
DescribeDevicesRequest,
DescribeHardwareSpecificationResponse,
CreatePsaRegulationResponse,
DescribeCustomImageProcessResponse,
DescribeDeviceHardwareInfoRequest,
DescribeDeviceOperationLogResponse,
RepairTaskControlRequest,
DevicePositionInfo,
DeviceInfo,
ResetDevicePasswordResponse,
DescribeUserCmdTasksRequest,
DetachCamRoleRequest,
DescribeDeviceClassPartitionResponse,
} from "./bm_models"
/**
* bm client
* @class
*/
export class Client extends AbstractClient {
constructor(clientConfig: ClientConfig) {
super("bm.tencentcloudapi.com", "2018-04-23", clientConfig)
}
/**
* 获取自定义脚本信息列表
*/
async DescribeUserCmds(
req: DescribeUserCmdsRequest,
cb?: (error: string, rep: DescribeUserCmdsResponse) => void
): Promise<DescribeUserCmdsResponse> {
return this.request("DescribeUserCmds", req, cb)
}
/**
* 重启机器
*/
async RebootDevices(
req: RebootDevicesRequest,
cb?: (error: string, rep: RebootDevicesResponse) => void
): Promise<RebootDevicesResponse> {
return this.request("RebootDevices", req, cb)
}
/**
* 允许修改规则信息及关联故障类型
*/
async ModifyPsaRegulation(
req: ModifyPsaRegulationRequest,
cb?: (error: string, rep: ModifyPsaRegulationResponse) => void
): Promise<ModifyPsaRegulationResponse> {
return this.request("ModifyPsaRegulation", req, cb)
}
/**
* 获取预授权规则列表
*/
async DescribePsaRegulations(
req: DescribePsaRegulationsRequest,
cb?: (error: string, rep: DescribePsaRegulationsResponse) => void
): Promise<DescribePsaRegulationsResponse> {
return this.request("DescribePsaRegulations", req, cb)
}
/**
* 修改物理机服务器自动续费标志
*/
async ModifyDeviceAutoRenewFlag(
req: ModifyDeviceAutoRenewFlagRequest,
cb?: (error: string, rep: ModifyDeviceAutoRenewFlagResponse) => void
): Promise<ModifyDeviceAutoRenewFlagResponse> {
return this.request("ModifyDeviceAutoRenewFlag", req, cb)
}
/**
* 销毁黑石物理机实例:可以销毁物理机列表中的竞价实例,或回收站列表中所有计费模式的实例
*/
async OfflineDevices(
req: OfflineDevicesRequest,
cb?: (error: string, rep: OfflineDevicesResponse) => void
): Promise<OfflineDevicesResponse> {
return this.request("OfflineDevices", req, cb)
}
/**
* 修改物理机内网IP(不重装系统)
*/
async ModifyLanIp(
req: ModifyLanIpRequest,
cb?: (error: string, rep: ModifyLanIpResponse) => void
): Promise<ModifyLanIpResponse> {
return this.request("ModifyLanIp", req, cb)
}
/**
* 运行自定义脚本
*/
async RunUserCmd(
req: RunUserCmdRequest,
cb?: (error: string, rep: RunUserCmdResponse) => void
): Promise<RunUserCmdResponse> {
return this.request("RunUserCmd", req, cb)
}
/**
* 查询自定义镜像制作进度
*/
async DescribeCustomImageProcess(
req: DescribeCustomImageProcessRequest,
cb?: (error: string, rep: DescribeCustomImageProcessResponse) => void
): Promise<DescribeCustomImageProcessResponse> {
return this.request("DescribeCustomImageProcess", req, cb)
}
/**
* 开启服务器
*/
async StartDevices(
req: StartDevicesRequest,
cb?: (error: string, rep: StartDevicesResponse) => void
): Promise<StartDevicesResponse> {
return this.request("StartDevices", req, cb)
}
/**
* 重装操作系统
*/
async ReloadDeviceOs(
req: ReloadDeviceOsRequest,
cb?: (error: string, rep: ReloadDeviceOsResponse) => void
): Promise<ReloadDeviceOsResponse> {
return this.request("ReloadDeviceOs", req, cb)
}
/**
* 查询设备硬件配置信息,如 CPU 型号,内存大小,磁盘大小和数量
*/
async DescribeDeviceHardwareInfo(
req: DescribeDeviceHardwareInfoRequest,
cb?: (error: string, rep: DescribeDeviceHardwareInfoResponse) => void
): Promise<DescribeDeviceHardwareInfoResponse> {
return this.request("DescribeDeviceHardwareInfo", req, cb)
}
/**
* 获取自定义脚本任务列表
*/
async DescribeUserCmdTasks(
req: DescribeUserCmdTasksRequest,
cb?: (error: string, rep: DescribeUserCmdTasksResponse) => void
): Promise<DescribeUserCmdTasksResponse> {
return this.request("DescribeUserCmdTasks", req, cb)
}
/**
* 创建预授权规则
*/
async CreatePsaRegulation(
req: CreatePsaRegulationRequest,
cb?: (error: string, rep: CreatePsaRegulationResponse) => void
): Promise<CreatePsaRegulationResponse> {
return this.request("CreatePsaRegulation", req, cb)
}
/**
* 获取设备类型
*/
async DescribeDeviceClass(
req: DescribeDeviceClassRequest,
cb?: (error: string, rep: DescribeDeviceClassResponse) => void
): Promise<DescribeDeviceClassResponse> {
return this.request("DescribeDeviceClass", req, cb)
}
/**
* 购买黑石物理机
*/
async BuyDevices(
req: BuyDevicesRequest,
cb?: (error: string, rep: BuyDevicesResponse) => void
): Promise<BuyDevicesResponse> {
return this.request("BuyDevices", req, cb)
}
/**
* 修改自定义脚本
*/
async ModifyUserCmd(
req: ModifyUserCmdRequest,
cb?: (error: string, rep: ModifyUserCmdResponse) => void
): Promise<ModifyUserCmdResponse> {
return this.request("ModifyUserCmd", req, cb)
}
/**
* 删除自定义脚本
*/
async DeleteUserCmds(
req: DeleteUserCmdsRequest,
cb?: (error: string, rep: DeleteUserCmdsResponse) => void
): Promise<DeleteUserCmdsResponse> {
return this.request("DeleteUserCmds", req, cb)
}
/**
* 查询托管设备带外信息
*/
async DescribeHostedDeviceOutBandInfo(
req: DescribeHostedDeviceOutBandInfoRequest,
cb?: (error: string, rep: DescribeHostedDeviceOutBandInfoResponse) => void
): Promise<DescribeHostedDeviceOutBandInfoResponse> {
return this.request("DescribeHostedDeviceOutBandInfo", req, cb)
}
/**
* 为预授权规则绑定标签
*/
async BindPsaTag(
req: BindPsaTagRequest,
cb?: (error: string, rep: BindPsaTagResponse) => void
): Promise<BindPsaTagResponse> {
return this.request("BindPsaTag", req, cb)
}
/**
* 删除自定义镜像<br>
正用于部署或重装中的镜像被删除后,镜像文件将保留一段时间,直到部署或重装结束
*/
async DeleteCustomImages(
req: DeleteCustomImagesRequest,
cb?: (error: string, rep: DeleteCustomImagesResponse) => void
): Promise<DeleteCustomImagesResponse> {
return this.request("DeleteCustomImages", req, cb)
}
/**
* 删除预授权规则
*/
async DeletePsaRegulation(
req: DeletePsaRegulationRequest,
cb?: (error: string, rep: DeletePsaRegulationResponse) => void
): Promise<DeletePsaRegulationResponse> {
return this.request("DeletePsaRegulation", req, cb)
}
/**
* 创建自定义脚本
*/
async CreateUserCmd(
req: CreateUserCmdRequest,
cb?: (error: string, rep: CreateUserCmdResponse) => void
): Promise<CreateUserCmdResponse> {
return this.request("CreateUserCmd", req, cb)
}
/**
* 查询自定义机型部件信息,包括CpuId对应的型号,DiskTypeId对应的磁盘类型
*/
async DescribeHardwareSpecification(
req?: DescribeHardwareSpecificationRequest,
cb?: (error: string, rep: DescribeHardwareSpecificationResponse) => void
): Promise<DescribeHardwareSpecificationResponse> {
return this.request("DescribeHardwareSpecification", req, cb)
}
/**
* 服务器绑定CAM角色
*/
async DetachCamRole(
req: DetachCamRoleRequest,
cb?: (error: string, rep: DetachCamRoleResponse) => void
): Promise<DetachCamRoleResponse> {
return this.request("DetachCamRole", req, cb)
}
/**
* 服务器绑定CAM角色,该角色授权访问黑石物理服务器服务,为黑石物理服务器提供了访问资源的权限,如请求服务器的临时证书
*/
async AttachCamRole(
req: AttachCamRoleRequest,
cb?: (error: string, rep: AttachCamRoleResponse) => void
): Promise<AttachCamRoleResponse> {
return this.request("AttachCamRole", req, cb)
}
/**
* 查询指定机型所支持的操作系统
*/
async DescribeOsInfo(
req: DescribeOsInfoRequest,
cb?: (error: string, rep: DescribeOsInfoResponse) => void
): Promise<DescribeOsInfoResponse> {
return this.request("DescribeOsInfo", req, cb)
}
/**
* 获取异步操作状态的完成状态
*/
async DescribeOperationResult(
req: DescribeOperationResultRequest,
cb?: (error: string, rep: DescribeOperationResultResponse) => void
): Promise<DescribeOperationResultResponse> {
return this.request("DescribeOperationResult", req, cb)
}
/**
* 用于修改自定义镜像名或描述
*/
async ModifyCustomImageAttribute(
req: ModifyCustomImageAttributeRequest,
cb?: (error: string, rep: ModifyCustomImageAttributeResponse) => void
): Promise<ModifyCustomImageAttributeResponse> {
return this.request("ModifyCustomImageAttribute", req, cb)
}
/**
* 查询服务器所在的位置,如机架,上联交换机等信息
*/
async DescribeDevicePosition(
req: DescribeDevicePositionRequest,
cb?: (error: string, rep: DescribeDevicePositionResponse) => void
): Promise<DescribeDevicePositionResponse> {
return this.request("DescribeDevicePosition", req, cb)
}
/**
* 查询地域以及可用区
*/
async DescribeRegions(
req: DescribeRegionsRequest,
cb?: (error: string, rep: DescribeRegionsResponse) => void
): Promise<DescribeRegionsResponse> {
return this.request("DescribeRegions", req, cb)
}
/**
* 获取自定义脚本任务详细信息
*/
async DescribeUserCmdTaskInfo(
req: DescribeUserCmdTaskInfoRequest,
cb?: (error: string, rep: DescribeUserCmdTaskInfoResponse) => void
): Promise<DescribeUserCmdTaskInfoResponse> {
return this.request("DescribeUserCmdTaskInfo", req, cb)
}
/**
* 查询服务器价格信息,支持设备的批量查找,支持标准机型和弹性机型的混合查找
*/
async DescribeDevicePriceInfo(
req: DescribeDevicePriceInfoRequest,
cb?: (error: string, rep: DescribeDevicePriceInfoResponse) => void
): Promise<DescribeDevicePriceInfoResponse> {
return this.request("DescribeDevicePriceInfo", req, cb)
}
/**
* 退回物理机至回收站,支持批量退还不同计费模式的物理机(包括预付费、后付费、预付费转后付费)
*/
async ReturnDevices(
req: ReturnDevicesRequest,
cb?: (error: string, rep: ReturnDevicesResponse) => void
): Promise<ReturnDevicesResponse> {
return this.request("ReturnDevices", req, cb)
}
/**
* 获取维修任务操作日志
*/
async DescribeTaskOperationLog(
req: DescribeTaskOperationLogRequest,
cb?: (error: string, rep: DescribeTaskOperationLogResponse) => void
): Promise<DescribeTaskOperationLogResponse> {
return this.request("DescribeTaskOperationLog", req, cb)
}
/**
* 将设备的预付费模式修改为后付费计费模式,支持批量转换。(前提是客户要加入黑石物理机后付费计费的白名单,申请黑石物理机后付费可以联系腾讯云客服)
*/
async ModifyPayModePre2Post(
req: ModifyPayModePre2PostRequest,
cb?: (error: string, rep: ModifyPayModePre2PostResponse) => void
): Promise<ModifyPayModePre2PostResponse> {
return this.request("ModifyPayModePre2Post", req, cb)
}
/**
* 解除标签与预授权规则的绑定
*/
async UnbindPsaTag(
req: UnbindPsaTagRequest,
cb?: (error: string, rep: UnbindPsaTagResponse) => void
): Promise<UnbindPsaTagResponse> {
return this.request("UnbindPsaTag", req, cb)
}
/**
* 创建黑石竞价实例
*/
async CreateSpotDevice(
req: CreateSpotDeviceRequest,
cb?: (error: string, rep: CreateSpotDeviceResponse) => void
): Promise<CreateSpotDeviceResponse> {
return this.request("CreateSpotDevice", req, cb)
}
/**
* 修改服务器名称
*/
async ModifyDeviceAliases(
req: ModifyDeviceAliasesRequest,
cb?: (error: string, rep: ModifyDeviceAliasesResponse) => void
): Promise<ModifyDeviceAliasesResponse> {
return this.request("ModifyDeviceAliases", req, cb)
}
/**
* 查询设备库存
*/
async DescribeDeviceInventory(
req: DescribeDeviceInventoryRequest,
cb?: (error: string, rep: DescribeDeviceInventoryResponse) => void
): Promise<DescribeDeviceInventoryResponse> {
return this.request("DescribeDeviceInventory", req, cb)
}
/**
* 查询设备操作日志, 如设备重启,重装,设置密码等操作
*/
async DescribeDeviceOperationLog(
req: DescribeDeviceOperationLogRequest,
cb?: (error: string, rep: DescribeDeviceOperationLogResponse) => void
): Promise<DescribeDeviceOperationLogResponse> {
return this.request("DescribeDeviceOperationLog", req, cb)
}
/**
* 获取用户维修任务列表及详细信息<br>
<br>
TaskStatus(任务状态ID)与状态中文名的对应关系如下:<br>
1:未授权<br>
2:处理中<br>
3:待确认<br>
4:未授权-暂不处理<br>
5:已恢复<br>
6:待确认-未恢复<br>
*/
async DescribeTaskInfo(
req: DescribeTaskInfoRequest,
cb?: (error: string, rep: DescribeTaskInfoResponse) => void
): Promise<DescribeTaskInfoResponse> {
return this.request("DescribeTaskInfo", req, cb)
}
/**
* 此接口用于操作维修任务<br>
入参TaskId为维修任务ID<br>
入参Operate表示对维修任务的操作,支持如下取值:<br>
AuthorizeRepair(授权维修)<br>
Ignore(暂不提醒)<br>
ConfirmRecovered(维修完成后,确认故障恢复)<br>
ConfirmUnRecovered(维修完成后,确认故障未恢复,该操作已不推荐用)<br>
NeedRepairAgain(维修完成后,故障未恢复,需要重新维修,推荐用此操作打回)<br>
入参OperateRemark仅在Operate为NeedRepairAgain时有效,表示打回重修原因,建议给出打回的具体原因。<br>
<br>
操作约束(当前任务状态(TaskStatus)->对应可执行的操作):<br>
未授权(1)->授权维修;暂不处理<br>
暂不处理(4)->授权维修<br>
待确认(3)->确认故障恢复;确认故障未恢复;需要重新维修<br>
未恢复(6)->确认故障恢复<br>
<br>
对于Ping不可达故障的任务,还允许:<br>
未授权->确认故障恢复<br>
暂不处理->确认故障恢复<br>
<br>
处理中与已恢复状态的任务不允许进行操作。<br>
<br>
详细信息请访问:https://cloud.tencent.com/document/product/386/18190
*/
async RepairTaskControl(
req: RepairTaskControlRequest,
cb?: (error: string, rep: RepairTaskControlResponse) => void
): Promise<RepairTaskControlResponse> {
return this.request("RepairTaskControl", req, cb)
}
/**
* 查询物理服务器,可以按照实例,业务IP等过滤
*/
async DescribeDevices(
req: DescribeDevicesRequest,
cb?: (error: string, rep: DescribeDevicesResponse) => void
): Promise<DescribeDevicesResponse> {
return this.request("DescribeDevices", req, cb)
}
/**
* 维修任务配置获取
*/
async DescribeRepairTaskConstant(
req?: DescribeRepairTaskConstantRequest,
cb?: (error: string, rep: DescribeRepairTaskConstantResponse) => void
): Promise<DescribeRepairTaskConstantResponse> {
return this.request("DescribeRepairTaskConstant", req, cb)
}
/**
* 设置带外VPN认证用户密码
*/
async SetOutBandVpnAuthPassword(
req: SetOutBandVpnAuthPasswordRequest,
cb?: (error: string, rep: SetOutBandVpnAuthPasswordResponse) => void
): Promise<SetOutBandVpnAuthPasswordResponse> {
return this.request("SetOutBandVpnAuthPassword", req, cb)
}
/**
* 查看自定义镜像列表
*/
async DescribeCustomImages(
req: DescribeCustomImagesRequest,
cb?: (error: string, rep: DescribeCustomImagesResponse) => void
): Promise<DescribeCustomImagesResponse> {
return this.request("DescribeCustomImages", req, cb)
}
/**
* 恢复回收站中的物理机(仅限后付费的物理机)
*/
async RecoverDevices(
req: RecoverDevicesRequest,
cb?: (error: string, rep: RecoverDevicesResponse) => void
): Promise<RecoverDevicesResponse> {
return this.request("RecoverDevices", req, cb)
}
/**
* 获取物理机的分区格式
*/
async DescribeDevicePartition(
req: DescribeDevicePartitionRequest,
cb?: (error: string, rep: DescribeDevicePartitionResponse) => void
): Promise<DescribeDevicePartitionResponse> {
return this.request("DescribeDevicePartition", req, cb)
}
/**
* 关闭服务器
*/
async ShutdownDevices(
req: ShutdownDevicesRequest,
cb?: (error: string, rep: ShutdownDevicesResponse) => void
): Promise<ShutdownDevicesResponse> {
return this.request("ShutdownDevices", req, cb)
}
/**
* 重置服务器密码
*/
async ResetDevicePassword(
req: ResetDevicePasswordRequest,
cb?: (error: string, rep: ResetDevicePasswordResponse) => void
): Promise<ResetDevicePasswordResponse> {
return this.request("ResetDevicePassword", req, cb)
}
/**
* 查询机型支持的RAID方式, 并返回系统盘的分区和逻辑盘的列表
*/
async DescribeDeviceClassPartition(
req: DescribeDeviceClassPartitionRequest,
cb?: (error: string, rep: DescribeDeviceClassPartitionResponse) => void
): Promise<DescribeDeviceClassPartitionResponse> {
return this.request("DescribeDeviceClassPartition", req, cb)
}
/**
* 创建自定义镜像<br>
每个AppId在每个可用区最多保留20个自定义镜像
*/
async CreateCustomImage(
req: CreateCustomImageRequest,
cb?: (error: string, rep: CreateCustomImageResponse) => void
): Promise<CreateCustomImageResponse> {
return this.request("CreateCustomImage", req, cb)
}
} | the_stack |
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { debounceTime } from 'rxjs/operators';
import { FileBrowserComponent } from '../file-browser/file-browser.component';
import { GraphComponent } from '../graph/graph.component';
import { FileBrowserFilter, ModelService, NewModel } from '../services/model.service';
import { SocketService } from '../services/socket.service';
declare var require: any;
var shajs = require('sha.js');
@Component({
selector: 'app-project-form',
templateUrl: './project-form.component.html',
styleUrls: ['./project-form.component.scss', './../error/error.component.scss',]
})
export class ProjectFormComponent implements OnInit {
showGraphSpinner = false;
showSpinner = false;
showGraphButton = false;
showDomain = false;
showExamples = true;
showShapeWarning: boolean;
projectFormGroup: FormGroup;
domains = [];
graph = {};
id: string;
modelList = [];
frameworks = [];
models = [];
model = {
id: '',
framework: '',
model: '',
domain: '',
model_path: '',
yaml: '',
project_name: '',
dataset_path: '',
};
boundaryNodes: {
inputs: 'none' | 'custom' | 'select',
outputs: 'none' | 'custom' | 'select',
};
inputs = [];
outputs = [];
order = {
input: [],
output: []
};
constructor(
private dialog: MatDialog,
private _formBuilder: FormBuilder,
public modelService: ModelService,
public socketService: SocketService,
private router: Router
) { }
ngOnInit(): void {
const dateTime = Date.now();
this.id = shajs('sha384').update(String(dateTime)).digest('hex');
this.boundaryNodes = {
inputs: 'none',
outputs: 'none'
};
this.getDomains();
this.setFormValues();
this.projectFormGroup.get('modelLocation').valueChanges
.pipe(
debounceTime(1000))
.subscribe(response => {
if (this.projectFormGroup.get('modelLocation').value) {
this.showSpinner = true;
this.showGraphButton = false;
this.socketService.getBoundaryNodes(this.getNewModel()).subscribe(
response => { },
error => {
this.modelService.openErrorDialog(error);
}
);
this.modelService.getModelGraph(this.projectFormGroup.get('modelLocation').value)
.subscribe(
graph => {
this.graph = graph;
this.showGraphButton = true;
},
error => {
this.showGraphButton = false;
}
);
}
});
this.socketService.boundaryNodesFinish$
.subscribe(result => {
this.showSpinner = false;
if (result['status'] === 'success') {
if (result['data'] && this.projectFormGroup.get('modelLocation').value && result['data'].request_id === this.id) {
this.projectFormGroup.get('domainFlavour').setValue(result['data']['domain_flavour']);
if (result['data']['domain']?.length) {
this.projectFormGroup.get('modelDomain').setValue(result['data']['domain']);
this.showDomain = false;
} else {
this.projectFormGroup.get('modelDomain').reset();
this.showDomain = true;
}
this.projectFormGroup.get('shape').setValue(result['data']['shape']);
this.showShapeWarning = result['data']['shape'] ? true : false;
this.projectFormGroup.get('framework').setValue(result['data']['framework']);
['inputs', 'outputs'].forEach(param => {
this[param] = result['data'][param];
if (Array.isArray(result['data'][param])) {
this.isFieldRequired('projectFormGroup', 'input', true);
this.isFieldRequired('projectFormGroup', 'output', true);
if (result['data'][param].length === 0) {
this.boundaryNodes[param] = 'custom';
} else if (result['data'][param].length === 1) {
this.boundaryNodes[param] = 'custom';
this.projectFormGroup.get(param.slice(0, -1)).setValue(result['data'][param]);
} else {
this.boundaryNodes[param] = 'select';
if (result['data']['domain'] === 'object_detection' && result['data']['domain_flavour'] === 'ssd') {
if (["detection_bboxes", "detection_scores", "detection_classes"].every((val) => result['data']['outputs'].includes(val))) {
this.projectFormGroup.get('output').setValue(["detection_bboxes", "detection_scores", "detection_classes"]);
}
} else {
const nonCustomParams = result['data'][param].filter(param => param !== 'custom');
if (nonCustomParams.length === 1) {
this.projectFormGroup.get(param.slice(0, -1)).setValue(nonCustomParams);
} else if (nonCustomParams.includes('softmax_tensor')) {
this.projectFormGroup.get(param.slice(0, -1)).setValue(['softmax_tensor']);
}
}
}
} else {
this.boundaryNodes[param] = 'none';
this.isFieldRequired('projectFormGroup', 'input', false);
this.isFieldRequired('projectFormGroup', 'output', false);
}
});
}
} else {
this.modelService.openErrorDialog(result['data']['message']);
}
});
}
getNewModel(): NewModel {
let model: NewModel;
model = {
domain: this.projectFormGroup.get('modelDomain').value,
domain_flavour: this.projectFormGroup.get('domainFlavour').value,
framework: this.projectFormGroup.get('framework').value,
id: this.id,
model_path: this.projectFormGroup.get('modelLocation').value,
};
return model;
}
getDomains() {
this.modelService.getDictionary('domains')
.subscribe(
resp => this.domains = resp['domains'],
error => this.modelService.openErrorDialog(error));
}
setFormValues() {
this.projectFormGroup = this._formBuilder.group({
name: ['Project' + String(this.modelService.projectCount + 1), Validators.required],
framework: ['', Validators.required],
modelLocation: ['', Validators.required],
modelDomain: [''],
domainFlavour: [''],
input: [''],
inputOther: [''],
output: [''],
outputOther: [''],
shape: ['']
});
}
createProject() {
this.showSpinner = true;
let newProject = {
name: this.projectFormGroup.get('name').value,
model: {
path: this.projectFormGroup.get('modelLocation').value,
domain: this.projectFormGroup.get('modelDomain').value,
input_nodes: this.getBoundaryNodes('input'),
output_nodes: this.getBoundaryNodes('output'),
shape: this.projectFormGroup.get('shape').value,
}
};
this.modelService.createProject(newProject)
.subscribe(
response => {
this.showSpinner = false;
this.modelService.projectCreated$.next(true);
this.router.navigate(['/project', response['project_id']], { queryParamsHandling: "merge" });
},
error => {
this.showSpinner = false;
this.modelService.openErrorDialog(error);
});
}
showGraph() {
this.showGraphSpinner = true;
this.showGraphSpinner = false;
this.dialog.open(GraphComponent, {
width: '90%',
height: '90%',
data: {
modelPath: this.projectFormGroup.get('modelLocation').value,
viewSize: [window.innerWidth * 0.9, window.innerHeight * 0.9]
}
});
}
openDialog(fieldName: string, filter: FileBrowserFilter, paramFile?) {
const dialogRef = this.dialog.open(FileBrowserComponent, {
width: '60%',
height: '60%',
data: {
path: this.projectFormGroup.get(fieldName) && this.projectFormGroup.get(fieldName).value ? this.projectFormGroup.get(fieldName).value.split("/").slice(0, -1).join("/") : this.modelService.workspacePath,
filter: filter,
filesToFind: paramFile
}
});
dialogRef.afterClosed().subscribe(response => {
if (response && response.chosenFile) {
this.projectFormGroup.get(fieldName).setValue(response.chosenFile);
}
});
}
boundaryNodesVisible(): boolean {
return (this.boundaryNodes.inputs !== 'none' || this.boundaryNodes.outputs !== 'none') && this.projectFormGroup.get('modelLocation').value && !this.showSpinner;
}
boundaryNodesChanged(value, type: 'input' | 'output') {
if (value === 'custom') {
if (!this.order[type].includes(value)) {
this.projectFormGroup.get(type).setValue([value]);
this.order[type] = [value];
} else {
this.projectFormGroup.get(type).setValue([]);
this.order[type] = [];
}
} else {
if (!this.order[type].includes(value)) {
this.order[type].push(value);
} else {
this.order[type].splice(this.order[type].indexOf(value), 1);
}
}
}
getBoundaryNodes(type: 'input' | 'output') {
if (this.projectFormGroup.get(type + 'Other').value.length) {
return [this.projectFormGroup.get(type + 'Other').value];
}
if (this.order[type].length) {
return this.order[type];
}
if (typeof this.projectFormGroup.get(type).value === 'string') {
if (typeof this.projectFormGroup.get(type).value.includes(',')) {
return this.projectFormGroup.get(type).value;
}
return [this.projectFormGroup.get(type).value];
}
return this.projectFormGroup.get(type).value;
}
isFieldRequired(form: string, field: string, required: boolean) {
if (required) {
this.projectFormGroup.controls[field].setValidators([Validators.required]);
} else {
this.projectFormGroup.controls[field].clearValidators();
}
this.projectFormGroup.controls[field].updateValueAndValidity();
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.