<commit_before>;(function($, window, document) {
    'use strict';

    /**
     * Get the value of a cookie with the given name
     * @param name
     * @returns {string|undefined}
     */
    $.getCookie = function(name) {
        var value = "; " + document.cookie,
            parts = value.split("; " + name + "=");

        if (parts.length == 2) {
            return parts.pop().split(";").shift();
        }
        return undefined;
    };

    /**
     * Remove a cookie with the provided name
     * @param name
     */
    $.removeCookie = function(name) {
        var basePath = window.csrfConfig.basePath || "/";
        document.cookie = name + '=; path=' + basePath + '; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    };

    var CSRF = {

        /**
         * Key including subshop and -path
         */
        storageKey: '__csrf_token-' + window.csrfConfig.shopId,

        /**
         * Temporary request callback store
         */
        pendingRequests: {},

        /**
         * Returns the token
         * @returns {string}
         */
        getToken: function() {
            return $.getCookie(this.storageKey);
        },

        /**
         * Checks if the token needs to be requested
         * @returns {boolean}
         */
        checkToken: function() {
            return $.getCookie('invalidate-xcsrf-token') === undefined && this.getToken() !== undefined;
        },

        /**
         * Creates a hidden input fields which holds the csrf information
         * @returns {HTMLElement}
         */
        createTokenField: function() {
            var me = this;

            return $('<input>', {
                'type': 'hidden',
                'name': '__csrf_token',
                'value': me.getToken()
            });
        },

        /**
         * Adds the token field to the given form
         * @param {HTMLElement} formElement
         */
        addTokenField: function(formElement) {
            formElement.append(CSRF.createTokenField());
        },

        /**
         *
         * @returns {HTMLElement[]}
         */
        getFormElements: function() {
            return $('form[method="post"]');
        },

        /**
         * Search all forms on the page and create or update their csrf input fields
         */
        updateForms: function() {
            var me = this,
                formElements = me.getFormElements();

            $.each(formElements, function(index, formElement) {
                var csrfInput;

                formElement = $(formElement);
                csrfInput = formElement.find('input[name="__csrf_token"]');

                if (csrfInput.length > 0) {
                    csrfInput.val(me.getToken());
                } else {
                    me.addTokenField(formElement);
                }
            });
        },

        /**
         * Modify every ajax request to add the X-CSRF-Token header
         */
        setupAjax: function() {
            var me = this,
                afterAjaxRequest = function() {
                    if (me.pendingRequests[this.url]) {
                        var request = me.pendingRequests[this.url];
                        request.callback.apply(request.context, arguments);
                    }

                    // to prevent timing issues, delay the update
                    window.setTimeout(function() {
                        me.updateForms();
                    }, 1);
                };

            $.ajaxSetup({
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-CSRF-Token', me.getToken());

                    if (typeof this.complete === 'function') {
                        me.pendingRequests[this.url] = {
                            context: this,
                            callback: this.complete
                        };
                    }

                    this.complete = afterAjaxRequest;
                }
            });
        },

        /**
         * Calls the frontend to retrieve a new csrf token and executes the afterInit on success
         */
        requestToken: function() {
            var me = this;

            $.ajax({
                url: window.csrfConfig.generateUrl,
                success: function(response, status, xhr) {
                    me.saveToken(xhr.getResponseHeader('x-csrf-token'));
                    $.removeCookie('invalidate-xcsrf-token');
                    me.afterInit();
                }
            });
        },

        /**
         * Save token into a cookie
         * @param token
         */
        saveToken: function(token) {
            var me = this,
                basePath = window.csrfConfig.basePath || "/";

            document.cookie = me.storageKey + "=" + token + "; path=" + basePath;
        },

        /**
         * Initialize the CSRF protection
         */
        init: function() {
            var me = this;

            if (me.checkToken()) {
                me.afterInit();
                return;
            }

            me.requestToken();
        },

        /**
         * Runs after a valid token is set
         */
        afterInit: function() {
            var me = this;

            me.updateForms();
            me.setupAjax();
        }

    };
<commit_msg>SW-15838 - Add events for CSRF jQuery plugin<commit_after>;(function($, window, document) {
    'use strict';

    /**
     * Get the value of a cookie with the given name
     * @param name
     * @returns {string|undefined}
     */
    $.getCookie = function(name) {
        var value = "; " + document.cookie,
            parts = value.split("; " + name + "=");

        if (parts.length == 2) {
            return parts.pop().split(";").shift();
        }
        return undefined;
    };

    /**
     * Remove a cookie with the provided name
     * @param name
     */
    $.removeCookie = function(name) {
        var basePath = window.csrfConfig.basePath || "/";
        document.cookie = name + '=; path=' + basePath + '; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    };

    var CSRF = {

        /**
         * Key including subshop and -path
         */
        storageKey: '__csrf_token-' + window.csrfConfig.shopId,

        /**
         * Temporary request callback store
         */
        pendingRequests: {},

        /**
         * Returns the token
         * @returns {string}
         */
        getToken: function() {
            return $.getCookie(this.storageKey);
        },

        /**
         * Checks if the token needs to be requested
         * @returns {boolean}
         */
        checkToken: function() {
            return $.getCookie('invalidate-xcsrf-token') === undefined && this.getToken() !== undefined;
        },

        /**
         * Creates a hidden input fields which holds the csrf information
         * @returns {HTMLElement}
         */
        createTokenField: function() {
            var me = this;

            return $('<input>', {
                'type': 'hidden',
                'name': '__csrf_token',
                'value': me.getToken()
            });
        },

        /**
         * Adds the token field to the given form
         * @param {HTMLElement} formElement
         */
        addTokenField: function(formElement) {
            formElement.append(CSRF.createTokenField());
            $.publish('plugin/swCsrfProtection/addTokenField', [ this, formElement ]);
        },

        /**
         *
         * @returns {HTMLElement[]}
         */
        getFormElements: function() {
            return $('form[method="post"]');
        },

        /**
         * Search all forms on the page and create or update their csrf input fields
         */
        updateForms: function() {
            var me = this,
                formElements = me.getFormElements();

            $.each(formElements, function(index, formElement) {
                var csrfInput;

                formElement = $(formElement);
                csrfInput = formElement.find('input[name="__csrf_token"]');

                if (csrfInput.length > 0) {
                    csrfInput.val(me.getToken());
                } else {
                    me.addTokenField(formElement);
                }
            });

            $.publish('plugin/swCsrfProtection/updateForms', [ this, formElements ]);
        },

        /**
         * Modify every ajax request to add the X-CSRF-Token header
         */
        setupAjax: function() {
            var me = this,
                token = me.getToken();

            $.ajaxSettings.headers = $.ajaxSettings.headers || {};
            $.ajaxSettings.headers['X-CSRF-Token'] = token;

            $.publish('plugin/swCsrfProtection/setupAjax', [ this, token ]);
        },

        /**
         * Calls the frontend to retrieve a new csrf token and executes the afterInit on success
         */
        requestToken: function() {
            var me = this;

            $.ajax({
                url: window.csrfConfig.generateUrl,
                success: function(response, status, xhr) {
                    me.saveToken(xhr.getResponseHeader('x-csrf-token'));
                    $.removeCookie('invalidate-xcsrf-token');
                    $.publish('plugin/swCsrfProtection/requestToken', [ me, me.getToken() ]);
                    me.afterInit();
                }
            });
        },

        /**
         * Save token into a cookie
         * @param token
         */
        saveToken: function(token) {
            var me = this,
                basePath = window.csrfConfig.basePath || "/";

            document.cookie = me.storageKey + "=" + token + "; path=" + basePath;
        },

        /**
         * Initialize the CSRF protection
         */
        init: function() {
            var me = this;

            if (me.checkToken()) {
                me.afterInit();
                return;
            }

            me.requestToken();
        },

        /**
         * Runs after a valid token is set
         */
        afterInit: function() {
            var me = this;

            me.updateForms();
            me.setupAjax();

            $.publish('plugin/swCsrfProtection/init', [ me ]);
        }

    };

{'fraction_non_alphanumeric': 0.12300039016777214, 'fraction_numerical': 0.003316426063207179, 'mean_word_length': 1.2881053336308859, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6543790', 'n_tokens_mistral': 2744, 'n_tokens_neox': 2593, 'n_words': 603}