code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function fixByTrimmingWhitespace(fixer, fromLoc, toLoc, mode, spacing) { let replacementText = getSourceCode(context).text.slice(fromLoc, toLoc); if (mode === 'start') { replacementText = replacementText.replace(/^\s+/gm, ''); } else { replacementText = replacementText.replace(/\s+$/gm, ''); } if (spacing === SPACING.always) { if (mode === 'start') { replacementText += ' '; } else { replacementText = ` ${replacementText}`; } } return fixer.replaceTextRange([fromLoc, toLoc], replacementText); }
Trims text of whitespace between two ranges @param {Fixer} fixer - the eslint fixer object @param {number} fromLoc - the start location @param {number} toLoc - the end location @param {string} mode - either 'start' or 'end' @param {string=} spacing - a spacing value that will optionally add a space to the removed text @returns {Object|*|{range, text}}
fixByTrimmingWhitespace ( fixer , fromLoc , toLoc , mode , spacing )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js
MIT
function reportNoBeginningNewline(node, token, spacing) { report(context, messages.noNewlineAfter, 'noNewlineAfter', { node, loc: token.loc.start, data: { token: token.value, }, fix(fixer) { const nextToken = getSourceCode(context).getTokenAfter(token); return fixByTrimmingWhitespace(fixer, token.range[1], nextToken.range[0], 'start', spacing); }, }); }
Reports that there shouldn't be a newline after the first token @param {ASTNode} node - The node to report in the event of an error. @param {Token} token - The token to use for the report. @param {string} spacing @returns {void}
reportNoBeginningNewline ( node , token , spacing )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js
MIT
function reportNoEndingNewline(node, token, spacing) { report(context, messages.noNewlineBefore, 'noNewlineBefore', { node, loc: token.loc.start, data: { token: token.value, }, fix(fixer) { const previousToken = getSourceCode(context).getTokenBefore(token); return fixByTrimmingWhitespace(fixer, previousToken.range[1], token.range[0], 'end', spacing); }, }); }
Reports that there shouldn't be a newline before the last token @param {ASTNode} node - The node to report in the event of an error. @param {Token} token - The token to use for the report. @param {string} spacing @returns {void}
reportNoEndingNewline ( node , token , spacing )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js
MIT
function reportNoBeginningSpace(node, token) { report(context, messages.noSpaceAfter, 'noSpaceAfter', { node, loc: token.loc.start, data: { token: token.value, }, fix(fixer) { const sourceCode = getSourceCode(context); const nextToken = sourceCode.getTokenAfter(token); let nextComment; // eslint >=4.x if (sourceCode.getCommentsAfter) { nextComment = sourceCode.getCommentsAfter(token); // eslint 3.x } else { const potentialComment = sourceCode.getTokenAfter(token, { includeComments: true }); nextComment = nextToken === potentialComment ? [] : [potentialComment]; } // Take comments into consideration to narrow the fix range to what is actually affected. (See #1414) if (nextComment.length > 0) { return fixByTrimmingWhitespace(fixer, token.range[1], Math.min(nextToken.range[0], nextComment[0].range[0]), 'start'); } return fixByTrimmingWhitespace(fixer, token.range[1], nextToken.range[0], 'start'); }, }); }
Reports that there shouldn't be a space after the first token @param {ASTNode} node - The node to report in the event of an error. @param {Token} token - The token to use for the report. @returns {void}
reportNoBeginningSpace ( node , token )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js
MIT
function reportNoEndingSpace(node, token) { report(context, messages.noSpaceBefore, 'noSpaceBefore', { node, loc: token.loc.start, data: { token: token.value, }, fix(fixer) { const sourceCode = getSourceCode(context); const previousToken = sourceCode.getTokenBefore(token); let previousComment; // eslint >=4.x if (sourceCode.getCommentsBefore) { previousComment = sourceCode.getCommentsBefore(token); // eslint 3.x } else { const potentialComment = sourceCode.getTokenBefore(token, { includeComments: true }); previousComment = previousToken === potentialComment ? [] : [potentialComment]; } // Take comments into consideration to narrow the fix range to what is actually affected. (See #1414) if (previousComment.length > 0) { return fixByTrimmingWhitespace(fixer, Math.max(previousToken.range[1], previousComment[0].range[1]), token.range[0], 'end'); } return fixByTrimmingWhitespace(fixer, previousToken.range[1], token.range[0], 'end'); }, }); }
Reports that there shouldn't be a space before the last token @param {ASTNode} node - The node to report in the event of an error. @param {Token} token - The token to use for the report. @returns {void}
reportNoEndingSpace ( node , token )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js
MIT
function reportRequiredBeginningSpace(node, token) { report(context, messages.spaceNeededAfter, 'spaceNeededAfter', { node, loc: token.loc.start, data: { token: token.value, }, fix(fixer) { return fixer.insertTextAfter(token, ' '); }, }); }
Reports that there should be a space after the first token @param {ASTNode} node - The node to report in the event of an error. @param {Token} token - The token to use for the report. @returns {void}
reportRequiredBeginningSpace ( node , token )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js
MIT
function reportRequiredEndingSpace(node, token) { report(context, messages.spaceNeededBefore, 'spaceNeededBefore', { node, loc: token.loc.start, data: { token: token.value, }, fix(fixer) { return fixer.insertTextBefore(token, ' '); }, }); }
Reports that there should be a space before the last token @param {ASTNode} node - The node to report in the event of an error. @param {Token} token - The token to use for the report. @returns {void}
reportRequiredEndingSpace ( node , token )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js
MIT
function validateBraceSpacing(node) { let config; switch (node.parent.type) { case 'JSXAttribute': case 'JSXOpeningElement': config = attributesConfig; break; case 'JSXElement': case 'JSXFragment': config = childrenConfig; break; default: return; } if (config === null) { return; } const sourceCode = getSourceCode(context); const first = sourceCode.getFirstToken(node); const last = sourceCode.getLastToken(node); let second = sourceCode.getTokenAfter(first, { includeComments: true }); let penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); if (!second) { second = sourceCode.getTokenAfter(first); const leadingComments = sourceCode.getNodeByRangeIndex(second.range[0]).leadingComments; second = leadingComments ? leadingComments[0] : second; } if (!penultimate) { penultimate = sourceCode.getTokenBefore(last); const trailingComments = sourceCode.getNodeByRangeIndex(penultimate.range[0]).trailingComments; penultimate = trailingComments ? trailingComments[trailingComments.length - 1] : penultimate; } const isObjectLiteral = first.value === second.value; const spacing = isObjectLiteral ? config.objectLiteralSpaces : config.when; if (spacing === SPACING.always) { if (!sourceCode.isSpaceBetweenTokens(first, second)) { reportRequiredBeginningSpace(node, first); } else if (!config.allowMultiline && isMultiline(first, second)) { reportNoBeginningNewline(node, first, spacing); } if (!sourceCode.isSpaceBetweenTokens(penultimate, last)) { reportRequiredEndingSpace(node, last); } else if (!config.allowMultiline && isMultiline(penultimate, last)) { reportNoEndingNewline(node, last, spacing); } } else if (spacing === SPACING.never) { if (isMultiline(first, second)) { if (!config.allowMultiline) { reportNoBeginningNewline(node, first, spacing); } } else if (sourceCode.isSpaceBetweenTokens(first, second)) { reportNoBeginningSpace(node, first); } if (isMultiline(penultimate, last)) { if (!config.allowMultiline) { reportNoEndingNewline(node, last, spacing); } } else if (sourceCode.isSpaceBetweenTokens(penultimate, last)) { reportNoEndingSpace(node, last); } } }
Determines if spacing in curly braces is valid. @param {ASTNode} node The AST node to check. @returns {void}
validateBraceSpacing ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js
MIT
function isTokenOnSameLine(left, right) { return left.loc.end.line === right.loc.start.line; }
Determines whether two adjacent tokens are on the same line. @param {Object} left - The left token object. @param {Object} right - The right token object. @returns {boolean} Whether or not the tokens are on the same line.
isTokenOnSameLine ( left , right )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-curly-newline.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-newline.js
MIT
function isNonNullaryLiteral(expression) { return expression.type === 'Literal' && expression.value !== null; }
@param {ASTNode} expression An Identifier node @returns {boolean}
isNonNullaryLiteral ( expression )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/style-prop-object.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/style-prop-object.js
MIT
function checkIdentifiers(node) { const variable = variableUtil.getVariableFromContext(context, node, node.name); if (!variable || !variable.defs[0] || !variable.defs[0].node.init) { return; } if (isNonNullaryLiteral(variable.defs[0].node.init)) { report(context, messages.stylePropNotObject, 'stylePropNotObject', { node, }); } }
@param {object} node A Identifier node
checkIdentifiers ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/style-prop-object.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/style-prop-object.js
MIT
function isValid(component) { return !!component && !component.mutateSetState; }
Checks if the component is valid @param {Object} component The component to process @returns {boolean} True if the component is valid, false if not.
isValid ( component )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-direct-mutation-state.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-direct-mutation-state.js
MIT
function reportMutations(component) { let mutation; for (let i = 0, j = component.mutations.length; i < j; i++) { mutation = component.mutations[i]; report(context, messages.noDirectMutation, 'noDirectMutation', { node: mutation, }); } }
Reports undeclared proptypes for a given component @param {Object} component The component to process
reportMutations ( component )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-direct-mutation-state.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-direct-mutation-state.js
MIT
function getOuterMemberExpression(node) { while (node.object && node.object.property) { node = node.object; } return node; }
Walks through the MemberExpression to the top-most property. @param {Object} node The node to process @returns {Object} The outer-most MemberExpression
getOuterMemberExpression ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-direct-mutation-state.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-direct-mutation-state.js
MIT
function shouldIgnoreComponent(component) { return !component || (component.inConstructor && !component.inCallExpression); }
Determine if we should currently ignore assignments in this component. @param {?Object} component The component to process @returns {boolean} True if we should skip assignment checks.
shouldIgnoreComponent ( component )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-direct-mutation-state.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-direct-mutation-state.js
MIT
function getMethodsOrder(userConfig) { userConfig = userConfig || {}; const groups = Object.assign({}, defaultConfig.groups, userConfig.groups); const order = userConfig.order || defaultConfig.order; let config = []; let entry; for (let i = 0, j = order.length; i < j; i++) { entry = order[i]; if (has(groups, entry)) { config = config.concat(groups[entry]); } else { config.push(entry); } } return config; }
Get the methods order from the default config and the user config @param {Object} userConfig The user configuration. @returns {Array} Methods order
getMethodsOrder ( userConfig )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/sort-comp.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-comp.js
MIT
function getRefPropIndexes(method) { const methodGroupIndexes = []; methodsOrder.forEach((currentGroup, groupIndex) => { if (currentGroup === 'getters') { if (method.getter) { methodGroupIndexes.push(groupIndex); } } else if (currentGroup === 'setters') { if (method.setter) { methodGroupIndexes.push(groupIndex); } } else if (currentGroup === 'type-annotations') { if (method.typeAnnotation) { methodGroupIndexes.push(groupIndex); } } else if (currentGroup === 'static-variables') { if (method.staticVariable) { methodGroupIndexes.push(groupIndex); } } else if (currentGroup === 'static-methods') { if (method.staticMethod) { methodGroupIndexes.push(groupIndex); } } else if (currentGroup === 'instance-variables') { if (method.instanceVariable) { methodGroupIndexes.push(groupIndex); } } else if (currentGroup === 'instance-methods') { if (method.instanceMethod) { methodGroupIndexes.push(groupIndex); } } else if (arrayIncludes([ 'displayName', 'propTypes', 'contextTypes', 'childContextTypes', 'mixins', 'statics', 'defaultProps', 'constructor', 'getDefaultProps', 'state', 'getInitialState', 'getChildContext', 'getDerivedStateFromProps', 'componentWillMount', 'UNSAFE_componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'UNSAFE_componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'UNSAFE_componentWillUpdate', 'getSnapshotBeforeUpdate', 'componentDidUpdate', 'componentDidCatch', 'componentWillUnmount', 'render', ], currentGroup)) { if (currentGroup === method.name) { methodGroupIndexes.push(groupIndex); } } else { // Is the group a regex? const isRegExp = currentGroup.match(regExpRegExp); if (isRegExp) { const isMatching = new RegExp(isRegExp[1], isRegExp[2]).test(method.name); if (isMatching) { methodGroupIndexes.push(groupIndex); } } else if (currentGroup === method.name) { methodGroupIndexes.push(groupIndex); } } }); // No matching pattern, return 'everything-else' index if (methodGroupIndexes.length === 0) { const everythingElseIndex = methodsOrder.indexOf('everything-else'); if (everythingElseIndex !== -1) { methodGroupIndexes.push(everythingElseIndex); } else { // No matching pattern and no 'everything-else' group methodGroupIndexes.push(Infinity); } } return methodGroupIndexes; }
Get indexes of the matching patterns in methods order configuration @param {Object} method - Method metadata. @returns {Array} The matching patterns indexes. Return [Infinity] if there is no match.
getRefPropIndexes ( method )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/sort-comp.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-comp.js
MIT
function storeError(propA, propB) { // Initialize the error object if needed if (!errors[propA.index]) { errors[propA.index] = { node: propA.node, score: 0, closest: { distance: Infinity, ref: { node: null, index: 0, }, }, }; } // Increment the prop score errors[propA.index].score += 1; // Stop here if we already have pushed another node at this position if (getPropertyName(errors[propA.index].node) !== getPropertyName(propA.node)) { return; } // Stop here if we already have a closer reference if (Math.abs(propA.index - propB.index) > errors[propA.index].closest.distance) { return; } // Update the closest reference errors[propA.index].closest.distance = Math.abs(propA.index - propB.index); errors[propA.index].closest.ref.node = propB.node; errors[propA.index].closest.ref.index = propB.index; }
Store a new error in the error list @param {Object} propA - Mispositioned property. @param {Object} propB - Reference property.
storeError ( propA , propB )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/sort-comp.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-comp.js
MIT
function dedupeErrors() { entries(errors).forEach((entry) => { const i = entry[0]; const error = entry[1]; const index = error.closest.ref.index; if (errors[index]) { if (error.score > errors[index].score) { delete errors[index]; } else { delete errors[i]; } } }); }
Dedupe errors, only keep the ones with the highest score and delete the others
dedupeErrors ( )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/sort-comp.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-comp.js
MIT
function comparePropsOrder(propertiesInfos, propA, propB) { let i; let j; let k; let l; let refIndexA; let refIndexB; // Get references indexes (the correct position) for given properties const refIndexesA = getRefPropIndexes(propA); const refIndexesB = getRefPropIndexes(propB); // Get current indexes for given properties const classIndexA = propertiesInfos.indexOf(propA); const classIndexB = propertiesInfos.indexOf(propB); // Loop around the references indexes for the 1st property for (i = 0, j = refIndexesA.length; i < j; i++) { refIndexA = refIndexesA[i]; // Loop around the properties for the 2nd property (for comparison) for (k = 0, l = refIndexesB.length; k < l; k++) { refIndexB = refIndexesB[k]; if ( // Comparing the same properties refIndexA === refIndexB // 1st property is placed before the 2nd one in reference and in current component || ((refIndexA < refIndexB) && (classIndexA < classIndexB)) // 1st property is placed after the 2nd one in reference and in current component || ((refIndexA > refIndexB) && (classIndexA > classIndexB)) ) { return { correct: true, indexA: classIndexA, indexB: classIndexB, }; } } } // We did not find any correct match between reference and current component return { correct: false, indexA: refIndexA, indexB: refIndexB, }; }
Compare two properties and find out if they are in the right order @param {Array} propertiesInfos Array containing all the properties metadata. @param {Object} propA First property name and metadata @param {Object} propB Second property name. @returns {Object} Object containing a correct true/false flag and the correct indexes for the two properties.
comparePropsOrder ( propertiesInfos , propA , propB )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/sort-comp.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-comp.js
MIT
function hasShouldComponentUpdate(node) { const properties = astUtil.getComponentProperties(node); return properties.some((property) => { const name = astUtil.getPropertyName(property); return name === 'shouldComponentUpdate'; }); }
Checks for shouldComponentUpdate property @param {ASTNode} node The AST node being checked. @returns {boolean} Whether or not the property exists.
hasShouldComponentUpdate ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-redundant-should-component-update.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-redundant-should-component-update.js
MIT
function getNodeName(node) { if (node.id) { return node.id.name; } if (node.parent && node.parent.id) { return node.parent.id.name; } return ''; }
Get name of node if available @param {ASTNode} node The AST node being checked. @return {string} The name of the node
getNodeName ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-redundant-should-component-update.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-redundant-should-component-update.js
MIT
function checkForViolation(node) { if (componentUtil.isPureComponent(node, context)) { const hasScu = hasShouldComponentUpdate(node); if (hasScu) { const className = getNodeName(node); report(context, messages.noShouldCompUpdate, 'noShouldCompUpdate', { node, data: { component: className, }, }); } } }
Checks for violation of rule @param {ASTNode} node The AST node being checked.
checkForViolation ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-redundant-should-component-update.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-redundant-should-component-update.js
MIT
function getExpectedLocation(tokens) { let location; // Is always after the opening tag if there is no props if (typeof tokens.lastProp === 'undefined') { location = 'after-tag'; // Is always after the last prop if this one is on the same line as the opening bracket } else if (tokens.opening.line === tokens.lastProp.lastLine) { location = 'after-props'; // Else use configuration dependent on selfClosing property } else { location = tokens.selfClosing ? options.selfClosing : options.nonEmpty; } return location; }
Get expected location for the closing bracket @param {Object} tokens Locations of the opening bracket, closing bracket and last prop @return {string} Expected location for the closing bracket
getExpectedLocation ( tokens )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-closing-bracket-location.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-closing-bracket-location.js
MIT
function getCorrectColumn(tokens, expectedLocation) { switch (expectedLocation) { case 'props-aligned': return tokens.lastProp.column; case 'tag-aligned': return tokens.opening.column; case 'line-aligned': return tokens.openingStartOfLine.column; default: return null; } }
Get the correct 0-indexed column for the closing bracket, given the expected location. @param {Object} tokens Locations of the opening bracket, closing bracket and last prop @param {string} expectedLocation Expected location for the closing bracket @return {?Number} The correct column for the closing bracket, or null
getCorrectColumn ( tokens , expectedLocation )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-closing-bracket-location.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-closing-bracket-location.js
MIT
function getIndentation(tokens, expectedLocation, correctColumn) { const newColumn = correctColumn || 0; let indentation; let spaces = ''; switch (expectedLocation) { case 'props-aligned': indentation = /^\s*/.exec(getSourceCode(context).lines[tokens.lastProp.firstLine - 1])[0]; break; case 'tag-aligned': case 'line-aligned': indentation = /^\s*/.exec(getSourceCode(context).lines[tokens.opening.line - 1])[0]; break; default: indentation = ''; } if (indentation.length + 1 < newColumn) { // Non-whitespace characters were included in the column offset spaces = repeat(' ', +correctColumn - indentation.length); } return indentation + spaces; }
Get the characters used for indentation on the line to be matched @param {Object} tokens Locations of the opening bracket, closing bracket and last prop @param {string} expectedLocation Expected location for the closing bracket @param {number} [correctColumn] Expected column for the closing bracket. Default to 0 @return {string} The characters used for indentation
getIndentation ( tokens , expectedLocation , correctColumn )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-closing-bracket-location.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-closing-bracket-location.js
MIT
function getOpeningElementId(node) { return node.range.join(':'); }
Get an unique ID for a given JSXOpeningElement @param {ASTNode} node The AST node being checked. @returns {string} Unique ID (based on its range)
getOpeningElementId ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-closing-bracket-location.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-closing-bracket-location.js
MIT
function isIgnored(component) { return ( ignoreStateless && ( /Function/.test(component.node.type) || utils.isPragmaComponentWrapper(component.node) ) ); }
Checks if the component is ignored @param {Object} component The component being checked. @returns {boolean} True if the component is ignored, false if not.
isIgnored ( component )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-multi-comp.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-multi-comp.js
MIT
function isContextInClass(node) { let blockNode; let scope = getScope(context, node); while (scope) { blockNode = scope.block; if (blockNode && blockNode.type === 'ClassDeclaration') { return true; } scope = scope.upper; } return false; }
Checks if we are declaring context in class @param {ASTNode} node @returns {boolean} True if we are declaring context in class, false if not.
isContextInClass ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/static-property-placement.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/static-property-placement.js
MIT
function reportNodeIncorrectlyPositioned(node, expectedRule) { // Detect if this node is an expected property declaration adn return the property name const name = classProperties.find((propertyName) => { if (propertiesToCheck[propertyName](node)) { return !!propertyName; } return false; }); // If name is set but the configured rule does not match expected then report error if ( name && ( config[name] !== expectedRule || (!node.static && (config[name] === STATIC_PUBLIC_FIELD || config[name] === STATIC_GETTER)) ) ) { const messageId = ERROR_MESSAGES[config[name]]; report(context, messages[messageId], messageId, { node, data: { name }, }); } }
Check if we should report this property node @param {ASTNode} node @param {string} expectedRule
reportNodeIncorrectlyPositioned ( node , expectedRule )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/static-property-placement.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/static-property-placement.js
MIT
function reportSetStateUsages(component) { for (let i = 0, j = component.setStateUsages.length; i < j; i++) { const setStateUsage = component.setStateUsages[i]; report(context, messages.noSetState, 'noSetState', { node: setStateUsage, }); } }
Reports usages of setState for a given component @param {Object} component The component to process
reportSetStateUsages ( component )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-set-state.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-set-state.js
MIT
function hasEqual(attrNode) { return attrNode.type !== 'JSXSpreadAttribute' && attrNode.value !== null; }
Determines a given attribute node has an equal sign. @param {ASTNode} attrNode - The attribute node. @returns {boolean} Whether or not the attriute node has an equal sign.
hasEqual ( attrNode )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-equals-spacing.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-equals-spacing.js
MIT
const t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,s=Symbol(),o=new WeakMap;class n{constructor(t,e,o){if(this._$cssResult$=!0,o!==s)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const s=this.t;if(e&&void 0===t){const e=void 0!==s&&1===s.length;e&&(t=o.get(s)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&o.set(s,t))}return t}toString(){return this.cssText}}const r=t=>new n("string"==typeof t?t:t+"",void 0,s),i=(t,...e)=>{const o=1===t.length?t[0]:e.reduce(((e,s,o)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+t[o+1]),t[0]);return new n(o,t,s)},S=(s,o)=>{if(e)s.adoptedStyleSheets=o.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet));else for(const e of o){const o=document.createElement("style"),n=t.litNonce;void 0!==n&&o.setAttribute("nonce",n),o.textContent=e.cssText,s.appendChild(o)}},c=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const s of t.cssRules)e+=s.cssText;return r(e)})(t):t;
@license Copyright 2019 Google LLC SPDX-License-Identifier: BSD-3-Clause
constructor ( t , e , o )
javascript
rapi-doc/RapiDoc
dist/rapidoc.js
https://github.com/rapi-doc/RapiDoc/blob/master/dist/rapidoc.js
MIT
const lit_html_n=globalThis,lit_html_c=lit_html_n.trustedTypes,lit_html_h=lit_html_c?lit_html_c.createPolicy("lit-html",{createHTML:t=>t}):void 0,lit_html_f="$lit$",v=`lit$${Math.random().toFixed(9).slice(2)}$`,m="?"+v,_=`<${m}>`,w=document,lt=()=>w.createComment(""),st=t=>null===t||"object"!=typeof t&&"function"!=typeof t,g=Array.isArray,$=t=>g(t)||"function"==typeof t?.[Symbol.iterator],x="[ \t\n\f\r]",T=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,E=/-->/g,k=/>/g,O=RegExp(`>|${x}(?:([^\\s"'>=/]+)(${x}*=${x}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),lit_html_S=/'/g,j=/"/g,M=/^(?:script|style|textarea|title)$/i,P=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),ke=P(1),Oe=P(2),Se=P(3),R=Symbol.for("lit-noChange"),D=Symbol.for("lit-nothing"),V=new WeakMap,I=w.createTreeWalker(w,129);function N(t,i){if(!g(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==lit_html_h?lit_html_h.createHTML(i):i}const U=(t,i)=>{const s=t.length-1,e=[];let h,o=2===i?"<svg>":3===i?"<math>":"",n=T;for(let i=0;i<s;i++){const s=t[i];let r,l,c=-1,a=0;for(;a<s.length&&(n.lastIndex=a,l=n.exec(s),null!==l);)a=n.lastIndex,n===T?"!--"===l[1]?n=E:void 0!==l[1]?n=k:void 0!==l[2]?(M.test(l[2])&&(h=RegExp("</"+l[2],"g")),n=O):void 0!==l[3]&&(n=O):n===O?">"===l[0]?(n=h??T,c=-1):void 0===l[1]?c=-2:(c=n.lastIndex-l[2].length,r=l[1],n=void 0===l[3]?O:'"'===l[3]?j:lit_html_S):n===j||n===lit_html_S?n=O:n===E||n===k?n=T:(n=O,h=void 0);const u=n===O&&t[i+1].startsWith("/>")?" ":"";o+=n===T?s+_:c>=0?(e.push(r),s.slice(0,c)+lit_html_f+s.slice(c)+v+u):s+v+(-2===c?i:u)}return[N(t,o+(t[s]||"<?>")+(2===i?"</svg>":3===i?"</math>":"")),e]};class B{constructor({strings:t,_$litType$:i},s){let e;this.parts=[];let h=0,o=0;const n=t.length-1,r=this.parts,[l,a]=U(t,i);if(this.el=B.createElement(l,s),I.currentNode=this.el.content,2===i||3===i){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(e=I.nextNode())&&r.length<n;){if(1===e.nodeType){if(e.hasAttributes())for(const t of e.getAttributeNames())if(t.endsWith(lit_html_f)){const i=a[o++],s=e.getAttribute(t).split(v),n=/([.?@])?(.*)/.exec(i);r.push({type:1,index:h,name:n[2],strings:s,ctor:"."===n[1]?Y:"?"===n[1]?Z:"@"===n[1]?q:G}),e.removeAttribute(t)}else t.startsWith(v)&&(r.push({type:6,index:h}),e.removeAttribute(t));if(M.test(e.tagName)){const t=e.textContent.split(v),i=t.length-1;if(i>0){e.textContent=lit_html_c?lit_html_c.emptyScript:"";for(let s=0;s<i;s++)e.append(t[s],lt()),I.nextNode(),r.push({type:2,index:++h});e.append(t[i],lt())}}}else if(8===e.nodeType)if(e.data===m)r.push({type:2,index:h});else{let t=-1;for(;-1!==(t=e.data.indexOf(v,t+1));)r.push({type:7,index:h}),t+=v.length-1}h++}}static createElement(t,i){const s=w.createElement("template");return s.innerHTML=t,s}}function z(t,i,s=t,e){if(i===R)return i;let h=void 0!==e?s.o?.[e]:s.l;const o=st(i)?void 0:i._$litDirective$;return h?.constructor!==o&&(h?._$AO?.(!1),void 0===o?h=void 0:(h=new o(t),h._$AT(t,s,e)),void 0!==e?(s.o??=[])[e]=h:s.l=h),void 0!==h&&(i=z(t,h._$AS(t,i.values),h,e)),i}class F{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,e=(t?.creationScope??w).importNode(i,!0);I.currentNode=e;let h=I.nextNode(),o=0,n=0,r=s[0];for(;void 0!==r;){if(o===r.index){let i;2===r.type?i=new et(h,h.nextSibling,this,t):1===r.type?i=new r.ctor(h,r.name,r.strings,this,t):6===r.type&&(i=new K(h,this,t)),this._$AV.push(i),r=s[++n]}o!==r?.index&&(h=I.nextNode(),o++)}return I.currentNode=w,e}p(t){let i=0;for(const s of this._$AV)void 0!==s&&(void 0!==s.strings?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class et{get _$AU(){return this._$AM?._$AU??this.v}constructor(t,i,s,e){this.type=2,this._$AH=D,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=e,this.v=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return void 0!==i&&11===t?.nodeType&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=z(this,t,i),st(t)?t===D||null==t||""===t?(this._$AH!==D&&this._$AR(),this._$AH=D):t!==this._$AH&&t!==R&&this._(t):void 0!==t._$litType$?this.$(t):void 0!==t.nodeType?this.T(t):$(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==D&&st(this._$AH)?this._$AA.nextSibling.data=t:this.T(w.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,e="number"==typeof s?this._$AC(t):(void 0===s.el&&(s.el=B.createElement(N(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===e)this._$AH.p(i);else{const t=new F(e,this),s=t.u(this.options);t.p(i),this.T(s),this._$AH=t}}_$AC(t){let i=V.get(t.strings);return void 0===i&&V.set(t.strings,i=new B(t)),i}k(t){g(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,e=0;for(const h of t)e===i.length?i.push(s=new et(this.O(lt()),this.O(lt()),this,this.options)):s=i[e],s._$AI(h),e++;e<i.length&&(this._$AR(s&&s._$AB.nextSibling,e),i.length=e)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t&&t!==this._$AB;){const i=t.nextSibling;t.remove(),t=i}}setConnected(t){void 0===this._$AM&&(this.v=t,this._$AP?.(t))}}class G{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,e,h){this.type=1,this._$AH=D,this._$AN=void 0,this.element=t,this.name=i,this._$AM=e,this.options=h,s.length>2||""!==s[0]||""!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=D}_$AI(t,i=this,s,e){const h=this.strings;let o=!1;if(void 0===h)t=z(this,t,i,0),o=!st(t)||t!==this._$AH&&t!==R,o&&(this._$AH=t);else{const e=t;let n,r;for(t=h[0],n=0;n<h.length-1;n++)r=z(this,e[s+n],i,n),r===R&&(r=this._$AH[n]),o||=!st(r)||r!==this._$AH[n],r===D?t=D:t!==D&&(t+=(r??"")+h[n+1]),this._$AH[n]=r}o&&!e&&this.j(t)}j(t){t===D?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}class Y extends G{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===D?void 0:t}}class Z extends G{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==D)}}class q extends G{constructor(t,i,s,e,h){super(t,i,s,e,h),this.type=5}_$AI(t,i=this){if((t=z(this,t,i,0)??D)===R)return;const s=this._$AH,e=t===D&&s!==D||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,h=t!==D&&(s===D||e);e&&this.element.removeEventListener(this.name,this,s),h&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}}class K{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){z(this,t)}}const si={M:lit_html_f,P:v,A:m,C:1,L:U,R:F,D:$,V:z,I:et,H:G,N:Z,U:q,B:Y,F:K},Re=lit_html_n.litHtmlPolyfillSupport;Re?.(B,et),(lit_html_n.litHtmlVersions??=[]).push("3.2.0");const Q=(t,i,s)=>{const e=s?.renderBefore??i;let h=e._$litPart$;if(void 0===h){const t=s?.renderBefore??null;e._$litPart$=h=new et(i.insertBefore(lt(),t),t,void 0,s??{})}return h._$AI(t),h};
@license Copyright 2017 Google LLC SPDX-License-Identifier: BSD-3-Clause
createHTML
javascript
rapi-doc/RapiDoc
dist/rapidoc.js
https://github.com/rapi-doc/RapiDoc/blob/master/dist/rapidoc.js
MIT
function getDefaults() { return { async: false, baseUrl: null, breaks: false, extensions: null, gfm: true, headerIds: true, headerPrefix: '', highlight: null, hooks: null, langPrefix: 'language-', mangle: true, pedantic: false, renderer: null, sanitize: false, sanitizer: null, silent: false, smartypants: false, tokenizer: null, walkTokens: null, xhtml: false }; }
DO NOT EDIT THIS FILE The code in this file is generated from files in ./src/
getDefaults ( )
javascript
rapi-doc/RapiDoc
dist/rapidoc.js
https://github.com/rapi-doc/RapiDoc/blob/master/dist/rapidoc.js
MIT
function rtrim(str, c, invert) { const l = str.length; if (l === 0) { return ''; } // Length of suffix matching the invert condition. let suffLen = 0; // Step left until we fail to match the invert condition. while (suffLen < l) { const currChar = str.charAt(l - suffLen - 1); if (currChar === c && !invert) { suffLen++; } else if (currChar !== c && invert) { suffLen++; } else { break; } } return str.slice(0, l - suffLen); }
Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). /c*$/ is vulnerable to REDOS. @param {string} str @param {string} c @param {boolean} invert Remove suffix of non-c chars instead. Default falsey.
rtrim ( str , c , invert )
javascript
rapi-doc/RapiDoc
dist/rapidoc.js
https://github.com/rapi-doc/RapiDoc/blob/master/dist/rapidoc.js
MIT
function repeatString(pattern, count) { if (count < 1) { return ''; } let result = ''; while (count > 1) { if (count & 1) { result += pattern; } count >>= 1; pattern += pattern; } return result + pattern; }
@param {string} pattern @param {number} count
repeatString ( pattern , count )
javascript
rapi-doc/RapiDoc
dist/rapidoc.js
https://github.com/rapi-doc/RapiDoc/blob/master/dist/rapidoc.js
MIT
slug(value, options = {}) { const slug = this.serialize(value); return this.getNextSafeSlug(slug, options.dryrun); } }
Convert string to unique id @param {object} [options] @param {boolean} [options.dryrun] Generates the next unique slug without updating the internal accumulator.
slug ( value , options = { )
javascript
rapi-doc/RapiDoc
dist/rapidoc.js
https://github.com/rapi-doc/RapiDoc/blob/master/dist/rapidoc.js
MIT
postprocess(html) { return html; } }
Process HTML after marked is finished
postprocess ( html )
javascript
rapi-doc/RapiDoc
dist/rapidoc.js
https://github.com/rapi-doc/RapiDoc/blob/master/dist/rapidoc.js
MIT
/******/ function hotSetStatus(newStatus) { /******/ hotStatus = newStatus; /******/ for (var i = 0; i < hotStatusHandlers.length; i++) /******/ hotStatusHandlers[i].call(null, newStatus); /******/ }
****/ var hotStatus = "idle"; ****/
hotSetStatus ( newStatus )
javascript
rapi-doc/RapiDoc
docs/images/example1_files/rapidoc-min.js
https://github.com/rapi-doc/RapiDoc/blob/master/docs/images/example1_files/rapidoc-min.js
MIT
/******/ function toModuleId(id) { /******/ var isNumber = +id + "" === id; /******/ return isNumber ? +id : id; /******/ }
****/ var hotUpdate, hotUpdateNewHash; ****/
toModuleId ( id )
javascript
rapi-doc/RapiDoc
docs/images/example1_files/rapidoc-min.js
https://github.com/rapi-doc/RapiDoc/blob/master/docs/images/example1_files/rapidoc-min.js
MIT
/******/ var queue = outdatedModules.map(function(id) { /******/ return { /******/ chain: [id], /******/ id: id /******/ }; /******/ });
****/ var outdatedDependencies = {}; ****/
(anonymous) ( id )
javascript
rapi-doc/RapiDoc
docs/images/example1_files/rapidoc-min.js
https://github.com/rapi-doc/RapiDoc/blob/master/docs/images/example1_files/rapidoc-min.js
MIT
/******/ var warnUnexpectedRequire = function warnUnexpectedRequire() { /******/ console.warn( /******/ "[HMR] unexpected require(" + result.moduleId + ") to disposed module" /******/ ); /******/ };
****/ var appliedUpdate = {}; ****/
warnUnexpectedRequire ( )
javascript
rapi-doc/RapiDoc
docs/images/example1_files/rapidoc-min.js
https://github.com/rapi-doc/RapiDoc/blob/master/docs/images/example1_files/rapidoc-min.js
MIT
receiveAuthParms() { let authData = {}; if (document.location.search) { // Applies to authorizationCode flow const params = new URLSearchParams(document.location.search); const code = params.get('code'); const error = params.get('error'); const state = params.get('state'); authData = { code, error, state, responseType: 'code', }; } else if (window.location.hash) { // Applies to Implicit flow const token_type = this.parseQueryString(window.location.hash.substring(1), 'token_type'); // eslint-disable-line camelcase const access_token = this.parseQueryString(window.location.hash.substring(1), 'access_token'); // eslint-disable-line camelcase authData = { token_type, access_token, responseType: 'token' }; // eslint-disable-line camelcase } if (window.opener) { window.opener.postMessage(authData, this.target); return; } sessionStorage.setItem('rapidoc-oauth-data', JSON.stringify(authData)); // Fallback to session storage if window.opener dont exist }
Read OAuth2 parameters and sends them off to the window opener through `window.postMessage`.
receiveAuthParms ( )
javascript
rapi-doc/RapiDoc
src/oauth-receiver.js
https://github.com/rapi-doc/RapiDoc/blob/master/src/oauth-receiver.js
MIT
export function standardizeExample(ex) { if (typeof ex === 'object' && !Array.isArray(ex)) { if (ex.value !== undefined) { // Case 1: Single object with 'value' property return { Example: { ...ex } }; } // Case 2: Object where each key is an object with a 'value' property const filteredEntries = Object.entries(ex).filter(([_, obj]) => obj.value !== undefined); // eslint-disable-line // If no valid entries found, return JSON.stringify of the input if (filteredEntries.length === 0) { return undefined; } return Object.fromEntries(filteredEntries); } if (Array.isArray(ex)) { // Case 3: Array of primitive values return ex.reduce((acc, value, index) => { acc[`Example${index + 1}`] = { value }; return acc; }, {}); } // Case 4: Single primitive value return ex ? { Example: { value: ex } } : undefined; }
@param {*} ex if the value - Is an Object with 'value' property like { 'value': 'example_val1', 'description': 'some description' } Returns >>> { 'Example': { 'value' : 'example_val1', 'description': 'some description' }, } - Is an object where each key represents a valid example object (i,e has a value property) { 'example1': { 'value' : 'example_val1', 'description': 'some description' }, 'example2': { 'value' : 'example_val2', 'description': 'some other description' }, 'invalid': { 'description': 'invalid example object without any value property' } } Returns >>> { 'example1': { 'value' : 'example_val1', 'description': 'some description' }, 'example2': { 'value' : 'example_val2', 'description': 'some other description' } } if none of the keys represents an object with 'value' property then return undefined - Is an array of premitive values ['example_val1', 'example_val2'] Returns >>> { 'Example1': {value:'value1'} 'Example2': {value:'value2'} } - Is a premitive value 'example_val1' Returns >>> { 'Example': { 'value': 'example_val1' } } - Is undefined returns undefined @returns
standardizeExample ( ex )
javascript
rapi-doc/RapiDoc
src/utils/schema-utils.js
https://github.com/rapi-doc/RapiDoc/blob/master/src/utils/schema-utils.js
MIT
var blobSupported = (function() { try { var a = new Blob(['hi']); return a.size === 2; } catch(e) { return false; } })();
Check if Blob constructor is supported
(anonymous) ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
var blobSupportsArrayBufferView = blobSupported && (function() { try { var b = new Blob([new Uint8Array([1,2])]); return b.size === 2; } catch(e) { return false; } })();
Check if Blob constructor supports ArrayBufferViews Fails in Safari 6, so we need to map to ArrayBuffers there.
(anonymous) ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
function mapArrayBufferViews(ary) { for (var i = 0; i < ary.length; i++) { var chunk = ary[i]; if (chunk.buffer instanceof ArrayBuffer) { var buf = chunk.buffer; // if this is a subarray, make a copy so we only // include the subarray region from the underlying buffer if (chunk.byteLength !== buf.byteLength) { var copy = new Uint8Array(chunk.byteLength); copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); buf = copy.buffer; } ary[i] = buf; } } }
Helper function that maps ArrayBufferViews to ArrayBuffers Used by BlobBuilder constructor and old browsers that didn't support it in the Blob constructor.
mapArrayBufferViews ( ary )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
exports.init = function() { var BrotliDecompressBuffer = require('./decode').BrotliDecompressBuffer; var compressed = base64.toByteArray(require('./dictionary.bin.js')); return BrotliDecompressBuffer(compressed); };
The normal dictionary-data.js is quite large, which makes it unsuitable for browser usage. In order to make it smaller, we read dictionary.bin, which is a compressed version of the dictionary, and on initial load, Brotli decompresses it's own dictionary. 😜
exports.init ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
function Zlib(mode) { if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) { throw new TypeError('Bad argument'); } this.dictionary = null; this.err = 0; this.flush = 0; this.init_done = false; this.level = 0; this.memLevel = 0; this.mode = mode; this.strategy = 0; this.windowBits = 0; this.write_in_progress = false; this.pending_close = false; this.gzip_id_bytes_read = 0; }
Emulate Node's zlib C++ layer for use by the JS layer in index.js
Zlib ( mode )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); }
Echos the value of a value. Trys to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Object} opts Optional options object that alters the output. /* legacy: obj, showHidden, depth, colors
inspect ( obj , opts )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
function clone(parent, circular, depth, prototype) { var filter; if (typeof circular === 'object') { depth = circular.depth; prototype = circular.prototype; filter = circular.filter; circular = circular.circular } // maintain two arrays for circular references, where corresponding parents // and children have the same index var allParents = []; var allChildren = []; var useBuffer = typeof Buffer != 'undefined'; if (typeof circular == 'undefined') circular = true; if (typeof depth == 'undefined') depth = Infinity; // recurse this function so we don't reset allParents and allChildren function _clone(parent, depth) { // cloning null always returns null if (parent === null) return null; if (depth == 0) return parent; var child; var proto; if (typeof parent != 'object') { return parent; } if (clone.__isArray(parent)) { child = []; } else if (clone.__isRegExp(parent)) { child = new RegExp(parent.source, __getRegExpFlags(parent)); if (parent.lastIndex) child.lastIndex = parent.lastIndex; } else if (clone.__isDate(parent)) { child = new Date(parent.getTime()); } else if (useBuffer && Buffer.isBuffer(parent)) { if (Buffer.allocUnsafe) { // Node.js >= 4.5.0 child = Buffer.allocUnsafe(parent.length); } else { // Older Node.js versions child = new Buffer(parent.length); } parent.copy(child); return child; } else { if (typeof prototype == 'undefined') { proto = Object.getPrototypeOf(parent); child = Object.create(proto); } else { child = Object.create(prototype); proto = prototype; } } if (circular) { var index = allParents.indexOf(parent); if (index != -1) { return allChildren[index]; } allParents.push(parent); allChildren.push(child); } for (var i in parent) { var attrs; if (proto) { attrs = Object.getOwnPropertyDescriptor(proto, i); } if (attrs && attrs.set == null) { continue; } child[i] = _clone(parent[i], depth - 1); } return child; } return _clone(parent, depth); }
Clones (copies) an Object using deep copying. This function supports circular references by default, but if you are certain there are no circular references in your object, you can save some CPU time by calling clone(obj, false). Caution: if `circular` is false and `parent` contains circular references, your program may enter an infinite loop and crash. @param `parent` - the object to be cloned @param `circular` - set to true if the object to be cloned may contain circular references. (optional - true by default) @param `depth` - set to a number if the object is only to be cloned to a particular depth. (optional - defaults to Infinity) @param `prototype` - sets the prototype to be used when cloning an object. (optional - defaults to parent prototype).
clone ( parent , circular , depth , prototype )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); },
Creates this cipher in encryption mode. @param {WordArray} key The key. @param {Object} cfg (Optional) The configuration options to use for this operation. @return {Cipher} A cipher instance. @static @example var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
createEncryptor ( key , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); },
Creates this cipher in decryption mode. @param {WordArray} key The key. @param {Object} cfg (Optional) The configuration options to use for this operation. @return {Cipher} A cipher instance. @static @example var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
createDecryptor ( key , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); },
Initializes a newly created cipher. @param {number} xformMode Either the encryption or decryption transormation mode constant. @param {WordArray} key The key. @param {Object} cfg (Optional) The configuration options to use for this operation. @example var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
init ( xformMode , key , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); },
Resets this cipher to its initial state. @example cipher.reset();
reset ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); },
Adds data to be encrypted or decrypted. @param {WordArray|string} dataUpdate The data to encrypt or decrypt. @return {WordArray} The data after processing. @example var encrypted = cipher.process('data'); var encrypted = cipher.process(wordArray);
process ( dataUpdate )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; },
Finalizes the encryption or decryption process. Note that the finalize operation is effectively a destructive, read-once operation. @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. @return {WordArray} The data after final processing. @example var encrypted = cipher.finalize(); var encrypted = cipher.finalize('data'); var encrypted = cipher.finalize(wordArray);
finalize ( dataUpdate )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
_createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }())
Creates shortcut functions to a cipher's object interface. @param {Cipher} cipher The cipher to create a helper for. @return {Object} An object with encrypt and decrypt shortcut functions. @static @example var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
_createHelper ( function ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); },
Creates this mode for encryption. @param {Cipher} cipher A block cipher instance. @param {Array} iv The IV words. @static @example var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
createEncryptor ( cipher , iv )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); },
Creates this mode for decryption. @param {Cipher} cipher A block cipher instance. @param {Array} iv The IV words. @static @example var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
createDecryptor ( cipher , iv )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; }
Initializes a newly created mode. @param {Cipher} cipher A block cipher instance. @param {Array} iv The IV words. @example var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
init ( cipher , iv )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); }
Processes the data block at offset. @param {Array} words The data words to operate on. @param {number} offset The offset where the block starts. @example mode.processBlock(data.words, offset);
processBlock ( words , offset )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); },
Pads data using the algorithm defined in PKCS #5/7. @param {WordArray} data The data to pad. @param {number} blockSize The multiple that the data should be padded to. @static @example CryptoJS.pad.Pkcs7.pad(wordArray, 4);
pad ( data , blockSize )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; }
Unpads data that had been padded using the algorithm defined in PKCS #5/7. @param {WordArray} data The data to unpad. @static @example CryptoJS.pad.Pkcs7.unpad(wordArray);
unpad ( data )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function (cipherParams) { this.mixIn(cipherParams); },
Initializes a newly created cipher params object. @param {Object} cipherParams An object with any of the possible cipher parameters. @example var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: ciphertextWordArray, key: keyWordArray, iv: ivWordArray, salt: saltWordArray, algorithm: CryptoJS.algo.AES, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.PKCS7, blockSize: 4, formatter: CryptoJS.format.OpenSSL });
init ( cipherParams )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
toString: function (formatter) { return (formatter || this.formatter).stringify(this); }
Converts this cipher params object to a string. @param {Format} formatter (Optional) The formatting strategy to use. @return {string} The stringified cipher params. @throws Error If neither the formatter nor the default formatter is set. @example var string = cipherParams + ''; var string = cipherParams.toString(); var string = cipherParams.toString(CryptoJS.format.OpenSSL);
toString ( formatter )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); },
Converts a cipher params object to an OpenSSL-compatible string. @param {CipherParams} cipherParams The cipher params object. @return {string} The OpenSSL-compatible string. @static @example var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
stringify ( cipherParams )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); }
Converts an OpenSSL-compatible string to a cipher params object. @param {string} openSSLStr The OpenSSL-compatible string. @return {CipherParams} The cipher params object. @static @example var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
parse ( openSSLStr )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); },
Encrypts a message. @param {Cipher} cipher The cipher algorithm to use. @param {WordArray|string} message The message to encrypt. @param {WordArray} key The key. @param {Object} cfg (Optional) The configuration options to use for this operation. @return {CipherParams} A cipher params object. @static @example var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
encrypt ( cipher , message , key , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; },
Decrypts serialized ciphertext. @param {Cipher} cipher The cipher algorithm to use. @param {CipherParams|string} ciphertext The ciphertext to decrypt. @param {WordArray} key The key. @param {Object} cfg (Optional) The configuration options to use for this operation. @return {WordArray} The plaintext. @static @example var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
decrypt ( cipher , ciphertext , key , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
_parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } }
Converts serialized ciphertext to CipherParams, else assumed CipherParams already and returns ciphertext unchanged. @param {CipherParams|string} ciphertext The ciphertext. @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. @return {CipherParams} The unserialized ciphertext. @static @example var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
_parse ( ciphertext , format )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); }
Derives a key and IV from a password. @param {string} password The password to derive from. @param {number} keySize The size in words of the key to generate. @param {number} ivSize The size in words of the IV to generate. @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. @return {CipherParams} A cipher params object with the key, IV, and salt. @static @example var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
execute ( password , keySize , ivSize , salt )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; },
Encrypts a message using a password. @param {Cipher} cipher The cipher algorithm to use. @param {WordArray|string} message The message to encrypt. @param {string} password The password. @param {Object} cfg (Optional) The configuration options to use for this operation. @return {CipherParams} A cipher params object. @static @example var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
encrypt ( cipher , message , password , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; }
Decrypts serialized ciphertext using a password. @param {Cipher} cipher The cipher algorithm to use. @param {CipherParams|string} ciphertext The ciphertext to decrypt. @param {string} password The password. @param {Object} cfg (Optional) The configuration options to use for this operation. @return {WordArray} The plaintext. @static @example var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
decrypt ( cipher , ciphertext , password , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }());
Configuration options. @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
SerializableCipher.cfg.extend ( { kdf : OpenSSLKdf } )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); }));
Configuration options. @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
Base.extend ( { format : OpenSSLFormatter } )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } if (this._mode && this._mode.__creator == modeCreator) { this._mode.init(this, iv && iv.words); } else { this._mode = modeCreator.call(mode, this, iv && iv.words); this._mode.__creator = modeCreator; } }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":195,"./evpkdf":198}],195:[function(require,module,exports){
Configuration options. @property {Mode} mode The block mode to use. Default: CBC @property {Padding} padding The padding strategy to use. Default: Pkcs7
Cipher.cfg.extend ( { mode : CBC , padding : Pkcs7 } )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; },
Creates a new object that inherits from this object. @param {Object} overrides Properties to copy into the new object. @return {Object} The new object. @static @example var MyType = CryptoJS.lib.Base.extend({ field: 'value', method: function () { } });
extend ( overrides )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; },
Extends this object and runs the init method. Arguments to create() will be passed to init(). @return {Object} The new object. @static @example var instance = MyType.create();
create ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function () { },
Initializes a newly created object. Override this method to add some logic when your objects are created. @example var MyType = CryptoJS.lib.Base.extend({ init: function () { // ... } });
init ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } },
Copies properties into this object. @param {Object} properties The properties to mix in. @example MyType.mixIn({ field: 'value' });
mixIn ( properties )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
clone: function () { return this.init.prototype.extend(this); }
Creates a copy of this object. @return {Object} The clone. @example var clone = instance.clone();
clone ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }());
Base object for prototypal inheritance.
(anonymous) ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } },
Initializes a newly created word array. @param {Array} words (Optional) An array of 32-bit words. @param {number} sigBytes (Optional) The number of significant bytes in the words. @example var wordArray = CryptoJS.lib.WordArray.create(); var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
init ( words , sigBytes )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
toString: function (encoder) { return (encoder || Hex).stringify(this); },
Converts this word array to a string. @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex @return {string} The stringified word array. @example var string = wordArray + ''; var string = wordArray.toString(); var string = wordArray.toString(CryptoJS.enc.Utf8);
toString ( encoder )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; },
Concatenates a word array to this word array. @param {WordArray} wordArray The word array to append. @return {WordArray} This word array. @example wordArray1.concat(wordArray2);
concat ( wordArray )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); },
Removes insignificant bits. @example wordArray.clamp();
clamp ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; },
Creates a copy of this word array. @return {WordArray} The clone. @example var clone = wordArray.clone();
clone ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } });
Creates a word array filled with random bytes. @param {number} nBytes The number of random bytes to generate. @return {WordArray} The random word array. @static @example var wordArray = CryptoJS.lib.WordArray.random(16);
random ( nBytes )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); },
Converts a word array to a hex string. @param {WordArray} wordArray The word array. @return {string} The hex string. @static @example var hexString = CryptoJS.enc.Hex.stringify(wordArray);
stringify ( wordArray )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); }
Converts a hex string to a word array. @param {string} hexStr The hex string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Hex.parse(hexString);
parse ( hexStr )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); },
Converts a word array to a Latin1 string. @param {WordArray} wordArray The word array. @return {string} The Latin1 string. @static @example var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
stringify ( wordArray )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); }
Converts a Latin1 string to a word array. @param {string} latin1Str The Latin1 string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
parse ( latin1Str )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } },
Converts a word array to a UTF-8 string. @param {WordArray} wordArray The word array. @return {string} The UTF-8 string. @static @example var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
stringify ( wordArray )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); }
Converts a UTF-8 string to a word array. @param {string} utf8Str The UTF-8 string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
parse ( utf8Str )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; },
Resets this block algorithm's data buffer to its initial state. @example bufferedBlockAlgorithm.reset();
reset ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
_append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; },
Adds new data to this block algorithm's buffer. @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. @example bufferedBlockAlgorithm._append('data'); bufferedBlockAlgorithm._append(wordArray);
_append ( data )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
_process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); },
Processes available data blocks. This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. @param {boolean} doFlush Whether all blocks and partial blocks should be processed. @return {WordArray} The processed data. @example var processedData = bufferedBlockAlgorithm._process(); var processedData = bufferedBlockAlgorithm._process(!!'flush');
_process ( doFlush )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; },
Creates a copy of this object. @return {Object} The clone. @example var clone = bufferedBlockAlgorithm.clone();
clone ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT