{"version":3,"file":"index.cjs","sources":["../package.json","../src/index.ts"],"sourcesContent":["{\n  \"name\": \"@jspsych/plugin-browser-check\",\n  \"version\": \"2.1.0\",\n  \"description\": \"jsPsych plugin for checking browser features\",\n  \"type\": \"module\",\n  \"main\": \"dist/index.cjs\",\n  \"exports\": {\n    \"import\": \"./dist/index.js\",\n    \"require\": \"./dist/index.cjs\"\n  },\n  \"typings\": \"dist/index.d.ts\",\n  \"unpkg\": \"dist/index.browser.min.js\",\n  \"files\": [\n    \"src\",\n    \"dist\"\n  ],\n  \"source\": \"src/index.ts\",\n  \"scripts\": {\n    \"test\": \"jest\",\n    \"test:watch\": \"npm test -- --watch\",\n    \"tsc\": \"tsc\",\n    \"build\": \"rollup --config\",\n    \"build:watch\": \"npm run build -- --watch\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/jspsych/jsPsych.git\",\n    \"directory\": \"packages/plugin-html-keyboard-response\"\n  },\n  \"author\": \"Josh de Leeuw\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/jspsych/jsPsych/issues\"\n  },\n  \"homepage\": \"https://www.jspsych.org/latest/plugins/html-keyboard-response\",\n  \"peerDependencies\": {\n    \"jspsych\": \">=7.1.0\"\n  },\n  \"devDependencies\": {\n    \"@jspsych/config\": \"^3.2.0\",\n    \"@jspsych/test-utils\": \"^1.2.0\"\n  },\n  \"dependencies\": {\n    \"detect-browser\": \"^5.2.1\"\n  }\n}\n","import { detect } from \"detect-browser\";\nimport { JsPsych, JsPsychPlugin, ParameterType, TrialType } from \"jspsych\";\n\nimport { version } from \"../package.json\";\n\nconst info = <const>{\n  name: \"browser-check\",\n  version: version,\n  parameters: {\n    /**\n     * The list of browser features to record. The default value includes all of the available options.\n     */\n    features: {\n      type: ParameterType.STRING,\n      array: true,\n      default: [\n        \"width\",\n        \"height\",\n        \"webaudio\",\n        \"browser\",\n        \"browser_version\",\n        \"mobile\",\n        \"os\",\n        \"fullscreen\",\n        \"vsync_rate\",\n        \"webcam\",\n        \"microphone\",\n      ],\n    },\n    /**\n     * Any features listed here will be skipped, even if they appear in `features`. Use this when you want to run most of the defaults.\n     */\n    skip_features: {\n      type: ParameterType.STRING,\n      array: true,\n      default: [],\n    },\n    /**\n     * The number of frames to sample when measuring the display refresh rate (`\"vsync_rate\"`).\n     * Increasing the number will potenially improve the stability of the estimate at the cost of\n     * increasing the amount of time the plugin takes during this test. On most devices, 60 frames takes\n     * about 1 second to measure.\n     */\n    vsync_frame_count: {\n      type: ParameterType.INT,\n      default: 60,\n    },\n    /**\n     * Whether to allow the participant to resize the browser window if the window is smaller than `minimum_width`\n     * and/or `minimum_height`. If `false`, then the `minimum_width` and `minimum_height` parameters are ignored\n     * and you can validate the size in the `inclusion_function`.\n     */\n    allow_window_resize: {\n      type: ParameterType.BOOL,\n      default: true,\n    },\n    /**\n     * If `allow_window_resize` is `true`, then this is the minimum width of the window (in pixels)\n     * that must be met before continuing.\n     */\n    minimum_width: {\n      type: ParameterType.INT,\n      default: 0,\n    },\n    /**\n     * If `allow_window_resize` is `true`, then this is the minimum height of the window (in pixels) that\n     * must be met before continuing.\n     */\n    minimum_height: {\n      type: ParameterType.INT,\n      default: 0,\n    },\n    /**\n     * The message that will be displayed during the interactive resize when `allow_window_resize` is `true`\n     * and the window is too small. If the message contains HTML elements with the special IDs `browser-check-min-width`,\n     * `browser-check-min-height`, `browser-check-actual-height`, and/or `browser-check-actual-width`, then the\n     * contents of those elements will be dynamically updated to reflect the `minimum_width`, `minimum_height` and\n     * measured width and height of the browser.\n     * The default message is:\n     * `<p>Your browser window is too small to complete this experiment. Please maximize the size of your browser window. If your browser window is already maximized, you will not be able to complete this experiment.</p>\n     * <p>The minimum window width is <span id=\"browser-check-min-width\"></span> px.</p>\n     * <p>Your current window width is <span id=\"browser-check-actual-width\"></span> px.</p>\n     * <p>The minimum window height is <span id=\"browser-check-min-height\"></span> px.</p>\n     * <p>Your current window height is <span id=\"browser-check-actual-height\"></span> px.</p>`.\n     */\n    window_resize_message: {\n      type: ParameterType.HTML_STRING,\n      default: `<p>Your browser window is too small to complete this experiment. Please maximize the size of your browser window. \n        If your browser window is already maximized, you will not be able to complete this experiment.</p>\n        <p>The minimum window width is <span id=\"browser-check-min-width\"></span> px.</p>\n        <p>Your current window width is <span id=\"browser-check-actual-width\"></span> px.</p>\n        <p>The minimum window height is <span id=\"browser-check-min-height\"></span> px.</p>\n        <p>Your current window height is <span id=\"browser-check-actual-height\"></span> px.</p>`,\n    },\n    /**\n     * During the interactive resize, a button with this text will be displayed below the\n     * `window_resize_message` for the participant to click if the window cannot meet the\n     * minimum size needed. When the button is clicked, the experiment will end and\n     * `exclusion_message` will be displayed.\n     */\n    resize_fail_button_text: {\n      type: ParameterType.STRING,\n      default: \"I cannot make the window any larger\",\n    },\n    /**\n     * A function that evaluates to `true` if the browser meets all of the inclusion criteria\n     * for the experiment, and `false` otherwise. The first argument to the function will be\n     * an object containing key value pairs with the measured features of the browser. The\n     * keys will be the same as those listed in `features`.\n     */\n    inclusion_function: {\n      type: ParameterType.FUNCTION,\n      default: () => {\n        return true;\n      },\n    },\n    /**\n     * A function that returns the message to display if `inclusion_function` evaluates to `false` or if the participant\n     * clicks on the resize fail button during the interactive resize. In order to allow customization of the message,\n     * the first argument to the function will be an object containing key value pairs with the measured features of the\n     * browser. The keys will be the same as those listed in `features`. See example below.\n     */\n    exclusion_message: {\n      type: ParameterType.FUNCTION,\n      default: () => {\n        return `<p>Your browser does not meet the requirements to participate in this experiment.</p>`;\n      },\n    },\n  },\n  data: {\n    /** The width of the browser window in pixels. If interactive resizing happens, this is the width *after* resizing. */\n    width: {\n      type: ParameterType.INT,\n    },\n    /** The height of the browser window in pixels. If interactive resizing happens, this is the height *after* resizing.*/\n    height: {\n      type: ParameterType.INT,\n    },\n    /** The browser used. */\n    browser: {\n      type: ParameterType.STRING,\n    },\n    /** The version of the browser used. */\n    browser_version: {\n      type: ParameterType.STRING,\n    },\n    /** The operating system used. */\n    os: {\n      type: ParameterType.STRING,\n    },\n    /** Whether the browser is a mobile device. */\n    mobile: {\n      type: ParameterType.BOOL,\n    },\n    /** Whether the browser supports the WebAudio API. */\n    webaudio: {\n      type: ParameterType.BOOL,\n    },\n    /** Whether the browser supports the Fullscreen API. */\n    fullscreen: {\n      type: ParameterType.BOOL,\n    },\n    /** An estimate of the refresh rate of the screen, in frames per second. */\n    vsync_rate: {\n      type: ParameterType.FLOAT,\n    },\n    /** Whether there is a webcam device available. Note that the participant still must grant permission to access the device before it can be used. */\n    webcam: {\n      type: ParameterType.BOOL,\n    },\n    /** Whether there is an audio input device available. Note that the participant still must grant permission to access the device before it can be used. */\n    microphone: {\n      type: ParameterType.BOOL,\n    },\n  },\n  // prettier-ignore\n  citations: '__CITATIONS__',\n};\n\ntype Info = typeof info;\n\n/**\n * This plugin measures and records various features of the participant's browser and can end the experiment if defined inclusion criteria are not met.\n *\n * The plugin currently can record the following features:\n *\n * The width and height of the browser window in pixels.\n * The type of browser used (e.g., Chrome, Firefox, Edge, etc.) and the version number of the browser.*\n * Whether the participant is using a mobile device.*\n * The operating system.*\n * Support for the WebAudio API.\n * Support for the Fullscreen API, e.g., through the [fullscreen plugin](../plugins/fullscreen.md).\n * The display refresh rate in frames per second.\n * Whether the device has a webcam and microphone. Note that this only reveals whether a webcam/microphone exists. The participant still needs to grant permission in order for the experiment to use these devices.\n *\n * !!! warning\n *     Features with an * are recorded by parsing the [user agent string](https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent).\n *     This method is accurate most of the time, but is not guaranteed to be correct.\n *     The plugin uses the [detect-browser package](https://github.com/DamonOehlman/detect-browser) to perform user agent parsing.\n *     You can find a list of supported browsers and OSes in the [source file](https://github.com/DamonOehlman/detect-browser/blob/master/src/index.ts).\n *\n * The plugin begins by measuring the set of features requested.\n * An inclusion function is evaluated to see if the paricipant passes the inclusion criteria.\n * If they do, then the trial ends and the experiment continues.\n * If they do not, then the experiment ends immediately.\n * If a minimum width and/or minimum height is desired, the plugin will optionally display a message to participants whose browser windows are too small to give them an opportunity to make the window larger if possible.\n * See the examples below for more guidance.\n * @author Josh de Leeuw\n * @see {@link https://www.jspsych.org/latest/plugins/browser-check/ browser-check plugin documentation on jspsych.org}\n */\nclass BrowserCheckPlugin implements JsPsychPlugin<Info> {\n  static info = info;\n  private end_flag = false;\n  private t: TrialType<Info>;\n\n  constructor(private jsPsych: JsPsych) {}\n\n  private delay(ms: number) {\n    return new Promise((resolve) => setTimeout(resolve, ms));\n  }\n\n  trial(display_element: HTMLElement, trial: TrialType<Info>) {\n    this.t = trial;\n\n    const featureCheckFunctionsMap = this.create_feature_fn_map(trial);\n\n    const features_to_check = trial.features.filter((x) => !trial.skip_features.includes(x));\n\n    this.run_trial(featureCheckFunctionsMap, features_to_check);\n  }\n\n  private async run_trial(fnMap, features) {\n    const feature_data = await this.measure_features(fnMap, features);\n\n    const include = await this.inclusion_check(this.t.inclusion_function, feature_data);\n\n    if (include) {\n      this.end_trial(feature_data);\n    } else {\n      this.end_experiment(feature_data);\n    }\n  }\n\n  private create_feature_fn_map(trial) {\n    return new Map<string, () => any>(\n      Object.entries({\n        width: () => {\n          return window.innerWidth;\n        },\n        height: () => {\n          return window.innerHeight;\n        },\n        webaudio: () => {\n          if (\n            window.AudioContext ||\n            // @ts-ignore because prefixed not in document type\n            window.webkitAudioContext ||\n            // @ts-ignore because prefixed not in document type\n            window.mozAudioContext ||\n            // @ts-ignore because prefixed not in document type\n            window.oAudioContext ||\n            // @ts-ignore because prefixed not in document type\n            window.msAudioContext\n          ) {\n            return true;\n          } else {\n            return false;\n          }\n        },\n        browser: () => {\n          return detect().name;\n        },\n        browser_version: () => {\n          return detect().version;\n        },\n        mobile: () => {\n          return /Mobi/i.test(window.navigator.userAgent);\n        },\n        os: () => {\n          return detect().os;\n        },\n        fullscreen: () => {\n          if (\n            document.exitFullscreen ||\n            // @ts-ignore because prefixed not in document type\n            document.webkitExitFullscreen ||\n            // @ts-ignore because prefixed not in document type\n            document.msExitFullscreen\n          ) {\n            return true;\n          } else {\n            return false;\n          }\n        },\n        vsync_rate: () => {\n          return new Promise((resolve) => {\n            let t0 = performance.now();\n            let deltas = [];\n            let framesToRun = trial.vsync_frame_count;\n            const finish = () => {\n              let sum = 0;\n              for (const v of deltas) {\n                sum += v;\n              }\n              const frame_rate = 1000.0 / (sum / deltas.length);\n              const frame_rate_two_sig_dig = Math.round(frame_rate * 100) / 100;\n              resolve(frame_rate_two_sig_dig);\n            };\n            const nextFrame = () => {\n              let t1 = performance.now();\n              deltas.push(t1 - t0);\n              t0 = t1;\n              framesToRun--;\n              if (framesToRun > 0) {\n                requestAnimationFrame(nextFrame);\n              } else {\n                finish();\n              }\n            };\n            const start = () => {\n              t0 = performance.now();\n              requestAnimationFrame(nextFrame);\n            };\n            requestAnimationFrame(start);\n          });\n        },\n        webcam: () => {\n          return new Promise((resolve, reject) => {\n            if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {\n              resolve(false);\n            }\n            navigator.mediaDevices.enumerateDevices().then((devices) => {\n              const webcams = devices.filter((d) => {\n                return d.kind == \"videoinput\";\n              });\n              if (webcams.length > 0) {\n                resolve(true);\n              } else {\n                resolve(false);\n              }\n            });\n          });\n        },\n        microphone: () => {\n          return new Promise((resolve, reject) => {\n            if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {\n              resolve(false);\n            }\n            navigator.mediaDevices.enumerateDevices().then((devices) => {\n              const microphones = devices.filter((d) => {\n                return d.kind == \"audioinput\";\n              });\n              if (microphones.length > 0) {\n                resolve(true);\n              } else {\n                resolve(false);\n              }\n            });\n          });\n        },\n      })\n    );\n  }\n\n  private async measure_features(fnMap, features_to_check) {\n    const feature_data = new Map<string, any>();\n    const feature_checks: Promise<void>[] = [];\n\n    for (const feature of features_to_check) {\n      // this allows for feature check functions to be sync or async\n      feature_checks.push(Promise.resolve(fnMap.get(feature)()));\n    }\n\n    const results = await Promise.allSettled(feature_checks);\n\n    for (let i = 0; i < features_to_check.length; i++) {\n      if (results[i].status === \"fulfilled\") {\n        // @ts-expect-error because .value isn't recognized for some reason\n        feature_data.set(features_to_check[i], results[i].value);\n      } else {\n        feature_data.set(features_to_check[i], null);\n      }\n    }\n\n    return feature_data;\n  }\n\n  private async inclusion_check(fn, data) {\n    await this.check_allow_resize(data);\n\n    // screen was too small\n    if (this.end_flag) {\n      return false;\n    }\n\n    return fn(Object.fromEntries(data));\n  }\n\n  private async check_allow_resize(feature_data) {\n    const display_element = this.jsPsych.getDisplayElement();\n    const w = feature_data.get(\"width\");\n    const h = feature_data.get(\"height\");\n\n    if (\n      this.t.allow_window_resize &&\n      (w || h) &&\n      (this.t.minimum_width > 0 || this.t.minimum_height > 0)\n    ) {\n      display_element.innerHTML =\n        this.t.window_resize_message +\n        `<p><button id=\"browser-check-max-size-btn\" class=\"jspsych-btn\">${this.t.resize_fail_button_text}</button></p>`;\n\n      display_element.querySelector(\"#browser-check-max-size-btn\").addEventListener(\"click\", () => {\n        display_element.innerHTML = \"\";\n        this.end_flag = true;\n      });\n\n      const min_width_el = display_element.querySelector(\"#browser-check-min-width\");\n      const min_height_el = display_element.querySelector(\"#browser-check-min-height\");\n      const actual_height_el = display_element.querySelector(\"#browser-check-actual-height\");\n      const actual_width_el = display_element.querySelector(\"#browser-check-actual-width\");\n\n      while (\n        !this.end_flag &&\n        (window.innerWidth < this.t.minimum_width || window.innerHeight < this.t.minimum_height)\n      ) {\n        if (min_width_el) {\n          min_width_el.innerHTML = this.t.minimum_width.toString();\n        }\n\n        if (min_height_el) {\n          min_height_el.innerHTML = this.t.minimum_height.toString();\n        }\n\n        if (actual_height_el) {\n          actual_height_el.innerHTML = window.innerHeight.toString();\n        }\n\n        if (actual_width_el) {\n          actual_width_el.innerHTML = window.innerWidth.toString();\n        }\n\n        await this.delay(100);\n\n        feature_data.set(\"width\", window.innerWidth);\n        feature_data.set(\"height\", window.innerHeight);\n      }\n    }\n  }\n\n  private end_trial(feature_data) {\n    const trial_data = { ...Object.fromEntries(feature_data) };\n\n    this.jsPsych.finishTrial(trial_data);\n  }\n\n  private end_experiment(feature_data) {\n    this.jsPsych.getDisplayElement().innerHTML = \"\";\n\n    const trial_data = { ...Object.fromEntries(feature_data) };\n\n    this.jsPsych.abortExperiment(this.t.exclusion_message(trial_data), trial_data);\n  }\n\n  simulate(\n    trial: TrialType<Info>,\n    simulation_mode,\n    simulation_options: any,\n    load_callback: () => void\n  ) {\n    if (simulation_mode == \"data-only\") {\n      load_callback();\n      this.simulate_data_only(trial, simulation_options);\n    }\n    if (simulation_mode == \"visual\") {\n      this.simulate_visual(trial, simulation_options, load_callback);\n    }\n  }\n\n  private async create_simulation_data(trial: TrialType<Info>, simulation_options) {\n    const featureCheckFunctionsMap = this.create_feature_fn_map(trial);\n    // measure everything except vsync, which we just fake.\n    const features_to_check = trial.features.filter((x) => !trial.skip_features.includes(x));\n\n    const feature_data = await this.measure_features(\n      featureCheckFunctionsMap,\n      features_to_check.filter((x) => x !== \"vsync_rate\")\n    );\n    if (features_to_check.includes(\"vsync_rate\")) {\n      feature_data.set(\"vsync_rate\", 60);\n    }\n\n    const default_data = Object.fromEntries(feature_data);\n\n    const data = this.jsPsych.pluginAPI.mergeSimulationData(default_data, simulation_options);\n\n    // don't think this is necessary for this plugin...\n    // this.jsPsych.pluginAPI.ensureSimulationDataConsistency(trial, data);\n\n    return data;\n  }\n\n  private simulate_data_only(trial: TrialType<Info>, simulation_options) {\n    this.create_simulation_data(trial, simulation_options).then((data) => {\n      if (trial.allow_window_resize) {\n        if (data.width < trial.minimum_width) {\n          data.width = trial.minimum_width;\n        }\n        if (data.height < trial.minimum_height) {\n          data.height = trial.minimum_height;\n        }\n      }\n\n      // check inclusion function\n      if (trial.inclusion_function(data)) {\n        this.jsPsych.finishTrial(data);\n      } else {\n        this.jsPsych.abortExperiment(trial.exclusion_message(data), data);\n      }\n    });\n  }\n\n  private simulate_visual(trial: TrialType<Info>, simulation_options, load_callback: () => void) {\n    this.t = trial;\n    load_callback();\n    this.create_simulation_data(trial, simulation_options).then((data) => {\n      const feature_data = new Map(Object.entries(data));\n      // run inclusion_check\n      // if the window size is big enough or the user resizes it within 3 seconds,\n      // then the plugin's trial code will finish up the trial.\n      // otherwise we simulate clicking the button and then the code above should\n      // finish it up too.\n\n      setTimeout(() => {\n        const btn = document.querySelector(\"#browser-check-max-size-btn\");\n        if (btn) {\n          this.jsPsych.pluginAPI.clickTarget(btn);\n        }\n      }, 3000);\n\n      this.inclusion_check(this.t.inclusion_function, feature_data).then((include) => {\n        if (include) {\n          this.end_trial(feature_data);\n        } else {\n          this.end_experiment(feature_data);\n        }\n      });\n    });\n  }\n}\n\nexport default BrowserCheckPlugin;\n"],"names":[],"mappings":";;;;;AAEE,IAAW,OAAA,GAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EC8KA,SAAA,EAAA;AAAA;;GAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}