code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function isTemplateCompatible(generator, apiVersion) {
const generatorVersion = getGeneratorVersion();
if (typeof generator === 'string' && !semver.satisfies(generatorVersion, generator, {includePrerelease: true})) {
throw new Error(`This template is not compatible with the current version of the generator (${generatorVersion}). This template is compatible with the following version range: ${generator}.`);
}
if (typeof apiVersion === 'string' && !supportedParserAPIMajorVersions.includes(apiVersion)) {
throw new Error(`The version specified in apiVersion is not supported by this Generator version. Supported versions are: ${supportedParserAPIMajorVersions.join(', ')}`);
}
}
|
Checks if template is compatible with the version of the generator that is used
@private
@param {String} generator Information about supported generator version that is part of the template configuration
@param {String} generator Information about supported Parser-API version that is part of the template configuration
|
isTemplateCompatible
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
function isRequiredParamProvided(configParams, templateParams) {
const missingParams = Object.keys(configParams || {})
.filter(key => configParams[key].required && !templateParams[key]);
if (missingParams.length) {
throw new Error(`This template requires the following missing params: ${missingParams}.`);
}
}
|
Checks if parameters described in template configuration as required are passed to the generator
@private
@param {Object} configParams Parameters specified in template configuration
@param {Object} templateParams All parameters provided to generator
|
isRequiredParamProvided
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
function getParamSuggestion(wrongParam, configParams) {
const sortInt = (a, b) => {
return a[0] - b[0];
};
return Object.keys(configParams).map(param => [levenshtein(wrongParam, param), param]).sort(sortInt)[0][1];
}
|
Provides a hint for a user about correct parameter name.
@private
@param {Object} wrongParam Incorrectly written parameter
@param {Object} configParams Parameters specified in template configuration
|
getParamSuggestion
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
sortInt = (a, b) => {
return a[0] - b[0];
}
|
Provides a hint for a user about correct parameter name.
@private
@param {Object} wrongParam Incorrectly written parameter
@param {Object} configParams Parameters specified in template configuration
|
sortInt
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
sortInt = (a, b) => {
return a[0] - b[0];
}
|
Provides a hint for a user about correct parameter name.
@private
@param {Object} wrongParam Incorrectly written parameter
@param {Object} configParams Parameters specified in template configuration
|
sortInt
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
function isProvidedParameterSupported(configParams, templateParams) {
const wrongParams = Object.keys(templateParams || {}).filter(key => !configParams?.[key]);
if (!wrongParams.length) return;
if (!configParams) throw new Error('This template doesn\'t have any params.');
let suggestionsString = '';
wrongParams.forEach(wp => {
suggestionsString += `\nDid you mean "${getParamSuggestion(wp,configParams)}" instead of "${wp}"?`;
});
throw new Error(`This template doesn't have the following params: ${wrongParams}.${suggestionsString}`);
}
|
Checks if parameters provided to generator is supported by the template
@private
@param {Object} configParams Parameters specified in template configuration
@param {Object} templateParams All parameters provided to generator
|
isProvidedParameterSupported
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
function isServerProtocolSupported(server, supportedProtocols, paramsServerName) {
if (server && Array.isArray(supportedProtocols) && !supportedProtocols.includes(server.protocol())) {
throw new Error(`Server "${paramsServerName}" uses the ${server.protocol()} protocol but this template only supports the following ones: ${supportedProtocols}.`);
}
}
|
Checks if given AsyncAPI document has servers with protocol that is supported by the template
@private
@param {Object} server Server object from AsyncAPI file
@param {String[]} supportedProtocols Supported protocols specified in template configuration
@param {String} paramsServerName Name of the server specified as a param for the generator
|
isServerProtocolSupported
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
function isProvidedTemplateRendererSupported(templateConfig) {
const supportedRenderers = [undefined, 'react', 'nunjucks'];
if (supportedRenderers.includes(templateConfig.renderer)) {
return;
}
throw new Error(`We do not support '${templateConfig.renderer}' as a renderer for a template. Only 'react' or 'nunjucks' are supported.`);
}
|
Checks if the the provided renderer are supported (no renderer are also supported, defaults to nunjucks)
@param {Object} templateConfig Template configuration.
|
isProvidedTemplateRendererSupported
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
function isServerProvidedInDocument(server, paramsServerName) {
if (typeof paramsServerName === 'string' && !server) throw new Error(`Couldn't find server with name ${paramsServerName}.`);
}
|
Checks if given AsyncAPI document has servers with protocol that is supported by the template
@private
@param {Object} server Server object from AsyncAPI file
@param {String} paramsServerName Name of the server specified as a param for the generator
|
isServerProvidedInDocument
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
function validateConditionalFiles(conditionalFiles) {
if (typeof conditionalFiles === 'object') {
const fileNames = Object.keys(conditionalFiles);
fileNames.forEach(fileName => {
const def = conditionalFiles[fileName];
if (typeof def.subject !== 'string') throw new Error(`Invalid conditional file subject for ${fileName}: ${def.subject}.`);
if (typeof def.validation !== 'object') throw new Error(`Invalid conditional file validation object for ${fileName}: ${def.validation}.`);
conditionalFiles[fileName].validate = ajv.compile(conditionalFiles[fileName].validation);
});
}
}
|
Checks if conditional files are specified properly in the template
@private
@param {Object} conditionalFiles conditions specified in the template config
|
validateConditionalFiles
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
function validateConditionalGeneration(conditionalGeneration) {
if (!conditionalGeneration || typeof conditionalGeneration !== 'object') return;
for (const [fileName, def] of Object.entries(conditionalGeneration)) {
const { subject, parameter, validation } = def;
if (subject && typeof subject !== 'string')
throw new Error(`Invalid 'subject' for ${fileName}: ${subject}`);
if (parameter && typeof parameter !== 'string')
throw new Error(`Invalid 'parameter' for ${fileName}: ${parameter}`);
if (subject && parameter)
throw new Error(`Both 'subject' and 'parameter' cannot be defined for ${fileName}`);
if (typeof validation !== 'object')
throw new Error(`Invalid 'validation' object for ${fileName}: ${validation}`);
def.validate = ajv.compile(validation);
}
}
|
Validates conditionalGeneration settings in the template config.
@private
@param {Object} conditionalGeneration - The conditions specified in the template config.
|
validateConditionalGeneration
|
javascript
|
asyncapi/generator
|
apps/generator/lib/templateConfigValidator.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
|
Apache-2.0
|
constructor(paths, ignorePaths) {
if (Array.isArray(paths)) {
this.paths = paths;
} else {
this.paths = [paths];
}
//Ensure all backwards slashes are replaced with forward slash based on the requirement from chokidar
for (const pathIndex in this.paths) {
const path = this.paths[pathIndex];
this.paths[pathIndex] = path.replace(/[\\]/g, '/');
}
this.fsWait = false;
this.watchers = {};
this.filesChanged = {};
this.ignorePaths = ignorePaths;
}
|
Class to watch for change in certain file(s)
|
constructor
|
javascript
|
asyncapi/generator
|
apps/generator/lib/watcher.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
|
Apache-2.0
|
initiateWatchOnPath(path, changeCallback, errorCallback) {
const watcher = chokidar.watch(path, {ignoreInitial: true, ignored: this.ignorePaths});
watcher.on('all', (eventType, changedPath) => this.fileChanged(path, changedPath, eventType, changeCallback, errorCallback));
this.watchers[path] = watcher;
}
|
Initiates watch on a path.
@param {*} path The path the watcher is listening on.
@param {*} changeCallback Callback to call when changed occur.
@param {*} errorCallback Calback to call when it is no longer possible to watch a file.
|
initiateWatchOnPath
|
javascript
|
asyncapi/generator
|
apps/generator/lib/watcher.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
|
Apache-2.0
|
async watch(changeCallback, errorCallback) {
for (const index in this.paths) {
const path = this.paths[index];
this.initiateWatchOnPath(path, changeCallback, errorCallback);
}
}
|
This method initiate the watch for change in all files
@param {*} callback called when the file(s) change
|
watch
|
javascript
|
asyncapi/generator
|
apps/generator/lib/watcher.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
|
Apache-2.0
|
fileChanged(listenerPath, changedPath, eventType, changeCallback, errorCallback) {
try {
if (fs.existsSync(listenerPath)) {
const newEventType = this.convertEventType(eventType);
this.filesChanged[changedPath] = { eventType: newEventType, path: changedPath};
// Since multiple changes can occur at the same time, lets wait a bit before processing.
if (this.fsWait) return;
this.fsWait = setTimeout(async () => {
await changeCallback(this.filesChanged);
this.filesChanged = {};
this.fsWait = false;
}, 500);
}
} catch (e) {
// File was not, find all files that are missing..
const unknownPaths = this.getAllNonExistingPaths();
this.closeWatchers();
errorCallback(unknownPaths);
}
}
|
Should be called when a file has changed one way or another.
@param {*} listenerPath The path the watcher is listening on.
@param {*} changedPath The file/dir that was changed
@param {*} eventType What kind of change
@param {*} changeCallback Callback to call when changed occur.
@param {*} errorCallback Calback to call when it is no longer possible to watch a file.
|
fileChanged
|
javascript
|
asyncapi/generator
|
apps/generator/lib/watcher.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
|
Apache-2.0
|
convertEventType(currentEventType) {
let newEventType = currentEventType;
//Change the naming of the event type
switch (newEventType) {
case 'unlink':
case 'unlinkDir':
newEventType = 'removed';
break;
case 'addDir':
case 'add':
newEventType = 'added';
break;
case 'change':
newEventType = 'changed';
break;
case 'rename':
newEventType = 'renamed';
break;
default:
newEventType = `unknown (${currentEventType})`;
}
return newEventType;
}
|
Convert the event type to a more usefull one.
@param {*} currentEventType The current event type (from chokidar)
|
convertEventType
|
javascript
|
asyncapi/generator
|
apps/generator/lib/watcher.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
|
Apache-2.0
|
getAllNonExistingPaths() {
const unknownPaths = [];
for (const index in this.paths) {
const path = this.paths[index];
if (!fs.existsSync(path)) {
unknownPaths.push(path);
}
}
return unknownPaths;
}
|
Get all paths which no longer exists
|
getAllNonExistingPaths
|
javascript
|
asyncapi/generator
|
apps/generator/lib/watcher.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
|
Apache-2.0
|
closeWatcher(path) {
// Ensure if called before `watch` to do nothing
if (path !== null) {
const watcher = this.watchers[path];
if (watcher !== null) {
watcher.close();
this.watchers[path] = null;
} else {
//Watcher not found for path
}
}
}
|
Closes an active watcher down.
@param {*} path The path to close the watcher for.
|
closeWatcher
|
javascript
|
asyncapi/generator
|
apps/generator/lib/watcher.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
|
Apache-2.0
|
saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = []) => {
let filePath = outputPath;
// Might be the same as in the `fs` package, but is an active choice for our default file permission for any rendered files.
let permissions = 0o666;
const content = renderedContent.content;
if (content === undefined || typeof content !== 'string') {
throw Error(`Template file not rendered correctly, was rendered as ${content}`);
}
if (renderedContent.metadata !== undefined) {
if (renderedContent.metadata.permissions !== undefined) {
permissions = renderedContent.metadata.permissions;
}
if (renderedContent.metadata.fileName !== undefined) {
const newFileName = renderedContent.metadata.fileName.trim();
const basepath = path.basename(filePath);
filePath = filePath.replace(basepath, newFileName);
}
}
// get the final file name of the file
const finalFileName = path.basename(filePath);
// check whether the filename should be ignored based on user's inputs
const shouldOverwrite = !noOverwriteGlobs.some(globExp => minimatch(finalFileName, globExp));
// Write the file only if it should not be skipped
if (shouldOverwrite) {
await writeFile(filePath, content, {
mode: permissions
});
} else {
await log.debug(logMessage.skipOverwrite(filePath));
}
}
|
Save the single rendered react content based on the meta data available.
@private
@param {TemplateRenderResult} renderedContent the react content rendered
@param {String} outputPath Path to the file being rendered.
|
saveContentToFile
|
javascript
|
asyncapi/generator
|
apps/generator/lib/renderer/react.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/renderer/react.js
|
Apache-2.0
|
saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = []) => {
let filePath = outputPath;
// Might be the same as in the `fs` package, but is an active choice for our default file permission for any rendered files.
let permissions = 0o666;
const content = renderedContent.content;
if (content === undefined || typeof content !== 'string') {
throw Error(`Template file not rendered correctly, was rendered as ${content}`);
}
if (renderedContent.metadata !== undefined) {
if (renderedContent.metadata.permissions !== undefined) {
permissions = renderedContent.metadata.permissions;
}
if (renderedContent.metadata.fileName !== undefined) {
const newFileName = renderedContent.metadata.fileName.trim();
const basepath = path.basename(filePath);
filePath = filePath.replace(basepath, newFileName);
}
}
// get the final file name of the file
const finalFileName = path.basename(filePath);
// check whether the filename should be ignored based on user's inputs
const shouldOverwrite = !noOverwriteGlobs.some(globExp => minimatch(finalFileName, globExp));
// Write the file only if it should not be skipped
if (shouldOverwrite) {
await writeFile(filePath, content, {
mode: permissions
});
} else {
await log.debug(logMessage.skipOverwrite(filePath));
}
}
|
Save the single rendered react content based on the meta data available.
@private
@param {TemplateRenderResult} renderedContent the react content rendered
@param {String} outputPath Path to the file being rendered.
|
saveContentToFile
|
javascript
|
asyncapi/generator
|
apps/generator/lib/renderer/react.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/renderer/react.js
|
Apache-2.0
|
function markdown2html(md) {
return Markdown().render(md || '');
}
|
Turns Markdown into HTML
@md {string} - String with valid Markdown syntax
@returns {string} HTML string
|
markdown2html
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
function getPayloadExamples(msg) {
const examples = msg.examples();
if (Array.isArray(examples) && examples.some(e => e.payload)) {
// Instead of flat or flatmap use this.
const messageExamples = _.flatMap(examples)
.map(e => {
if (!e.payload) return;
return {
name: e.name,
summary: e.summary,
example: e.payload,
};
})
.filter(Boolean);
if (messageExamples.length > 0) {
return messageExamples;
}
}
const payload = msg.payload();
if (payload?.examples()) {
return payload.examples().map(example => ({ example }));
}
}
|
Extracts example from the message payload
@msg {object} - Parser Message function
@returns {object}
|
getPayloadExamples
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
function getHeadersExamples(msg) {
const examples = msg.examples();
if (Array.isArray(examples) && examples.some(e => e.headers)) {
// Instead of flat or flatmap use this.
const messageExamples = _.flatMap(examples)
.map(e => {
if (!e.headers) return;
return {
name: e.name,
summary: e.summary,
example: e.headers,
};
})
.filter(Boolean);
if (messageExamples.length > 0) {
return messageExamples;
}
}
const headers = msg.headers();
if (headers?.examples()) {
return headers.examples().map(example => ({ example }));
}
}
|
Extracts example from the message header
@msg {object} - Parser Message function
@returns {object}
|
getHeadersExamples
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
function generateExample(schema, options) {
return JSON.stringify(OpenAPISampler.sample(schema, options || {}) || '', null, 2);
}
|
Generate string with example from provided schema
@schema {object} - Schema object as JSON and not Schema model map
@options {object} - Options object. Supported options are listed here https://github.com/Redocly/openapi-sampler#usage
@returns {string}
|
generateExample
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
function oneLine(str) {
if (!str) return str;
return str.replace(/\n/g, ' ');
}
|
Turns multiline string into one liner
@str {string} - Any multiline string
@returns {string}
|
oneLine
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
function docline(field, fieldName, scopePropName) {
/* eslint-disable sonarjs/cognitive-complexity */
const getType = (f) => f.type() || 'string';
const getDescription = (f) => f.description() ? ` - ${f.description().replace(/\r?\n|\r/g, '')}` : '';
const getDefault = (f, type) => (f.default() && type === 'string') ? `'${f.default()}'` : f.default();
const getPName = (pName) => pName ? `${pName}.` : '';
const buildLineCore = (type, def, pName, fName) => {
const paramName = `${pName}${fName}`;
const defaultValue = def !== undefined ? `=${def}` : '';
return `* @param {${type}} ${paramName}${defaultValue}`;
};
const buildLine = (f, fName, pName) => {
const type = getType(f);
const def = getDefault(f, type);
const line = buildLineCore(type, def, getPName(pName), fName);
return line + (type === 'object' ? '' : getDescription(f));
};
const buildObjectLines = (f, fName, pName) => {
const properties = f.properties();
const mainLine = buildLine(f, fName, pName);
return `${mainLine }\n${ Object.keys(properties).map((propName) =>
buildLine(properties[propName], propName, `${getPName(pName)}${fName}`)
).join('\n')}`;
};
return getType(field) === 'object'
? buildObjectLines(field, fieldName, scopePropName)
: buildLine(field, fieldName, scopePropName);
}
|
Generate JSDoc from message properties of the header and the payload
@example
docline(
Schema {
_json: {
type: 'integer',
minimum: 0,
maximum: 100,
'x-parser-schema-id': '<anonymous-schema-3>'
}
},
my-app-header,
options.message.headers
)
Returned value will be -> * @param {integer} options.message.headers.my-app-header
@field {object} - Property object
@fieldName {string} - Name of documented property
@scopePropName {string} - Name of param for JSDocs
@returns {string} JSDoc compatible entry
|
docline
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
buildLineCore = (type, def, pName, fName) => {
const paramName = `${pName}${fName}`;
const defaultValue = def !== undefined ? `=${def}` : '';
return `* @param {${type}} ${paramName}${defaultValue}`;
}
|
Generate JSDoc from message properties of the header and the payload
@example
docline(
Schema {
_json: {
type: 'integer',
minimum: 0,
maximum: 100,
'x-parser-schema-id': '<anonymous-schema-3>'
}
},
my-app-header,
options.message.headers
)
Returned value will be -> * @param {integer} options.message.headers.my-app-header
@field {object} - Property object
@fieldName {string} - Name of documented property
@scopePropName {string} - Name of param for JSDocs
@returns {string} JSDoc compatible entry
|
buildLineCore
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
buildLineCore = (type, def, pName, fName) => {
const paramName = `${pName}${fName}`;
const defaultValue = def !== undefined ? `=${def}` : '';
return `* @param {${type}} ${paramName}${defaultValue}`;
}
|
Generate JSDoc from message properties of the header and the payload
@example
docline(
Schema {
_json: {
type: 'integer',
minimum: 0,
maximum: 100,
'x-parser-schema-id': '<anonymous-schema-3>'
}
},
my-app-header,
options.message.headers
)
Returned value will be -> * @param {integer} options.message.headers.my-app-header
@field {object} - Property object
@fieldName {string} - Name of documented property
@scopePropName {string} - Name of param for JSDocs
@returns {string} JSDoc compatible entry
|
buildLineCore
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
buildLine = (f, fName, pName) => {
const type = getType(f);
const def = getDefault(f, type);
const line = buildLineCore(type, def, getPName(pName), fName);
return line + (type === 'object' ? '' : getDescription(f));
}
|
Generate JSDoc from message properties of the header and the payload
@example
docline(
Schema {
_json: {
type: 'integer',
minimum: 0,
maximum: 100,
'x-parser-schema-id': '<anonymous-schema-3>'
}
},
my-app-header,
options.message.headers
)
Returned value will be -> * @param {integer} options.message.headers.my-app-header
@field {object} - Property object
@fieldName {string} - Name of documented property
@scopePropName {string} - Name of param for JSDocs
@returns {string} JSDoc compatible entry
|
buildLine
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
buildLine = (f, fName, pName) => {
const type = getType(f);
const def = getDefault(f, type);
const line = buildLineCore(type, def, getPName(pName), fName);
return line + (type === 'object' ? '' : getDescription(f));
}
|
Generate JSDoc from message properties of the header and the payload
@example
docline(
Schema {
_json: {
type: 'integer',
minimum: 0,
maximum: 100,
'x-parser-schema-id': '<anonymous-schema-3>'
}
},
my-app-header,
options.message.headers
)
Returned value will be -> * @param {integer} options.message.headers.my-app-header
@field {object} - Property object
@fieldName {string} - Name of documented property
@scopePropName {string} - Name of param for JSDocs
@returns {string} JSDoc compatible entry
|
buildLine
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
buildObjectLines = (f, fName, pName) => {
const properties = f.properties();
const mainLine = buildLine(f, fName, pName);
return `${mainLine }\n${ Object.keys(properties).map((propName) =>
buildLine(properties[propName], propName, `${getPName(pName)}${fName}`)
).join('\n')}`;
}
|
Generate JSDoc from message properties of the header and the payload
@example
docline(
Schema {
_json: {
type: 'integer',
minimum: 0,
maximum: 100,
'x-parser-schema-id': '<anonymous-schema-3>'
}
},
my-app-header,
options.message.headers
)
Returned value will be -> * @param {integer} options.message.headers.my-app-header
@field {object} - Property object
@fieldName {string} - Name of documented property
@scopePropName {string} - Name of param for JSDocs
@returns {string} JSDoc compatible entry
|
buildObjectLines
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
buildObjectLines = (f, fName, pName) => {
const properties = f.properties();
const mainLine = buildLine(f, fName, pName);
return `${mainLine }\n${ Object.keys(properties).map((propName) =>
buildLine(properties[propName], propName, `${getPName(pName)}${fName}`)
).join('\n')}`;
}
|
Generate JSDoc from message properties of the header and the payload
@example
docline(
Schema {
_json: {
type: 'integer',
minimum: 0,
maximum: 100,
'x-parser-schema-id': '<anonymous-schema-3>'
}
},
my-app-header,
options.message.headers
)
Returned value will be -> * @param {integer} options.message.headers.my-app-header
@field {object} - Property object
@fieldName {string} - Name of documented property
@scopePropName {string} - Name of param for JSDocs
@returns {string} JSDoc compatible entry
|
buildObjectLines
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
function replaceServerVariablesWithValues(url, serverVariables) {
const getVariablesNamesFromUrl = (inputUrl) => {
const result = [];
let array = [];
const regEx = /{([^}]+)}/g;
while ((array = regEx.exec(inputUrl)) !== null) {
result.push([array[0], array[1]]);
}
return result;
};
const getVariableValue = (object, variable) => {
const keyValue = object[variable]._json;
if (keyValue) return keyValue.default ?? keyValue.enum?.[0];
};
const urlVariables = getVariablesNamesFromUrl(url);
const declaredVariables =
urlVariables.filter(el => serverVariables.hasOwnProperty(el[1]));
if (urlVariables.length !== 0 && declaredVariables.length !== 0) {
let value;
let newUrl = url;
urlVariables.forEach(el => {
value = getVariableValue(serverVariables, el[1]);
if (value) {
newUrl = newUrl.replace(el[0], value);
}
});
return newUrl;
}
return url;
}
|
Helper function to replace server variables in the url with actual values
@url {string} - url string
@serverserverVariables {Object} - Variables model map
@returns {string}
|
replaceServerVariablesWithValues
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
getVariablesNamesFromUrl = (inputUrl) => {
const result = [];
let array = [];
const regEx = /{([^}]+)}/g;
while ((array = regEx.exec(inputUrl)) !== null) {
result.push([array[0], array[1]]);
}
return result;
}
|
Helper function to replace server variables in the url with actual values
@url {string} - url string
@serverserverVariables {Object} - Variables model map
@returns {string}
|
getVariablesNamesFromUrl
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
getVariablesNamesFromUrl = (inputUrl) => {
const result = [];
let array = [];
const regEx = /{([^}]+)}/g;
while ((array = regEx.exec(inputUrl)) !== null) {
result.push([array[0], array[1]]);
}
return result;
}
|
Helper function to replace server variables in the url with actual values
@url {string} - url string
@serverserverVariables {Object} - Variables model map
@returns {string}
|
getVariablesNamesFromUrl
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
getVariableValue = (object, variable) => {
const keyValue = object[variable]._json;
if (keyValue) return keyValue.default ?? keyValue.enum?.[0];
}
|
Helper function to replace server variables in the url with actual values
@url {string} - url string
@serverserverVariables {Object} - Variables model map
@returns {string}
|
getVariableValue
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
getVariableValue = (object, variable) => {
const keyValue = object[variable]._json;
if (keyValue) return keyValue.default ?? keyValue.enum?.[0];
}
|
Helper function to replace server variables in the url with actual values
@url {string} - url string
@serverserverVariables {Object} - Variables model map
@returns {string}
|
getVariableValue
|
javascript
|
asyncapi/generator
|
apps/nunjucks-filters/src/customFilters.js
|
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
|
Apache-2.0
|
async function Models({ asyncapi, language = 'python', format = 'toPascalCase', presets, constraints }) {
// Get the selected generator and file extension, defaulting to Python if unknown
const { generator: GeneratorClass, extension } = generatorConfig[language] || generatorConfig.python;
// Create the generator instance with presets and constraints
const generator = (presets || constraints)
? new GeneratorClass({ ...(presets && { presets }), ...(constraints && { constraints }) })
: new GeneratorClass();
// Get the format helper function, defaulting to toPascalCase if unknown
const formatHelper = formatHelpers[format] || formatHelpers.toPascalCase;
// Generate models asynchronously
const models = await generator.generate(asyncapi);
return models.map(model => {
const modelContent = model.result;
const modelFileName = `${formatHelper(model.modelName)}.${extension}`;
if (modelContent) return <File name={modelFileName}>{modelContent}</File>;
});
}
|
Generates and returns an array of model files based on the AsyncAPI document.
@param {Object} params - The parameters for the function.
@param {AsyncAPIDocumentInterface} params.asyncapi - Parsed AsyncAPI document object.
@param {Language} [params.language='python'] - Target programming language for the generated models.
@param {Format} [params.format='toPascalCase'] - Naming format for generated files.
@param {object} [params.presets={}] - Custom presets for the generator instance.
@param {object} [params.constraints={}] - Custom constraints for the generator instance.
@returns {Array<File>} Array of File components with generated model content.
|
Models
|
javascript
|
asyncapi/generator
|
packages/components/src/components/models.js
|
https://github.com/asyncapi/generator/blob/master/packages/components/src/components/models.js
|
Apache-2.0
|
function getOperationMessages(operation) {
if (!operation) {
throw new Error('Operation object must be provided.');
}
const messages = operation.messages();
if (messages.isEmpty()) {
return null;
}
return messages.all();
}
|
Get messages related to the provided operation.
@param {object} operation - The AsyncAPI operation object.
@throws {Error} If opeartion object is not provided or is invalid.
@returns {null} if there are no messages
@returns messages resulting from operation
|
getOperationMessages
|
javascript
|
asyncapi/generator
|
packages/helpers/src/operations.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/operations.js
|
Apache-2.0
|
function getMessageExamples(message) {
if (!message) {
throw new Error('Message object must be provided.');
}
const examples = message.examples();
if (examples.isEmpty()) {
return null;
}
return examples;
}
|
Get examples related to the provided message.
@param {object} message
@returns {Array} - An array of examples for the provided message.
@returns {null} if there are no examples
@throws {Error} If message object is not provided or is invalid.
|
getMessageExamples
|
javascript
|
asyncapi/generator
|
packages/helpers/src/operations.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/operations.js
|
Apache-2.0
|
getServerUrl = (server) => {
let url = server.host();
//might be that somebody by mistake duplicated protocol info inside the host field
//we need to make sure host do not hold protocol info
if (server.protocol() && !url.includes(`${server.protocol()}://`)) {
url = `${server.protocol()}://${url}`;
}
if (server.hasPathname()) {
url = `${url}${server.pathname()}`;
}
return url;
}
|
Get server URL from AsyncAPI server object.
@param {object} server - The AsyncAPI server object.
return {string} - The server URL.
|
getServerUrl
|
javascript
|
asyncapi/generator
|
packages/helpers/src/servers.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/servers.js
|
Apache-2.0
|
getServerUrl = (server) => {
let url = server.host();
//might be that somebody by mistake duplicated protocol info inside the host field
//we need to make sure host do not hold protocol info
if (server.protocol() && !url.includes(`${server.protocol()}://`)) {
url = `${server.protocol()}://${url}`;
}
if (server.hasPathname()) {
url = `${url}${server.pathname()}`;
}
return url;
}
|
Get server URL from AsyncAPI server object.
@param {object} server - The AsyncAPI server object.
return {string} - The server URL.
|
getServerUrl
|
javascript
|
asyncapi/generator
|
packages/helpers/src/servers.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/servers.js
|
Apache-2.0
|
getServer = (servers, serverName) => {
if (!servers) {
throw new Error('Provided AsyncAPI document doesn\'t contain Servers object.');
}
if (!serverName) {
throw new Error('Server name must be provided.');
}
if (!servers.has(serverName)) {
throw new Error(`Server "${serverName}" not found in AsyncAPI document. Available servers: ${Array.from(servers.keys()).join(', ')}`);
}
return servers.get(serverName);
}
|
Retrieve a server object from the provided AsyncAPI servers collection.
@param {Map<string, object>} servers - A map of server names to AsyncAPI server objects.
@param {string} serverName - The name of the server to retrieve.
@throws {Error} If any of the parameter is missing or invalid.
@returns {object} The AsyncAPI server object corresponding to the given server name.
|
getServer
|
javascript
|
asyncapi/generator
|
packages/helpers/src/servers.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/servers.js
|
Apache-2.0
|
getServer = (servers, serverName) => {
if (!servers) {
throw new Error('Provided AsyncAPI document doesn\'t contain Servers object.');
}
if (!serverName) {
throw new Error('Server name must be provided.');
}
if (!servers.has(serverName)) {
throw new Error(`Server "${serverName}" not found in AsyncAPI document. Available servers: ${Array.from(servers.keys()).join(', ')}`);
}
return servers.get(serverName);
}
|
Retrieve a server object from the provided AsyncAPI servers collection.
@param {Map<string, object>} servers - A map of server names to AsyncAPI server objects.
@param {string} serverName - The name of the server to retrieve.
@throws {Error} If any of the parameter is missing or invalid.
@returns {object} The AsyncAPI server object corresponding to the given server name.
|
getServer
|
javascript
|
asyncapi/generator
|
packages/helpers/src/servers.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/servers.js
|
Apache-2.0
|
getInfo = (asyncapi) => {
if (!asyncapi) {
throw new Error('Make sure you pass AsyncAPI document as an argument.');
}
if (!asyncapi.info) {
throw new Error('Provided AsyncAPI document doesn\'t contain Info object.');
}
const info = asyncapi.info();
if (!info) {
throw new Error('AsyncAPI document info object cannot be empty.');
}
return info;
}
|
Validate and retrieve the AsyncAPI info object from an AsyncAPI document.
Throws an error if the provided AsyncAPI document has no `info` section.
@param {object} asyncapi - The AsyncAPI document object.
@returns {object} The validated info object from the AsyncAPI document.
|
getInfo
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
getInfo = (asyncapi) => {
if (!asyncapi) {
throw new Error('Make sure you pass AsyncAPI document as an argument.');
}
if (!asyncapi.info) {
throw new Error('Provided AsyncAPI document doesn\'t contain Info object.');
}
const info = asyncapi.info();
if (!info) {
throw new Error('AsyncAPI document info object cannot be empty.');
}
return info;
}
|
Validate and retrieve the AsyncAPI info object from an AsyncAPI document.
Throws an error if the provided AsyncAPI document has no `info` section.
@param {object} asyncapi - The AsyncAPI document object.
@returns {object} The validated info object from the AsyncAPI document.
|
getInfo
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
getTitle = asyncapi => {
const info = getInfo(asyncapi);
if (!info.title) {
throw new Error('Provided AsyncAPI document info field doesn\'t contain title.');
}
const title = info.title();
if (title === '') {
throw new Error('AsyncAPI document title cannot be an empty string.');
}
return title;
}
|
Validate and retrieve the AsyncAPI title parameter in the info object.
Throws an error if the provided AsyncAPI info object lacks a `title` parameter.
@param {object} asyncapi - The AsyncAPI document object.
@throws {Error} When `title` is `null` or `undefined` or `empty string` .
@returns {string} The retrieved `title` parameter.
|
getTitle
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
getTitle = asyncapi => {
const info = getInfo(asyncapi);
if (!info.title) {
throw new Error('Provided AsyncAPI document info field doesn\'t contain title.');
}
const title = info.title();
if (title === '') {
throw new Error('AsyncAPI document title cannot be an empty string.');
}
return title;
}
|
Validate and retrieve the AsyncAPI title parameter in the info object.
Throws an error if the provided AsyncAPI info object lacks a `title` parameter.
@param {object} asyncapi - The AsyncAPI document object.
@throws {Error} When `title` is `null` or `undefined` or `empty string` .
@returns {string} The retrieved `title` parameter.
|
getTitle
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
getClientName = (asyncapi, appendClientSuffix, customClientName) => {
if (customClientName) {
return customClientName;
}
const title = getTitle(asyncapi);
const baseName = `${title.replace(/\s+/g, '') // Remove all spaces
.replace(/^./, char => char.toUpperCase())}`; // Make the first letter uppercase
return appendClientSuffix ? `${baseName}Client` : baseName;
}
|
Get client name from AsyncAPI info.title or uses a custom name if provided.
@param {object} info - The AsyncAPI info object.
@param {boolean} appendClientSuffix - Whether to append "Client" to the generated name
@param {string} [customClientName] - Optional custom client name to use instead of generating from title
@returns {string} The formatted client name, either the custom name or a generated name based on the title
|
getClientName
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
getClientName = (asyncapi, appendClientSuffix, customClientName) => {
if (customClientName) {
return customClientName;
}
const title = getTitle(asyncapi);
const baseName = `${title.replace(/\s+/g, '') // Remove all spaces
.replace(/^./, char => char.toUpperCase())}`; // Make the first letter uppercase
return appendClientSuffix ? `${baseName}Client` : baseName;
}
|
Get client name from AsyncAPI info.title or uses a custom name if provided.
@param {object} info - The AsyncAPI info object.
@param {boolean} appendClientSuffix - Whether to append "Client" to the generated name
@param {string} [customClientName] - Optional custom client name to use instead of generating from title
@returns {string} The formatted client name, either the custom name or a generated name based on the title
|
getClientName
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
listFiles = async (dir) => {
const dirElements = await readdir(dir, { withFileTypes: true });
// Filter to only files, map to full paths
return dirElements
.filter(dirE => dirE.isFile())
.map(dirE => dirE.name);
}
|
Get client name from AsyncAPI info.title or uses a custom name if provided.
@param {object} info - The AsyncAPI info object.
@param {boolean} appendClientSuffix - Whether to append "Client" to the generated name
@param {string} [customClientName] - Optional custom client name to use instead of generating from title
@returns {string} The formatted client name, either the custom name or a generated name based on the title
|
listFiles
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
listFiles = async (dir) => {
const dirElements = await readdir(dir, { withFileTypes: true });
// Filter to only files, map to full paths
return dirElements
.filter(dirE => dirE.isFile())
.map(dirE => dirE.name);
}
|
Get client name from AsyncAPI info.title or uses a custom name if provided.
@param {object} info - The AsyncAPI info object.
@param {boolean} appendClientSuffix - Whether to append "Client" to the generated name
@param {string} [customClientName] - Optional custom client name to use instead of generating from title
@returns {string} The formatted client name, either the custom name or a generated name based on the title
|
listFiles
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
toSnakeCase = (inputStr) => {
return inputStr
.replace(/\W+/g, ' ')
.split(/ |\B(?=[A-Z])/)
.map((word) => word.toLowerCase())
.join('_');
}
|
Convert a camelCase or PascalCase string to snake_case.
If the string is already in snake_case, it will be returned unchanged.
@param {string} camelStr - The string to convert to snake_case
@returns {string} The converted snake_case string
|
toSnakeCase
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
toSnakeCase = (inputStr) => {
return inputStr
.replace(/\W+/g, ' ')
.split(/ |\B(?=[A-Z])/)
.map((word) => word.toLowerCase())
.join('_');
}
|
Convert a camelCase or PascalCase string to snake_case.
If the string is already in snake_case, it will be returned unchanged.
@param {string} camelStr - The string to convert to snake_case
@returns {string} The converted snake_case string
|
toSnakeCase
|
javascript
|
asyncapi/generator
|
packages/helpers/src/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
|
Apache-2.0
|
async function waitForTestSuccess(url) {
while (true) {
try {
const response = await fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
if (!response.ok) {
console.error(`Request failed with status: ${response.status}`);
break;
}
const data = await response.json();
if (data.success) {
return true;
}
} catch (err) {
break;
}
await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds
}
return false;
}
|
Polls the Microcks API every 2 seconds until a test with the given ID reports success.
@param {string} url - link to endpoint providing info on particular test
@returns {Promise<boolean>} Resolves with `true` when the test is marked as successful.
|
waitForTestSuccess
|
javascript
|
asyncapi/generator
|
packages/templates/clients/websocket/test/javascript/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/templates/clients/websocket/test/javascript/utils.js
|
Apache-2.0
|
async function waitForMessage(a, expectedMessage, timeout = 3000, interval = 10) {
const start = Date.now();
while (Date.now() - start < timeout) {
if (a.some(message => message.includes(expectedMessage))) {
return;
}
await delay(interval);
}
throw new Error(`Expected message "${expectedMessage}" not found within timeout`);
}
|
Wait for a specific message to appear in the spy's log calls.
@param {array} a - array with messages
@param {string} expectedMessage - The message to look for in logs.
@param {number} timeout - Maximum time (in ms) to wait. Default is 3000ms.
@param {number} interval - How long to wait (in ms) until next check. Default is 10ms.
@returns {Promise<void>} Resolves if the message is found, otherwise rejects.
|
waitForMessage
|
javascript
|
asyncapi/generator
|
packages/templates/clients/websocket/test/javascript/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/templates/clients/websocket/test/javascript/utils.js
|
Apache-2.0
|
async function delay(time = 1000) {
return new Promise(resolve => setTimeout(resolve, time));
}
|
Delay execution by a specified time.
@param {number} time - Delay duration in milliseconds. Default is 1000ms.
@returns {Promise<void>} Resolves after the specified delay.
|
delay
|
javascript
|
asyncapi/generator
|
packages/templates/clients/websocket/test/javascript/utils.js
|
https://github.com/asyncapi/generator/blob/master/packages/templates/clients/websocket/test/javascript/utils.js
|
Apache-2.0
|
function validate(extension, name) {
'use strict';
var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
ret = {
valid: true,
error: ''
};
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var i = 0; i < extension.length; ++i) {
var baseMsg = errMsg + ' sub-extension ' + i + ': ',
ext = extension[i];
if (typeof ext !== 'object') {
ret.valid = false;
ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
return ret;
}
if (!showdown.helper.isString(ext.type)) {
ret.valid = false;
ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
return ret;
}
var type = ext.type = ext.type.toLowerCase();
// normalize extension type
if (type === 'language') {
type = ext.type = 'lang';
}
if (type === 'html') {
type = ext.type = 'output';
}
if (type !== 'lang' && type !== 'output' && type !== 'listener') {
ret.valid = false;
ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang/language", "output/html" or "listener"';
return ret;
}
if (type === 'listener') {
if (showdown.helper.isUndefined(ext.listeners)) {
ret.valid = false;
ret.error = baseMsg + '. Extensions of type "listener" must have a property called "listeners"';
return ret;
}
} else {
if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
ret.valid = false;
ret.error = baseMsg + type + ' extensions must define either a "regex" property or a "filter" method';
return ret;
}
}
if (ext.listeners) {
if (typeof ext.listeners !== 'object') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an object but ' + typeof ext.listeners + ' given';
return ret;
}
for (var ln in ext.listeners) {
if (ext.listeners.hasOwnProperty(ln)) {
if (typeof ext.listeners[ln] !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an hash of [event name]: [callback]. listeners.' + ln +
' must be a function but ' + typeof ext.listeners[ln] + ' given';
return ret;
}
}
}
}
if (ext.filter) {
if (typeof ext.filter !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
return ret;
}
} else if (ext.regex) {
if (showdown.helper.isString(ext.regex)) {
ext.regex = new RegExp(ext.regex, 'g');
}
if (!ext.regex instanceof RegExp) {
ret.valid = false;
ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';
return ret;
}
if (showdown.helper.isUndefined(ext.replace)) {
ret.valid = false;
ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
return ret;
}
}
}
return ret;
}
|
Validate extension
@param {array} extension
@param {string} name
@returns {{valid: boolean, error: string}}
|
validate
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function escapeCharactersCallback(wholeMatch, m1) {
'use strict';
var charCodeToEscape = m1.charCodeAt(0);
return '~E' + charCodeToEscape + 'E';
}
|
Standardidize extension name
@static
@param {string} s extension name
@returns {string}
|
escapeCharactersCallback
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
rgxFindMatchPos = function (str, left, right, flags) {
'use strict';
var f = flags || '',
g = f.indexOf('g') > -1,
x = new RegExp(left + '|' + right, 'g' + f.replace(/g/g, '')),
l = new RegExp(left, f.replace(/g/g, '')),
pos = [],
t, s, m, start, end;
do {
t = 0;
while ((m = x.exec(str))) {
if (l.test(m[0])) {
if (!(t++)) {
s = x.lastIndex;
start = s - m[0].length;
}
} else if (t) {
if (!--t) {
end = m.index + m[0].length;
var obj = {
left: {start: start, end: s},
match: {start: s, end: m.index},
right: {start: m.index, end: end},
wholeMatch: {start: start, end: end}
};
pos.push(obj);
if (!g) {
return pos;
}
}
}
}
} while (t && (x.lastIndex = s));
return pos;
}
|
Escape characters in a string
@static
@param {string} text
@param {string} charsToEscape
@param {boolean} afterBackslash
@returns {XML|string|void|*}
|
rgxFindMatchPos
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function _parseExtension(ext, name) {
name = name || null;
// If it's a string, the extension was previously loaded
if (showdown.helper.isString(ext)) {
ext = showdown.helper.stdExtName(ext);
name = ext;
// LEGACY_SUPPORT CODE
if (showdown.extensions[ext]) {
console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
'Please inform the developer that the extension should be updated!');
legacyExtensionLoading(showdown.extensions[ext], ext);
return;
// END LEGACY SUPPORT CODE
} else if (!showdown.helper.isUndefined(extensions[ext])) {
ext = extensions[ext];
} else {
throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
}
}
if (typeof ext === 'function') {
ext = ext();
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExt = validate(ext, name);
if (!validExt.valid) {
throw Error(validExt.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
}
if (ext[i].hasOwnProperty(listeners)) {
for (var ln in ext[i].listeners) {
if (ext[i].listeners.hasOwnProperty(ln)) {
listen(ln, ext[i].listeners[ln]);
}
}
}
}
}
|
Parse extension
@param {*} ext
@param {string} [name='']
@private
|
_parseExtension
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function listen(name, callback) {
if (!showdown.helper.isString(name)) {
throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
}
if (typeof callback !== 'function') {
throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
}
if (!listeners.hasOwnProperty(name)) {
listeners[name] = [];
}
listeners[name].push(callback);
}
|
Listen to an event
@param {string} name
@param {function} callback
|
listen
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function rTrimInputText(text) {
var rsp = text.match(/^\s*/)[0].length,
rgx = new RegExp('^\\s{0,' + rsp + '}', 'gm');
return text.replace(rgx, '');
}
|
Listen to an event
@param {string} name
@param {function} callback
|
rTrimInputText
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
writeAnchorTag = function (wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
if (showdown.helper.isUndefined(m7)) {
m7 = '';
}
wholeMatch = m1;
var linkText = m2,
linkId = m3.toLowerCase(),
url = m4,
title = m7;
if (!url) {
if (!linkId) {
// lower-case and turn embedded newlines into spaces
linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
url = globals.gUrls[linkId];
if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
title = globals.gTitles[linkId];
}
} else {
if (wholeMatch.search(/\(\s*\)$/m) > -1) {
// Special case for explicit empty url
url = '';
} else {
return wholeMatch;
}
}
}
url = showdown.helper.escapeCharacters(url, '*_', false);
var result = '<a href="' + url + '"';
if (title !== '' && title !== null) {
title = title.replace(/"/g, '"');
title = showdown.helper.escapeCharacters(title, '*_', false);
result += ' title="' + title + '"';
}
result += '>' + linkText + '</a>';
return result;
}
|
Turn Markdown link shortcuts into XHTML <a> tags.
|
writeAnchorTag
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function replaceLink(wm, link) {
var lnkTxt = link;
if (/^www\./i.test(link)) {
link = link.replace(/^www\./i, 'http://www.');
}
return '<a href="' + link + '">' + lnkTxt + '</a>';
}
|
Turn Markdown link shortcuts into XHTML <a> tags.
|
replaceLink
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function replaceMail(wholeMatch, m1) {
var unescapedStr = showdown.subParser('unescapeSpecialChars')(m1);
return showdown.subParser('encodeEmailAddress')(unescapedStr);
}
|
Turn Markdown link shortcuts into XHTML <a> tags.
|
replaceMail
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
repFunc = function (wholeMatch, match, left, right) {
var txt = wholeMatch;
// check if this html element is marked as markdown
// if so, it's contents should be parsed as markdown
if (left.search(/\bmarkdown\b/) !== -1) {
txt = left + globals.converter.makeHtml(match) + right;
}
return '\n\n~K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
}
|
Handle github codeblocks prior to running HashHTML so that
HTML contained within the codeblock gets escaped properly
Example:
```ruby
def hello_world(x)
puts "Hello, #{x}"
end
```
|
repFunc
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
repFunc = function (wholeMatch, match, left, right) {
// encode html entities
var codeblock = left + showdown.subParser('encodeCode')(match) + right;
return '\n\n~G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
}
|
Hash span elements that should not be parsed as markdown
|
repFunc
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function headerId(m) {
var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase();
if (globals.hashLinkCounts[escapedId]) {
title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++);
} else {
title = escapedId;
globals.hashLinkCounts[escapedId] = 1;
}
// Prefix id to prevent causing inadvertent pre-existing style matches.
if (prefixHeader === true) {
prefixHeader = 'section';
}
if (showdown.helper.isString(prefixHeader)) {
return prefixHeader + title;
}
return title;
}
|
Hash span elements that should not be parsed as markdown
|
headerId
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
var gUrls = globals.gUrls,
gTitles = globals.gTitles,
gDims = globals.gDimensions;
linkId = linkId.toLowerCase();
if (!title) {
title = '';
}
if (url === '' || url === null) {
if (linkId === '' || linkId === null) {
// lower-case and turn embedded newlines into spaces
linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(gUrls[linkId])) {
url = gUrls[linkId];
if (!showdown.helper.isUndefined(gTitles[linkId])) {
title = gTitles[linkId];
}
if (!showdown.helper.isUndefined(gDims[linkId])) {
width = gDims[linkId].width;
height = gDims[linkId].height;
}
} else {
return wholeMatch;
}
}
altText = altText.replace(/"/g, '"');
altText = showdown.helper.escapeCharacters(altText, '*_', false);
url = showdown.helper.escapeCharacters(url, '*_', false);
var result = '<img src="' + url + '" alt="' + altText + '"';
if (title) {
title = title.replace(/"/g, '"');
title = showdown.helper.escapeCharacters(title, '*_', false);
result += ' title="' + title + '"';
}
if (width && height) {
width = (width === '*') ? 'auto' : width;
height = (height === '*') ? 'auto' : height;
result += ' width="' + width + '"';
result += ' height="' + height + '"';
}
result += ' />';
return result;
}
|
Turn Markdown image shortcuts into <img> tags.
|
writeImageTag
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function processListItems (listStr, trimTrailing) {
// The $g_list_level global keeps track of when we're inside a list.
// Each time we enter a list, we increment it; when we leave a list,
// we decrement. If it's zero, we're not in a list anymore.
//
// We do this because when we're not inside a list, we want to treat
// something like this:
//
// I recommend upgrading to version
// 8. Oops, now this line is treated
// as a sub-list.
//
// As a single paragraph, despite the fact that the second line starts
// with a digit-period-space sequence.
//
// Whereas when we're inside a list (or sub-list), that line will be
// treated as the start of a sub-list. What a kludge, huh? This is
// an aspect of Markdown's syntax that's hard to parse perfectly
// without resorting to mind-reading. Perhaps the solution is to
// change the syntax rules such that sub-lists must start with a
// starting cardinal number; e.g. "1." or "a.".
globals.gListLevel++;
// trim trailing blank lines:
listStr = listStr.replace(/\n{2,}$/, '\n');
// attacklab: add sentinel to emulate \z
listStr += '~0';
var rgx = /(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm,
isParagraphed = (/\n[ \t]*\n(?!~0)/.test(listStr));
listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
checked = (checked && checked.trim() !== '');
var item = showdown.subParser('outdent')(m4, options, globals),
bulletStyle = '';
// Support for github tasklists
if (taskbtn && options.tasklists) {
bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
item = item.replace(/^[ \t]*\[(x|X| )?]/m, function () {
var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
if (checked) {
otp += ' checked';
}
otp += '>';
return otp;
});
}
// m1 - Leading line or
// Has a double return (multi paragraph) or
// Has sublist
if (m1 || (item.search(/\n{2,}/) > -1)) {
item = showdown.subParser('githubCodeBlocks')(item, options, globals);
item = showdown.subParser('blockGamut')(item, options, globals);
} else {
// Recursion for sub-lists:
item = showdown.subParser('lists')(item, options, globals);
item = item.replace(/\n$/, ''); // chomp(item)
if (isParagraphed) {
item = showdown.subParser('paragraphs')(item, options, globals);
} else {
item = showdown.subParser('spanGamut')(item, options, globals);
}
}
item = '\n<li' + bulletStyle + '>' + item + '</li>\n';
return item;
});
// attacklab: strip sentinel
listStr = listStr.replace(/~0/g, '');
globals.gListLevel--;
if (trimTrailing) {
listStr = listStr.replace(/\s+$/, '');
}
return listStr;
}
|
Process the contents of a single ordered or unordered list, splitting it
into individual list items.
@param {string} listStr
@param {boolean} trimTrailing
@returns {string}
|
processListItems
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function parseConsecutiveLists(list, listType, trimTrailing) {
// check if we caught 2 or more consecutive lists by mistake
// we use the counterRgx, meaning if listType is UL we look for UL and vice versa
var counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm,
subLists = [],
result = '';
if (list.search(counterRxg) !== -1) {
(function parseCL(txt) {
var pos = txt.search(counterRxg);
if (pos !== -1) {
// slice
result += '\n\n<' + listType + '>' + processListItems(txt.slice(0, pos), !!trimTrailing) + '</' + listType + '>\n\n';
// invert counterType and listType
listType = (listType === 'ul') ? 'ol' : 'ul';
counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm;
//recurse
parseCL(txt.slice(pos));
} else {
result += '\n\n<' + listType + '>' + processListItems(txt, !!trimTrailing) + '</' + listType + '>\n\n';
}
})(list);
for (var i = 0; i < subLists.length; ++i) {
}
} else {
result = '\n\n<' + listType + '>' + processListItems(list, !!trimTrailing) + '</' + listType + '>\n\n';
}
return result;
}
|
Check and parse consecutive lists (better fix for issue #142)
@param {string} list
@param {string} listType
@param {boolean} trimTrailing
@returns {string}
|
parseConsecutiveLists
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function parseStyles(sLine) {
if (/^:[ \t]*--*$/.test(sLine)) {
return ' style="text-align:left;"';
} else if (/^--*[ \t]*:[ \t]*$/.test(sLine)) {
return ' style="text-align:right;"';
} else if (/^:[ \t]*--*[ \t]*:$/.test(sLine)) {
return ' style="text-align:center;"';
} else {
return '';
}
}
|
Strips link definitions from text, stores the URLs and titles in
hash references.
Link defs are in the form: ^[id]: url "optional title"
^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
[ \t]*
\n? // maybe *one* newline
[ \t]*
<?(\S+?)>? // url = $2
[ \t]*
\n? // maybe one newline
[ \t]*
(?:
(\n*) // any lines skipped = $3 attacklab: lookbehind removed
["(]
(.+?) // title = $4
[")]
[ \t]*
)? // title is optional
(?:\n+|$)
/gm,
function(){...});
|
parseStyles
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function parseHeaders(header, style) {
var id = '';
header = header.trim();
if (options.tableHeaderId) {
id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
}
header = showdown.subParser('spanGamut')(header, options, globals);
return '<th' + id + style + '>' + header + '</th>\n';
}
|
Strips link definitions from text, stores the URLs and titles in
hash references.
Link defs are in the form: ^[id]: url "optional title"
^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
[ \t]*
\n? // maybe *one* newline
[ \t]*
<?(\S+?)>? // url = $2
[ \t]*
\n? // maybe one newline
[ \t]*
(?:
(\n*) // any lines skipped = $3 attacklab: lookbehind removed
["(]
(.+?) // title = $4
[")]
[ \t]*
)? // title is optional
(?:\n+|$)
/gm,
function(){...});
|
parseHeaders
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function parseCells(cell, style) {
var subText = showdown.subParser('spanGamut')(cell, options, globals);
return '<td' + style + '>' + subText + '</td>\n';
}
|
Strips link definitions from text, stores the URLs and titles in
hash references.
Link defs are in the form: ^[id]: url "optional title"
^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
[ \t]*
\n? // maybe *one* newline
[ \t]*
<?(\S+?)>? // url = $2
[ \t]*
\n? // maybe one newline
[ \t]*
(?:
(\n*) // any lines skipped = $3 attacklab: lookbehind removed
["(]
(.+?) // title = $4
[")]
[ \t]*
)? // title is optional
(?:\n+|$)
/gm,
function(){...});
|
parseCells
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
function buildTable(headers, cells) {
var tb = '<table>\n<thead>\n<tr>\n',
tblLgn = headers.length;
for (var i = 0; i < tblLgn; ++i) {
tb += headers[i];
}
tb += '</tr>\n</thead>\n<tbody>\n';
for (i = 0; i < cells.length; ++i) {
tb += '<tr>\n';
for (var ii = 0; ii < tblLgn; ++ii) {
tb += cells[i][ii];
}
tb += '</tr>\n';
}
tb += '</tbody>\n</table>\n';
return tb;
}
|
Strips link definitions from text, stores the URLs and titles in
hash references.
Link defs are in the form: ^[id]: url "optional title"
^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1
[ \t]*
\n? // maybe *one* newline
[ \t]*
<?(\S+?)>? // url = $2
[ \t]*
\n? // maybe one newline
[ \t]*
(?:
(\n*) // any lines skipped = $3 attacklab: lookbehind removed
["(]
(.+?) // title = $4
[")]
[ \t]*
)? // title is optional
(?:\n+|$)
/gm,
function(){...});
|
buildTable
|
javascript
|
iamdarcy/hioshop-miniprogram
|
lib/wxParse/showdown.js
|
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
|
MIT
|
render() {
return Children.only(this.props.children)
}
|
This is a utility wrapper component that will allow our higher order
component to get a ref handle on our wrapped components html.
@see https://gist.github.com/jimfb/32b587ee6177665fb4cf
|
render
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
function Placeholder({ className, style }) {
// Lets create the props for the temp element.
const phProps = {}
// We will use any provided className/style or else make the temp
// container take the full available space.
if (!className && !style) {
phProps.style = { width: '100%', height: '100%' }
} else {
if (className) {
phProps.className = className
}
if (style) {
phProps.style = style
}
}
return <div {...phProps} />
}
|
This is a utility wrapper component that will allow our higher order
component to get a ref handle on our wrapped components html.
@see https://gist.github.com/jimfb/32b587ee6177665fb4cf
|
Placeholder
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
renderWrapper = (WrappedComponent) => {
function SizeMeRenderer(props) {
const {
explicitRef,
className,
style,
size,
disablePlaceholder,
onSize,
...restProps
} = props
const noSizeData =
size == null || (size.width == null && size.height == null)
const renderPlaceholder = noSizeData && !disablePlaceholder
const renderProps = {
className,
style,
}
if (size != null) {
renderProps.size = size
}
const toRender = renderPlaceholder ? (
<Placeholder className={className} style={style} />
) : (
<WrappedComponent {...renderProps} {...restProps} />
)
return <ReferenceWrapper ref={explicitRef}>{toRender}</ReferenceWrapper>
}
SizeMeRenderer.displayName = `SizeMeRenderer(${getDisplayName(
WrappedComponent,
)})`
return SizeMeRenderer
}
|
As we need to maintain a ref on the root node that is rendered within our
SizeMe component we need to wrap our entire render in a sub component.
Without this, we lose the DOM ref after the placeholder is removed from
the render and the actual component is rendered.
It took me forever to figure this out, so tread extra careful on this one!
|
renderWrapper
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
renderWrapper = (WrappedComponent) => {
function SizeMeRenderer(props) {
const {
explicitRef,
className,
style,
size,
disablePlaceholder,
onSize,
...restProps
} = props
const noSizeData =
size == null || (size.width == null && size.height == null)
const renderPlaceholder = noSizeData && !disablePlaceholder
const renderProps = {
className,
style,
}
if (size != null) {
renderProps.size = size
}
const toRender = renderPlaceholder ? (
<Placeholder className={className} style={style} />
) : (
<WrappedComponent {...renderProps} {...restProps} />
)
return <ReferenceWrapper ref={explicitRef}>{toRender}</ReferenceWrapper>
}
SizeMeRenderer.displayName = `SizeMeRenderer(${getDisplayName(
WrappedComponent,
)})`
return SizeMeRenderer
}
|
As we need to maintain a ref on the root node that is rendered within our
SizeMe component we need to wrap our entire render in a sub component.
Without this, we lose the DOM ref after the placeholder is removed from
the render and the actual component is rendered.
It took me forever to figure this out, so tread extra careful on this one!
|
renderWrapper
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
function SizeMeRenderer(props) {
const {
explicitRef,
className,
style,
size,
disablePlaceholder,
onSize,
...restProps
} = props
const noSizeData =
size == null || (size.width == null && size.height == null)
const renderPlaceholder = noSizeData && !disablePlaceholder
const renderProps = {
className,
style,
}
if (size != null) {
renderProps.size = size
}
const toRender = renderPlaceholder ? (
<Placeholder className={className} style={style} />
) : (
<WrappedComponent {...renderProps} {...restProps} />
)
return <ReferenceWrapper ref={explicitRef}>{toRender}</ReferenceWrapper>
}
|
As we need to maintain a ref on the root node that is rendered within our
SizeMe component we need to wrap our entire render in a sub component.
Without this, we lose the DOM ref after the placeholder is removed from
the render and the actual component is rendered.
It took me forever to figure this out, so tread extra careful on this one!
|
SizeMeRenderer
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
componentDidMount() {
this.detector = resizeDetector(resizeDetectorStrategy)
this.determineStrategy(this.props)
this.handleDOMNode()
}
|
:: config -> Component -> WrappedComponent
Higher order component that allows the wrapped component to become aware
of it's size, by receiving it as an object within it's props.
@param monitorWidth
Default true, whether changes in the element's width should be monitored,
causing a size property to be broadcast.
@param monitorHeight
Default false, whether changes in the element's height should be monitored,
causing a size property to be broadcast.
@return The wrapped component.
|
componentDidMount
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
componentDidUpdate() {
this.determineStrategy(this.props)
this.handleDOMNode()
}
|
:: config -> Component -> WrappedComponent
Higher order component that allows the wrapped component to become aware
of it's size, by receiving it as an object within it's props.
@param monitorWidth
Default true, whether changes in the element's width should be monitored,
causing a size property to be broadcast.
@param monitorHeight
Default false, whether changes in the element's height should be monitored,
causing a size property to be broadcast.
@return The wrapped component.
|
componentDidUpdate
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
componentWillUnmount() {
// Change our size checker to a noop just in case we have some
// late running events.
this.hasSizeChanged = () => undefined
this.checkIfSizeChanged = () => undefined
this.uninstall()
}
|
:: config -> Component -> WrappedComponent
Higher order component that allows the wrapped component to become aware
of it's size, by receiving it as an object within it's props.
@param monitorWidth
Default true, whether changes in the element's width should be monitored,
causing a size property to be broadcast.
@param monitorHeight
Default false, whether changes in the element's height should be monitored,
causing a size property to be broadcast.
@return The wrapped component.
|
componentWillUnmount
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
render() {
const disablePlaceholder =
withSize.enableSSRBehaviour ||
withSize.noPlaceholders ||
noPlaceholder ||
this.strategy === 'callback'
const size = { ...this.state }
return (
<SizeMeRenderWrapper
explicitRef={this.refCallback}
size={this.strategy === 'callback' ? null : size}
disablePlaceholder={disablePlaceholder}
{...this.props}
/>
)
}
|
:: config -> Component -> WrappedComponent
Higher order component that allows the wrapped component to become aware
of it's size, by receiving it as an object within it's props.
@param monitorWidth
Default true, whether changes in the element's width should be monitored,
causing a size property to be broadcast.
@param monitorHeight
Default false, whether changes in the element's height should be monitored,
causing a size property to be broadcast.
@return The wrapped component.
|
render
|
javascript
|
ctrlplusb/react-sizeme
|
src/with-size.js
|
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
|
MIT
|
shallowCompare = (obj1, obj2) => {
const obj1Keys = Object.keys(obj1);
return (
obj1Keys.length === Object.keys(obj2).length &&
obj1Keys.every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key])
);
}
|
Shallow compares two objects.
@param {Object} obj1 The first object to compare.
@param {Object} obj2 The second object to compare.
|
shallowCompare
|
javascript
|
reach/router
|
src/lib/utils.js
|
https://github.com/reach/router/blob/master/src/lib/utils.js
|
MIT
|
shallowCompare = (obj1, obj2) => {
const obj1Keys = Object.keys(obj1);
return (
obj1Keys.length === Object.keys(obj2).length &&
obj1Keys.every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key])
);
}
|
Shallow compares two objects.
@param {Object} obj1 The first object to compare.
@param {Object} obj2 The second object to compare.
|
shallowCompare
|
javascript
|
reach/router
|
src/lib/utils.js
|
https://github.com/reach/router/blob/master/src/lib/utils.js
|
MIT
|
async function setupCamera() {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
throw new Error(
'Browser API navigator.mediaDevices.getUserMedia not available');
}
const video = document.getElementById('video');
video.width = videoWidth;
video.height = videoHeight;
const stream = await navigator.mediaDevices.getUserMedia({
'audio': false,
'video': {
facingMode: 'user',
width: videoWidth,
height: videoHeight,
},
});
video.srcObject = stream;
return new Promise((resolve) => {
video.onloadedmetadata = () => {
resolve(video);
};
});
}
|
Loads a the camera to be used in the demo
|
setupCamera
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
async function loadVideo() {
const video = await setupCamera();
video.play();
return video;
}
|
Loads a the camera to be used in the demo
|
loadVideo
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
function setupGui(cameras) {
if (cameras.length > 0) {
guiState.camera = cameras[0].deviceId;
}
const gui = new dat.GUI({width: 300});
let multi = gui.addFolder('Image');
gui.add(guiState, 'avatarSVG', Object.keys(avatarSvgs)).onChange(() => parseSVG(avatarSvgs[guiState.avatarSVG]));
multi.open();
let output = gui.addFolder('Debug control');
output.add(guiState.debug, 'showDetectionDebug');
output.add(guiState.debug, 'showIllustrationDebug');
output.open();
}
|
Sets up dat.gui controller on the top-right of the window
|
setupGui
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
function setupFPS() {
stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
document.getElementById('main').appendChild(stats.dom);
}
|
Sets up a frames per second panel on the top-left of the window
|
setupFPS
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
function detectPoseInRealTime(video) {
const canvas = document.getElementById('output');
const keypointCanvas = document.getElementById('keypoints');
const videoCtx = canvas.getContext('2d');
const keypointCtx = keypointCanvas.getContext('2d');
canvas.width = videoWidth;
canvas.height = videoHeight;
keypointCanvas.width = videoWidth;
keypointCanvas.height = videoHeight;
async function poseDetectionFrame() {
// Begin monitoring code for frames per second
stats.begin();
let poses = [];
videoCtx.clearRect(0, 0, videoWidth, videoHeight);
// Draw video
videoCtx.save();
videoCtx.scale(-1, 1);
videoCtx.translate(-videoWidth, 0);
videoCtx.drawImage(video, 0, 0, videoWidth, videoHeight);
videoCtx.restore();
// Creates a tensor from an image
const input = tf.browser.fromPixels(canvas);
faceDetection = await facemesh.estimateFaces(input, false, false);
let all_poses = await posenet.estimatePoses(video, {
flipHorizontal: true,
decodingMethod: 'multi-person',
maxDetections: 1,
scoreThreshold: minPartConfidence,
nmsRadius: nmsRadius
});
poses = poses.concat(all_poses);
input.dispose();
keypointCtx.clearRect(0, 0, videoWidth, videoHeight);
if (guiState.debug.showDetectionDebug) {
poses.forEach(({score, keypoints}) => {
if (score >= minPoseConfidence) {
drawKeypoints(keypoints, minPartConfidence, keypointCtx);
drawSkeleton(keypoints, minPartConfidence, keypointCtx);
}
});
faceDetection.forEach(face => {
Object.values(facePartName2Index).forEach(index => {
let p = face.scaledMesh[index];
drawPoint(keypointCtx, p[1], p[0], 2, 'red');
});
});
}
canvasScope.project.clear();
if (poses.length >= 1 && illustration) {
Skeleton.flipPose(poses[0]);
if (faceDetection && faceDetection.length > 0) {
let face = Skeleton.toFaceFrame(faceDetection[0]);
illustration.updateSkeleton(poses[0], face);
} else {
illustration.updateSkeleton(poses[0], null);
}
illustration.draw(canvasScope, videoWidth, videoHeight);
if (guiState.debug.showIllustrationDebug) {
illustration.debugDraw(canvasScope);
}
}
canvasScope.project.activeLayer.scale(
canvasWidth / videoWidth,
canvasHeight / videoHeight,
new canvasScope.Point(0, 0));
// End monitoring code for frames per second
stats.end();
requestAnimationFrame(poseDetectionFrame);
}
poseDetectionFrame();
}
|
Feeds an image to posenet to estimate poses - this is where the magic
happens. This function loops with a requestAnimationFrame method.
|
detectPoseInRealTime
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
async function poseDetectionFrame() {
// Begin monitoring code for frames per second
stats.begin();
let poses = [];
videoCtx.clearRect(0, 0, videoWidth, videoHeight);
// Draw video
videoCtx.save();
videoCtx.scale(-1, 1);
videoCtx.translate(-videoWidth, 0);
videoCtx.drawImage(video, 0, 0, videoWidth, videoHeight);
videoCtx.restore();
// Creates a tensor from an image
const input = tf.browser.fromPixels(canvas);
faceDetection = await facemesh.estimateFaces(input, false, false);
let all_poses = await posenet.estimatePoses(video, {
flipHorizontal: true,
decodingMethod: 'multi-person',
maxDetections: 1,
scoreThreshold: minPartConfidence,
nmsRadius: nmsRadius
});
poses = poses.concat(all_poses);
input.dispose();
keypointCtx.clearRect(0, 0, videoWidth, videoHeight);
if (guiState.debug.showDetectionDebug) {
poses.forEach(({score, keypoints}) => {
if (score >= minPoseConfidence) {
drawKeypoints(keypoints, minPartConfidence, keypointCtx);
drawSkeleton(keypoints, minPartConfidence, keypointCtx);
}
});
faceDetection.forEach(face => {
Object.values(facePartName2Index).forEach(index => {
let p = face.scaledMesh[index];
drawPoint(keypointCtx, p[1], p[0], 2, 'red');
});
});
}
canvasScope.project.clear();
if (poses.length >= 1 && illustration) {
Skeleton.flipPose(poses[0]);
if (faceDetection && faceDetection.length > 0) {
let face = Skeleton.toFaceFrame(faceDetection[0]);
illustration.updateSkeleton(poses[0], face);
} else {
illustration.updateSkeleton(poses[0], null);
}
illustration.draw(canvasScope, videoWidth, videoHeight);
if (guiState.debug.showIllustrationDebug) {
illustration.debugDraw(canvasScope);
}
}
canvasScope.project.activeLayer.scale(
canvasWidth / videoWidth,
canvasHeight / videoHeight,
new canvasScope.Point(0, 0));
// End monitoring code for frames per second
stats.end();
requestAnimationFrame(poseDetectionFrame);
}
|
Feeds an image to posenet to estimate poses - this is where the magic
happens. This function loops with a requestAnimationFrame method.
|
poseDetectionFrame
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
function setupCanvas() {
mobile = isMobile();
if (mobile) {
canvasWidth = Math.min(window.innerWidth, window.innerHeight);
canvasHeight = canvasWidth;
videoWidth *= 0.7;
videoHeight *= 0.7;
}
canvasScope = paper.default;
let canvas = document.querySelector('.illustration-canvas');;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvasScope.setup(canvas);
}
|
Feeds an image to posenet to estimate poses - this is where the magic
happens. This function loops with a requestAnimationFrame method.
|
setupCanvas
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
async function bindPage() {
setupCanvas();
toggleLoadingUI(true);
setStatusText('Loading PoseNet model...');
posenet = await posenet_module.load({
architecture: defaultPoseNetArchitecture,
outputStride: defaultStride,
inputResolution: defaultInputResolution,
multiplier: defaultMultiplier,
quantBytes: defaultQuantBytes
});
setStatusText('Loading FaceMesh model...');
facemesh = await facemesh_module.load();
setStatusText('Loading Avatar file...');
let t0 = new Date();
await parseSVG(Object.values(avatarSvgs)[0]);
setStatusText('Setting up camera...');
try {
video = await loadVideo();
} catch (e) {
let info = document.getElementById('info');
info.textContent = 'this device type is not supported yet, ' +
'or this browser does not support video capture: ' + e.toString();
info.style.display = 'block';
throw e;
}
setupGui([], posenet);
setupFPS();
toggleLoadingUI(false);
detectPoseInRealTime(video, posenet);
}
|
Kicks off the demo by loading the posenet model, finding and loading
available camera devices, and setting off the detectPoseInRealTime function.
|
bindPage
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
async function parseSVG(target) {
let svgScope = await SVGUtils.importSVG(target /* SVG string or file path */);
let skeleton = new Skeleton(svgScope);
illustration = new PoseIllustration(canvasScope);
illustration.bindSkeleton(skeleton, svgScope);
}
|
Kicks off the demo by loading the posenet model, finding and loading
available camera devices, and setting off the detectPoseInRealTime function.
|
parseSVG
|
javascript
|
yemount/pose-animator
|
camera.js
|
https://github.com/yemount/pose-animator/blob/master/camera.js
|
Apache-2.0
|
function drawResults(image, canvas, faceDetection, poses) {
renderImageToCanvas(image, [VIDEO_WIDTH, VIDEO_HEIGHT], canvas);
const ctx = canvas.getContext('2d');
poses.forEach((pose) => {
if (pose.score >= defaultMinPoseConfidence) {
if (guiState.showKeypoints) {
drawKeypoints(pose.keypoints, defaultMinPartConfidence, ctx);
}
if (guiState.showSkeleton) {
drawSkeleton(pose.keypoints, defaultMinPartConfidence, ctx);
}
}
});
if (guiState.showKeypoints) {
faceDetection.forEach(face => {
Object.values(facePartName2Index).forEach(index => {
let p = face.scaledMesh[index];
drawPoint(ctx, p[1], p[0], 3, 'red');
});
});
}
}
|
Draws a pose if it passes a minimum confidence onto a canvas.
Only the pose's keypoints that pass a minPartConfidence are drawn.
|
drawResults
|
javascript
|
yemount/pose-animator
|
static_image.js
|
https://github.com/yemount/pose-animator/blob/master/static_image.js
|
Apache-2.0
|
async function loadImage(imagePath) {
const image = new Image();
const promise = new Promise((resolve, reject) => {
image.crossOrigin = '';
image.onload = () => {
resolve(image);
}
});
image.src = imagePath;
return promise;
}
|
Draws a pose if it passes a minimum confidence onto a canvas.
Only the pose's keypoints that pass a minPartConfidence are drawn.
|
loadImage
|
javascript
|
yemount/pose-animator
|
static_image.js
|
https://github.com/yemount/pose-animator/blob/master/static_image.js
|
Apache-2.0
|
function multiPersonCanvas() {
return document.querySelector('#multi canvas');
}
|
Draws a pose if it passes a minimum confidence onto a canvas.
Only the pose's keypoints that pass a minPartConfidence are drawn.
|
multiPersonCanvas
|
javascript
|
yemount/pose-animator
|
static_image.js
|
https://github.com/yemount/pose-animator/blob/master/static_image.js
|
Apache-2.0
|
function getIllustrationCanvas() {
return document.querySelector('.illustration-canvas');
}
|
Draws a pose if it passes a minimum confidence onto a canvas.
Only the pose's keypoints that pass a minPartConfidence are drawn.
|
getIllustrationCanvas
|
javascript
|
yemount/pose-animator
|
static_image.js
|
https://github.com/yemount/pose-animator/blob/master/static_image.js
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.