type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
ClassDeclaration
class BinaryWidgetView extends TestWidgetView { render(): void { this._rendered += 1; } _rendered = 0; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
ClassDeclaration
export class DummyManager implements widgets.IWidgetManager { constructor() { this.el = window.document.createElement('div'); } protected loadClass( className: string, moduleName: string, moduleVersion: string ): Promise<any> { if (moduleName === '@jupyter-widgets/base') { if ((widgets as any)[className]) { return Promise.resolve((widgets as any)[className]); } else { return Promise.reject(`Cannot find class ${className}`); } } else if (moduleName === 'test-widgets') { if ((testWidgets as any)[className]) { return Promise.resolve((testWidgets as any)[className]); } else { return Promise.reject(`Cannot find class ${className}`); } } else { return Promise.reject(`Cannot find module ${moduleName}`); } } el: HTMLElement; /** * Creates a promise for a view of a given model * * Make sure the view creation is not out of order with * any state updates. */ create_view( model: widgets.DOMWidgetModel, options?: any ): Promise<widgets.DOMWidgetView>; create_view( model: widgets.WidgetModel, options?: any ): Promise<widgets.WidgetView> { throw new Error('Not implemented in dummy manager'); } /** * callback handlers specific to a view */ callbacks(view?: widgets.WidgetView): widgets.ICallbacks { return {}; } /** * Get a promise for a model by model id. * * #### Notes * If a model is not found, undefined is returned (NOT a promise). However, * the calling code should also deal with the case where a rejected promise * is returned, and should treat that also as a model not found. */ get_model(model_id: string): Promise<widgets.WidgetModel> | undefined { // TODO: Perhaps we should return a Promise.reject if the model is not // found. Right now this isn't a true async function because it doesn't // always return a promise. return this._models[model_id]; } /** * Create a comm and new widget model. * @param options - same options as new_model but comm is not * required and additional options are available. * @param serialized_state - serialized model attributes. */ new_widget( options: widgets.IWidgetOptions, serialized_state: JSONObject = {} ): Promise<widgets.WidgetModel> { return this.new_model(options, serialized_state); } register_model( model_id: string, modelPromise: Promise<widgets.WidgetModel> ): void { this._models[model_id] = modelPromise; modelPromise.then((model) => { model.once('comm:close', () => { delete this._models[model_id]; }); }); } /** * Create and return a promise for a new widget model * * @param options - the options for creating the model. * @param serialized_state - attribute values for the model. * * @example * widget_manager.new_model({ * model_name: 'IntSlider', * model_module: '@jupyter-widgets/controls', * model_module_version: '1.0.0', * model_id: 'u-u-i-d' * }).then((model) => { console.log('Create success!', model); }, * (err) => {console.error(err)}); * */ async new_model( options: widgets.IModelOptions, serialized_state: any = {} ): Promise<widgets.WidgetModel> { let model_id; if (options.model_id) { model_id = options.model_id; } else if (options.comm) { model_id = options.model_id = options.comm.comm_id; } else { throw new Error( 'Neither comm nor model_id provided in options object. At least one must exist.' ); } const modelPromise = this._make_model(options, serialized_state); // this call needs to happen before the first `await`, see note in `set_state`: this.register_model(model_id, modelPromise); return await modelPromise; } async _make_model( options: any, serialized_state: any = {} ): Promise<widgets.WidgetModel> { const model_id = options.model_id; const model_promise = this.loadClass( options.model_name, options.model_module, options.model_module_version ); let ModelType; try { ModelType = await model_promise; } catch (error) { console.error('Could not instantiate widget'); throw error; } if (!ModelType) { throw new Error( `Cannot find model module ${options.model_module}@${options.model_module_version}, ${options.model_name}` ); } const attributes = await ModelType._deserialize_state( serialized_state, this ); const modelOptions = { widget_manager: this, model_id: model_id, comm: options.comm, }; const widget_model = new ModelType(attributes, modelOptions); widget_model.name = options.model_name; widget_model.module = options.model_module; return widget_model; } /** * Resolve a URL relative to the current notebook location. * * The default implementation just returns the original url. */ resolveUrl(url: string): Promise<string> { return Promise.resolve(url); } inline_sanitize(s: string): string { return s; } /** * Dictionary of model ids and model instance promises */ private _models: { [key: string]: Promise<widgets.WidgetModel>; } = Object.create(null); }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
on_open(fn: Function): void { this._on_open = fn; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
on_close(fn: Function): void { this._on_close = fn; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
on_msg(fn: Function): void { this._on_msg = fn; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
_process_msg(msg: any): any { if (this._on_msg) { return this._on_msg(msg); } else { return Promise.resolve(); } }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
open(): string { if (this._on_open) { this._on_open(); } return ''; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
close(): string { if (this._on_close) { this._on_close(); } return ''; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
send(): string { return ''; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
defaults(): Backbone.ObjectHash { return { ...super.defaults(), _model_module: 'test-widgets', _model_name: 'TestWidget', _model_module_version: '1.0.0', _view_module: 'test-widgets', _view_name: 'TestWidgetView', _view_module_version: '1.0.0', _view_count: null as any, }; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
render(): void { this._rendered += 1; super.render(); }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
remove(): void { this._removed += 1; super.remove(); }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
defaults(): Backbone.ObjectHash { return { ...super.defaults(), _model_name: 'BinaryWidget', _view_name: 'BinaryWidgetView', array: new Int8Array(0), }; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
render(): void { this._rendered += 1; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
protected loadClass( className: string, moduleName: string, moduleVersion: string ): Promise<any> { if (moduleName === '@jupyter-widgets/base') { if ((widgets as any)[className]) { return Promise.resolve((widgets as any)[className]); } else { return Promise.reject(`Cannot find class ${className}`); } } else if (moduleName === 'test-widgets') { if ((testWidgets as any)[className]) { return Promise.resolve((testWidgets as any)[className]); } else { return Promise.reject(`Cannot find class ${className}`); } } else { return Promise.reject(`Cannot find module ${moduleName}`); } }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
/** * Creates a promise for a view of a given model * * Make sure the view creation is not out of order with * any state updates. */ create_view( model: widgets.DOMWidgetModel, options?: any ): Promise<widgets.DOMWidgetView>;
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
create_view( model: widgets.WidgetModel, options?: any ): Promise<widgets.WidgetView> { throw new Error('Not implemented in dummy manager'); }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
/** * callback handlers specific to a view */ callbacks(view?: widgets.WidgetView): widgets.ICallbacks { return {}; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
/** * Get a promise for a model by model id. * * #### Notes * If a model is not found, undefined is returned (NOT a promise). However, * the calling code should also deal with the case where a rejected promise * is returned, and should treat that also as a model not found. */ get_model(model_id: string): Promise<widgets.WidgetModel> | undefined { // TODO: Perhaps we should return a Promise.reject if the model is not // found. Right now this isn't a true async function because it doesn't // always return a promise. return this._models[model_id]; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
/** * Create a comm and new widget model. * @param options - same options as new_model but comm is not * required and additional options are available. * @param serialized_state - serialized model attributes. */ new_widget( options: widgets.IWidgetOptions, serialized_state: JSONObject = {} ): Promise<widgets.WidgetModel> { return this.new_model(options, serialized_state); }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
register_model( model_id: string, modelPromise: Promise<widgets.WidgetModel> ): void { this._models[model_id] = modelPromise; modelPromise.then((model) => { model.once('comm:close', () => { delete this._models[model_id]; }); }); }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
/** * Create and return a promise for a new widget model * * @param options - the options for creating the model. * @param serialized_state - attribute values for the model. * * @example * widget_manager.new_model({ * model_name: 'IntSlider', * model_module: '@jupyter-widgets/controls', * model_module_version: '1.0.0', * model_id: 'u-u-i-d' * }).then((model) => { console.log('Create success!', model); }, * (err) => {console.error(err)}); * */ async new_model( options: widgets.IModelOptions, serialized_state: any = {} ): Promise<widgets.WidgetModel> { let model_id; if (options.model_id) { model_id = options.model_id; } else if (options.comm) { model_id = options.model_id = options.comm.comm_id; } else { throw new Error( 'Neither comm nor model_id provided in options object. At least one must exist.' ); } const modelPromise = this._make_model(options, serialized_state); // this call needs to happen before the first `await`, see note in `set_state`: this.register_model(model_id, modelPromise); return await modelPromise; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
async _make_model( options: any, serialized_state: any = {} ): Promise<widgets.WidgetModel> { const model_id = options.model_id; const model_promise = this.loadClass( options.model_name, options.model_module, options.model_module_version ); let ModelType; try { ModelType = await model_promise; } catch (error) { console.error('Could not instantiate widget'); throw error; } if (!ModelType) { throw new Error( `Cannot find model module ${options.model_module}@${options.model_module_version}, ${options.model_name}` ); } const attributes = await ModelType._deserialize_state( serialized_state, this ); const modelOptions = { widget_manager: this, model_id: model_id, comm: options.comm, }; const widget_model = new ModelType(attributes, modelOptions); widget_model.name = options.model_name; widget_model.module = options.model_module; return widget_model; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
/** * Resolve a URL relative to the current notebook location. * * The default implementation just returns the original url. */ resolveUrl(url: string): Promise<string> { return Promise.resolve(url); }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
MethodDeclaration
inline_sanitize(s: string): string { return s; }
KGerring/ipywidgets
packages/base/test/src/dummy-manager.ts
TypeScript
FunctionDeclaration
export function matchRegistrarAccountsWithIndexes ( judgementsWithRegistrarIndexes: SortedJudgements, allRegistrars: Registrar[] ): Judgement[] { return judgementsWithRegistrarIndexes.map(({ judgementName, registrarsIndexes }) => { const findRegistrarByIndex = (index: number) => allRegistrars.find((registrar) => registrar.index === index); return { judgementName, registrars: registrarsIndexes.map((index) => findRegistrarByIndex(index.toNumber())) }; }); }
454076513/apps
packages/react-hooks/src/utils/matchRegistrarAccountsWithIndexes.ts
TypeScript
ArrowFunction
({ judgementName, registrarsIndexes }) => { const findRegistrarByIndex = (index: number) => allRegistrars.find((registrar) => registrar.index === index); return { judgementName, registrars: registrarsIndexes.map((index) => findRegistrarByIndex(index.toNumber())) }; }
454076513/apps
packages/react-hooks/src/utils/matchRegistrarAccountsWithIndexes.ts
TypeScript
ArrowFunction
(index: number) => allRegistrars.find((registrar) => registrar.index === index)
454076513/apps
packages/react-hooks/src/utils/matchRegistrarAccountsWithIndexes.ts
TypeScript
ArrowFunction
(registrar) => registrar.index === index
454076513/apps
packages/react-hooks/src/utils/matchRegistrarAccountsWithIndexes.ts
TypeScript
ArrowFunction
(index) => findRegistrarByIndex(index.toNumber())
454076513/apps
packages/react-hooks/src/utils/matchRegistrarAccountsWithIndexes.ts
TypeScript
ClassDeclaration
@NgModule({ imports: [ CommonModule, RouterModule.forChild(AdminLayoutRoutes), FormsModule, ReactiveFormsModule, MatButtonModule, MatRippleModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatTooltipModule, ], declarations: [ DashboardComponent, UserProfileComponent, TableListComponent, TypographyComponent, IconsComponent, MapsComponent, NotificationsComponent, UpgradeComponent, ] }) export class AdminLayoutModule {}
vscalcione/material-angular-dashboard
src/app/layouts/admin-layout/admin-layout.module.ts
TypeScript
FunctionDeclaration
function isEmpty( op: OperationDefinitionNode | FragmentDefinitionNode, fragments: FragmentMap, ): boolean { return op.selectionSet.selections.every( selection => selection.kind === 'FragmentSpread' && isEmpty(fragments[selection.name.value], fragments), ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
function nullIfDocIsEmpty(doc: DocumentNode) { return isEmpty( getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)), ) ? null : doc; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
function getDirectiveMatcher( directives: (RemoveDirectiveConfig | GetDirectiveConfig)[], ) { return function directiveMatcher(directive: DirectiveNode) { return directives.some( dir => (dir.name && dir.name === directive.name.value) || (dir.test && dir.test(directive)), ); }; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
export function removeDirectivesFromDocument( directives: RemoveDirectiveConfig[], doc: DocumentNode, ): DocumentNode | null { const variablesInUse: Record<string, boolean> = Object.create(null); let variablesToRemove: RemoveArgumentsConfig[] = []; const fragmentSpreadsInUse: Record<string, boolean> = Object.create(null); let fragmentSpreadsToRemove: RemoveFragmentSpreadConfig[] = []; let modifiedDoc = nullIfDocIsEmpty( visit(doc, { Variable: { enter(node, _key, parent) { // Store each variable that's referenced as part of an argument // (excluding operation definition variables), so we know which // variables are being used. If we later want to remove a variable // we'll fist check to see if it's being used, before continuing with // the removal. if ( (parent as VariableDefinitionNode).kind !== 'VariableDefinition' ) { variablesInUse[node.name.value] = true; } }, }, Field: { enter(node) { if (directives && node.directives) { // If `remove` is set to true for a directive, and a directive match // is found for a field, remove the field as well. const shouldRemoveField = directives.some( directive => directive.remove, ); if ( shouldRemoveField && node.directives && node.directives.some(getDirectiveMatcher(directives)) ) { if (node.arguments) { // Store field argument variables so they can be removed // from the operation definition. node.arguments.forEach(arg => { if (arg.value.kind === 'Variable') { variablesToRemove.push({ name: (arg.value as VariableNode).name.value, }); } }); } if (node.selectionSet) { // Store fragment spread names so they can be removed from the // docuemnt. getAllFragmentSpreadsFromSelectionSet(node.selectionSet).forEach( frag => { fragmentSpreadsToRemove.push({ name: frag.name.value, }); }, ); } // Remove the field. return null; } } }, }, FragmentSpread: { enter(node) { // Keep track of referenced fragment spreads. This is used to // determine if top level fragment definitions should be removed. fragmentSpreadsInUse[node.name.value] = true; }, }, Directive: { enter(node) { // If a matching directive is found, remove it. if (getDirectiveMatcher(directives)(node)) { return null; } }, }, }), ); // If we've removed fields with arguments, make sure the associated // variables are also removed from the rest of the document, as long as they // aren't being used elsewhere. if ( modifiedDoc && filterInPlace(variablesToRemove, v => !variablesInUse[v.name]).length ) { modifiedDoc = removeArgumentsFromDocument(variablesToRemove, modifiedDoc); } // If we've removed selection sets with fragment spreads, make sure the // associated fragment definitions are also removed from the rest of the // document, as long as they aren't being used elsewhere. if ( modifiedDoc && filterInPlace(fragmentSpreadsToRemove, fs => !fragmentSpreadsInUse[fs.name]) .length ) { modifiedDoc = removeFragmentSpreadFromDocument( fragmentSpreadsToRemove, modifiedDoc, ); } return modifiedDoc; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
export function addTypenameToDocument(doc: DocumentNode): DocumentNode { return visit(checkDocument(doc), { SelectionSet: { enter(node, _key, parent) { // Don't add __typename to OperationDefinitions. if ( parent && (parent as OperationDefinitionNode).kind === 'OperationDefinition' ) { return; } // No changes if no selections. const { selections } = node; if (!selections) { return; } // If selections already have a __typename, or are part of an // introspection query, do nothing. const skip = selections.some(selection => { return ( selection.kind === 'Field' && ((selection as FieldNode).name.value === '__typename' || (selection as FieldNode).name.value.lastIndexOf('__', 0) === 0) ); }); if (skip) { return; } // Create and return a new SelectionSet with a __typename Field. return { ...node, selections: [...selections, TYPENAME_FIELD], }; }, }, }); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
export function removeConnectionDirectiveFromDocument(doc: DocumentNode) { return removeDirectivesFromDocument( [connectionRemoveConfig], checkDocument(doc), ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
function hasDirectivesInSelectionSet( directives: GetDirectiveConfig[], selectionSet: SelectionSetNode, nestedCheck = true, ): boolean { return ( selectionSet && selectionSet.selections && selectionSet.selections.some(selection => hasDirectivesInSelection(directives, selection, nestedCheck), ) ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
function hasDirectivesInSelection( directives: GetDirectiveConfig[], selection: SelectionNode, nestedCheck = true, ): boolean { if (selection.kind !== 'Field' || !(selection as FieldNode)) { return true; } if (!selection.directives) { return false; } return ( selection.directives.some(getDirectiveMatcher(directives)) || (nestedCheck && hasDirectivesInSelectionSet( directives, selection.selectionSet, nestedCheck, )) ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
export function getDirectivesFromDocument( directives: GetDirectiveConfig[], doc: DocumentNode, ): DocumentNode { checkDocument(doc); let parentPath: string; return nullIfDocIsEmpty( visit(doc, { SelectionSet: { enter(node, _key, _parent, path) { const currentPath = path.join('-'); if ( !parentPath || currentPath === parentPath || !currentPath.startsWith(parentPath) ) { if (node.selections) { const selectionsWithDirectives = node.selections.filter( selection => hasDirectivesInSelection(directives, selection), ); if (hasDirectivesInSelectionSet(directives, node, false)) { parentPath = currentPath; } return { ...node, selections: selectionsWithDirectives, }; } else { return null; } } }, }, }), ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
function getArgumentMatcher(config: RemoveArgumentsConfig[]) { return function argumentMatcher(argument: ArgumentNode) { return config.some( (aConfig: RemoveArgumentsConfig) => argument.value && argument.value.kind === 'Variable' && argument.value.name && (aConfig.name === argument.value.name.value || (aConfig.test && aConfig.test(argument))), ); }; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
export function removeArgumentsFromDocument( config: RemoveArgumentsConfig[], doc: DocumentNode, ): DocumentNode { const argMatcher = getArgumentMatcher(config); return nullIfDocIsEmpty( visit(doc, { OperationDefinition: { enter(node) { return { ...node, // Remove matching top level variables definitions. variableDefinitions: node.variableDefinitions.filter( varDef => !config.some(arg => arg.name === varDef.variable.name.value), ), }; }, }, Field: { enter(node) { // If `remove` is set to true for an argument, and an argument match // is found for a field, remove the field as well. const shouldRemoveField = config.some(argConfig => argConfig.remove); if (shouldRemoveField) { let argMatchCount = 0; node.arguments.forEach(arg => { if (argMatcher(arg)) { argMatchCount += 1; } }); if (argMatchCount === 1) { return null; } } }, }, Argument: { enter(node) { // Remove all matching arguments. if (argMatcher(node)) { return null; } }, }, }), ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
export function removeFragmentSpreadFromDocument( config: RemoveFragmentSpreadConfig[], doc: DocumentNode, ): DocumentNode { function enter( node: FragmentSpreadNode | FragmentDefinitionNode, ): null | void { if (config.some(def => def.name === node.name.value)) { return null; } } return nullIfDocIsEmpty( visit(doc, { FragmentSpread: { enter }, FragmentDefinition: { enter }, }), ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
function enter( node: FragmentSpreadNode | FragmentDefinitionNode, ): null | void { if (config.some(def => def.name === node.name.value)) { return null; } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
function getAllFragmentSpreadsFromSelectionSet( selectionSet: SelectionSetNode, ): FragmentSpreadNode[] { const allFragments: FragmentSpreadNode[] = []; selectionSet.selections.forEach(selection => { if ( (selection.kind === 'Field' || selection.kind === 'InlineFragment') && selection.selectionSet ) { getAllFragmentSpreadsFromSelectionSet(selection.selectionSet).forEach( frag => allFragments.push(frag), ); } else if (selection.kind === 'FragmentSpread') { allFragments.push(selection); } }); return allFragments; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
// If the incoming document is a query, return it as is. Otherwise, build a // new document containing a query operation based on the selection set // of the previous main operation. export function buildQueryFromSelectionSet( document: DocumentNode, ): DocumentNode { const definition = getMainDefinition(document); const definitionOperation = (<OperationDefinitionNode>definition).operation; if (definitionOperation === 'query') { // Already a query, so return the existing document. return document; } // Build a new query using the selection set of the main operation. const modifiedDoc = visit(document, { OperationDefinition: { enter(node) { return { ...node, operation: 'query', }; }, }, }); return modifiedDoc; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
FunctionDeclaration
// Remove fields / selection sets that include an @client directive. export function removeClientSetsFromDocument( document: DocumentNode, ): DocumentNode | null { checkDocument(document); let modifiedDoc = removeDirectivesFromDocument( [ { test: (directive: DirectiveNode) => directive.name.value === 'client', remove: true, }, ], document, ); // After a fragment definition has had its @client related document // sets removed, if the only field it has left is a __typename field, // remove the entire fragment operation to prevent it from being fired // on the server. if (modifiedDoc) { modifiedDoc = visit(modifiedDoc, { FragmentDefinition: { enter(node) { if (node.selectionSet) { const isTypenameOnly = node.selectionSet.selections.every( selection => { return ( selection.kind === 'Field' && (selection as FieldNode).name.value === '__typename' ); }, ); if (isTypenameOnly) { return null; } } }, }, }); } return modifiedDoc; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
selection => selection.kind === 'FragmentSpread' && isEmpty(fragments[selection.name.value], fragments)
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
dir => (dir.name && dir.name === directive.name.value) || (dir.test && dir.test(directive))
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
directive => directive.remove
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
arg => { if (arg.value.kind === 'Variable') { variablesToRemove.push({ name: (arg.value as VariableNode).name.value, }); } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
frag => { fragmentSpreadsToRemove.push({ name: frag.name.value, }); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
v => !variablesInUse[v.name]
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
fs => !fragmentSpreadsInUse[fs.name]
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
selection => { return ( selection.kind === 'Field' && ((selection as FieldNode).name.value === '__typename' || (selection as FieldNode).name.value.lastIndexOf('__', 0) === 0) ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
(directive: DirectiveNode) => { const willRemove = directive.name.value === 'connection'; if (willRemove) { if ( !directive.arguments || !directive.arguments.some(arg => arg.name.value === 'key') ) { console.warn( 'Removing an @connection directive even though it does not have a key. ' + 'You may want to use the key parameter to specify a store key.', ); } } return willRemove; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
arg => arg.name.value === 'key'
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
selection => hasDirectivesInSelection(directives, selection, nestedCheck)
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
selection => hasDirectivesInSelection(directives, selection)
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
(aConfig: RemoveArgumentsConfig) => argument.value && argument.value.kind === 'Variable' && argument.value.name && (aConfig.name === argument.value.name.value || (aConfig.test && aConfig.test(argument)))
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
varDef => !config.some(arg => arg.name === varDef.variable.name.value)
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
arg => arg.name === varDef.variable.name.value
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
argConfig => argConfig.remove
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
arg => { if (argMatcher(arg)) { argMatchCount += 1; } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
def => def.name === node.name.value
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
selection => { if ( (selection.kind === 'Field' || selection.kind === 'InlineFragment') && selection.selectionSet ) { getAllFragmentSpreadsFromSelectionSet(selection.selectionSet).forEach( frag => allFragments.push(frag), ); } else if (selection.kind === 'FragmentSpread') { allFragments.push(selection); } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
frag => allFragments.push(frag)
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
(directive: DirectiveNode) => directive.name.value === 'client'
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
selection => { return ( selection.kind === 'Field' && (selection as FieldNode).name.value === '__typename' ); }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type RemoveNodeConfig<N> = { name?: string; test?: (node: N) => boolean; remove?: boolean; };
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type GetNodeConfig<N> = { name?: string; test?: (node: N) => boolean; };
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type RemoveDirectiveConfig = RemoveNodeConfig<DirectiveNode>;
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type GetDirectiveConfig = GetNodeConfig<DirectiveNode>;
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type RemoveArgumentsConfig = RemoveNodeConfig<ArgumentNode>;
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type GetFragmentSpreadConfig = GetNodeConfig<FragmentSpreadNode>;
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type RemoveFragmentSpreadConfig = RemoveNodeConfig<FragmentSpreadNode>;
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type RemoveFragmentDefinitionConfig = RemoveNodeConfig< FragmentDefinitionNode >;
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
TypeAliasDeclaration
export type RemoveVariableDefinitionConfig = RemoveNodeConfig< VariableDefinitionNode >;
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node, _key, parent) { // Store each variable that's referenced as part of an argument // (excluding operation definition variables), so we know which // variables are being used. If we later want to remove a variable // we'll fist check to see if it's being used, before continuing with // the removal. if ( (parent as VariableDefinitionNode).kind !== 'VariableDefinition' ) { variablesInUse[node.name.value] = true; } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node) { if (directives && node.directives) { // If `remove` is set to true for a directive, and a directive match // is found for a field, remove the field as well. const shouldRemoveField = directives.some( directive => directive.remove, ); if ( shouldRemoveField && node.directives && node.directives.some(getDirectiveMatcher(directives)) ) { if (node.arguments) { // Store field argument variables so they can be removed // from the operation definition. node.arguments.forEach(arg => { if (arg.value.kind === 'Variable') { variablesToRemove.push({ name: (arg.value as VariableNode).name.value, }); } }); } if (node.selectionSet) { // Store fragment spread names so they can be removed from the // docuemnt. getAllFragmentSpreadsFromSelectionSet(node.selectionSet).forEach( frag => { fragmentSpreadsToRemove.push({ name: frag.name.value, }); }, ); } // Remove the field. return null; } } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node) { // Keep track of referenced fragment spreads. This is used to // determine if top level fragment definitions should be removed. fragmentSpreadsInUse[node.name.value] = true; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node) { // If a matching directive is found, remove it. if (getDirectiveMatcher(directives)(node)) { return null; } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node, _key, parent) { // Don't add __typename to OperationDefinitions. if ( parent && (parent as OperationDefinitionNode).kind === 'OperationDefinition' ) { return; } // No changes if no selections. const { selections } = node; if (!selections) { return; } // If selections already have a __typename, or are part of an // introspection query, do nothing. const skip = selections.some(selection => { return ( selection.kind === 'Field' && ((selection as FieldNode).name.value === '__typename' || (selection as FieldNode).name.value.lastIndexOf('__', 0) === 0) ); }); if (skip) { return; } // Create and return a new SelectionSet with a __typename Field. return { ...node, selections: [...selections, TYPENAME_FIELD], }; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node, _key, _parent, path) { const currentPath = path.join('-'); if ( !parentPath || currentPath === parentPath || !currentPath.startsWith(parentPath) ) { if (node.selections) { const selectionsWithDirectives = node.selections.filter( selection => hasDirectivesInSelection(directives, selection), ); if (hasDirectivesInSelectionSet(directives, node, false)) { parentPath = currentPath; } return { ...node, selections: selectionsWithDirectives, }; } else { return null; } } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node) { return { ...node, // Remove matching top level variables definitions. variableDefinitions: node.variableDefinitions.filter( varDef => !config.some(arg => arg.name === varDef.variable.name.value), ), }; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node) { // If `remove` is set to true for an argument, and an argument match // is found for a field, remove the field as well. const shouldRemoveField = config.some(argConfig => argConfig.remove); if (shouldRemoveField) { let argMatchCount = 0; node.arguments.forEach(arg => { if (argMatcher(arg)) { argMatchCount += 1; } }); if (argMatchCount === 1) { return null; } } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node) { // Remove all matching arguments. if (argMatcher(node)) { return null; } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node) { return { ...node, operation: 'query', }; }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
MethodDeclaration
enter(node) { if (node.selectionSet) { const isTypenameOnly = node.selectionSet.selections.every( selection => { return ( selection.kind === 'Field' && (selection as FieldNode).name.value === '__typename' ); }, ); if (isTypenameOnly) { return null; } } }
Baehongmin/gatsby-blog
node_modules/apollo-utilities/src/transform.ts
TypeScript
ArrowFunction
() => this.flush()
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
ArrowFunction
([ackId]) => ackId
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
ArrowFunction
(table: {[index: string]: string[]}, [ackId, deadline]) => { if (!table[deadline!]) { table[deadline!] = []; } table[deadline!].push(ackId); return table; }
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
ArrowFunction
async deadline => { const ackIds = modAckTable[deadline]; const ackDeadlineSeconds = Number(deadline); const reqOpts = {subscription, ackIds, ackDeadlineSeconds}; try { await client.modifyAckDeadline(reqOpts, this._options.callOptions!); } catch (e) { throw new BatchError(e, ackIds, 'modifyAckDeadline'); } }
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
ClassDeclaration
/** * Error class used to signal a batch failure. * * @class * * @param {string} message The error message. * @param {ServiceError} err The grpc service error. */ export class BatchError extends Error implements ServiceError { ackIds: string[]; code?: status; metadata?: Metadata; constructor(err: ServiceError, ackIds: string[], rpc: string) { super( `Failed to "${rpc}" for ${ackIds.length} message(s). Reason: ${ err.message }` ); this.ackIds = ackIds; this.code = err.code; this.metadata = err.metadata; } }
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
ClassDeclaration
/** * Class for buffering ack/modAck requests. * * @private * @class * * @param {Subscriber} sub The subscriber we're queueing requests for. * @param {BatchOptions} options Batching options. */ export abstract class MessageQueue { numPendingRequests: number; protected _onFlush?: DeferredPromise<void>; protected _options!: BatchOptions; protected _requests: QueuedMessages; protected _subscriber: Subscriber; protected _timer?: NodeJS.Timer; protected abstract _sendBatch(batch: QueuedMessages): Promise<void>; constructor(sub: Subscriber, options = {} as BatchOptions) { this.numPendingRequests = 0; this._requests = []; this._subscriber = sub; this.setOptions(options); } /** * Gets the default buffer time in ms. * * @returns {number} * @private */ get maxMilliseconds(): number { return this._options!.maxMilliseconds!; } /** * Adds a message to the queue. * * @param {Message} message The message to add. * @param {number} [deadline] The deadline. * @private */ add({ackId}: Message, deadline?: number): void { const {maxMessages, maxMilliseconds} = this._options; this._requests.push([ackId, deadline]); this.numPendingRequests += 1; if (this._requests.length >= maxMessages!) { this.flush(); } else if (!this._timer) { this._timer = setTimeout(() => this.flush(), maxMilliseconds!); } } /** * Sends a batch of messages. * @private */ async flush(): Promise<void> { if (this._timer) { clearTimeout(this._timer); delete this._timer; } const batch = this._requests; const batchSize = batch.length; const deferred = this._onFlush; this._requests = []; this.numPendingRequests -= batchSize; delete this._onFlush; try { await this._sendBatch(batch); } catch (e) { this._subscriber.emit('error', e); } if (deferred) { deferred.resolve(); } } /** * Returns a promise that resolves after the next flush occurs. * * @returns {Promise} * @private */ onFlush(): Promise<void> { if (!this._onFlush) { this._onFlush = defer(); } return this._onFlush.promise; } /** * Set the batching options. * * @param {BatchOptions} options Batching options. * @private */ setOptions(options: BatchOptions): void { const defaults: BatchOptions = {maxMessages: 3000, maxMilliseconds: 100}; this._options = Object.assign(defaults, options); } }
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
ClassDeclaration
/** * Queues up Acknowledge (ack) requests. * * @private * @class */ export class AckQueue extends MessageQueue { /** * Sends a batch of ack requests. * * @private * * @param {Array.<Array.<string|number>>} batch Array of ackIds and deadlines. * @return {Promise} */ protected async _sendBatch(batch: QueuedMessages): Promise<void> { const client = await this._subscriber.getClient(); const ackIds = batch.map(([ackId]) => ackId); const reqOpts = {subscription: this._subscriber.name, ackIds}; try { await client.acknowledge(reqOpts, this._options.callOptions!); } catch (e) { throw new BatchError(e, ackIds, 'acknowledge'); } } }
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
ClassDeclaration
/** * Queues up ModifyAckDeadline requests and sends them out in batches. * * @private * @class */ export class ModAckQueue extends MessageQueue { /** * Sends a batch of modAck requests. Each deadline requires its own request, * so we have to group all the ackIds by deadline and send multiple requests. * * @private * * @param {Array.<Array.<string|number>>} batch Array of ackIds and deadlines. * @return {Promise} */ protected async _sendBatch(batch: QueuedMessages): Promise<void> { const client = await this._subscriber.getClient(); const subscription = this._subscriber.name; const modAckTable: {[index: string]: string[]} = batch.reduce( (table: {[index: string]: string[]}, [ackId, deadline]) => { if (!table[deadline!]) { table[deadline!] = []; } table[deadline!].push(ackId); return table; }, {} ); const modAckRequests = Object.keys(modAckTable).map(async deadline => { const ackIds = modAckTable[deadline]; const ackDeadlineSeconds = Number(deadline); const reqOpts = {subscription, ackIds, ackDeadlineSeconds}; try { await client.modifyAckDeadline(reqOpts, this._options.callOptions!); } catch (e) { throw new BatchError(e, ackIds, 'modifyAckDeadline'); } }); await Promise.all(modAckRequests); } }
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
InterfaceDeclaration
/** * @typedef {object} BatchOptions * @property {object} [callOptions] Request configuration option, outlined * here: {@link https://googleapis.github.io/gax-nodejs/CallSettings.html}. * @property {number} [maxMessages=3000] Maximum number of messages allowed in * each batch sent. * @property {number} [maxMilliseconds=100] Maximum duration to wait before * sending a batch. Batches can be sent earlier if the maxMessages option * is met before the configured duration has passed. */ export interface BatchOptions { callOptions?: CallOptions; maxMessages?: number; maxMilliseconds?: number; }
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
TypeAliasDeclaration
type QueuedMessages = Array<[string, number?]>;
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript
MethodDeclaration
protected abstract _sendBatch(batch: QueuedMessages): Promise<void>;
ajaaym/nodejs-pubsub
src/message-queues.ts
TypeScript