### trackSessionStart Source: https://constructor-io.github.io/constructorio-client-javascript/module-tracker.html Sends a session start event to the API. This method should be called to initiate tracking for a user's session. ```APIDOC ## trackSessionStart(networkParametersopt) ### Description Sends a session start event to the API. This method should be called to initiate tracking for a user's session. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters: * **networkParameters** (object) - Optional - Parameters relevant to the network request. * **timeout** (number) - Optional - Request timeout in milliseconds. ### Request Example ```javascript constructorio.tracker.trackSessionStart(); ``` ### Response #### Success Response Returns `true` on success. #### Error Response Returns an `Error` object on failure. #### Response Example ```json true ``` ``` -------------------------------- ### Track Session Start (v2) Source: https://constructor-io.github.io/constructorio-client-javascript/modules_tracker.js.html Sends a session start event to the Constructor.io API using the v2 endpoint. This method is typically called automatically when the tracker is initialized or when a new session begins. It queues the request for sending. ```javascript trackSessionStartV2(networkParameters = {}) { const url = `${this.options.serviceUrl}/v2/behavioral_action/session_start?`; this.requests.queue(`${url}${applyParamsAsString({}, this.options)}`, 'POST', undefined, networkParameters); this.requests.send(); return true; } ``` -------------------------------- ### Track Session Start Source: https://constructor-io.github.io/constructorio-client-javascript/modules_tracker.js.html Sends a session start event to the Constructor.io API. This is a primary method for initiating session tracking. It queues the request to be sent via the request queue. ```javascript trackSessionStart() { // This method is intended to be implemented or called. // The actual implementation would likely queue a request similar to trackSessionStartV2. // Example placeholder: // const url = `${this.options.serviceUrl}/v1/behavioral_action/session_start?`; // this.requests.queue(`${url}${applyParamsAsString({}, this.options)}`, 'POST'); // this.requests.send(); // return true; } ``` -------------------------------- ### Track Session Start Event Source: https://constructor-io.github.io/constructorio-client-javascript/module-tracker.html Call this method to send a session start event to the Constructor.io API. It can optionally accept network parameters like timeout. ```javascript constructorio.tracker.trackSessionStart(); ``` -------------------------------- ### trackSessionStartV2 Source: https://constructor-io.github.io/constructorio-client-javascript/modules_tracker.js.html Send session start event to API. This method is intended for internal use and is marked as private. ```APIDOC ## trackSessionStartV2 ### Description Send session start event to API. This method is intended for internal use and is marked as private. ### Method POST ### Endpoint /v2/behavioral_action/session_start ### Parameters #### Network Parameters - **timeout** (number) - Optional - Request timeout (in milliseconds) ### Request Example ```javascript constructorio.tracker.trackSessionStartV2(); ``` ### Response #### Success Response (200) - Returns `true` on successful queuing of the request. #### Response Example ```json true ``` ``` -------------------------------- ### Track Session Start Source: https://constructor-io.github.io/constructorio-client-javascript/modules_tracker.js.html Initiates a tracking session by sending a 'session_start' event to the Constructor.io API. This is typically called automatically when the tracker is initialized. ```javascript trackSessionStart(networkParameters = {}) { const url = `${this.options.serviceUrl}/behavior?`; const queryParams = { action: 'session_start' }; this.requests.queue(`${url}${applyParamsAsString(queryParams, this.options)}`, undefined, undefined, networkParameters); this.requests.send(); return true; } ``` -------------------------------- ### trackAgentResultLoadStarted Source: https://constructor-io.github.io/constructorio-client-javascript/modules_tracker.js.html Logs the event when the agent results page has started loading. This is called before the content is fully loaded. ```APIDOC ## POST /v2/behavioral_action/assistant_result_load_start ### Description Logs the event when the agent results page has started loading. This is called before the content is fully loaded. ### Method POST ### Endpoint /v2/behavioral_action/assistant_result_load_start ### Parameters #### Request Body - **intent** (string) - Required - Intent of user request - **section** (string) - Optional - The section name for the item Ex. "Products" - **intentResultId** (string) - Optional - The intent result id from the ASA response ### Request Example { "intent": "show me a recipe for a cookie", "intentResultId": "Zde93fd-f955-4020-8b8d-6b21b93cb5a2" } ### Response #### Success Response (200) - **success** (boolean) - Indicates if the tracking event was successful #### Response Example { "success": true } ``` -------------------------------- ### Get Browse Results Source: https://constructor-io.github.io/constructorio-client-javascript/modules_browse.js.html Retrieves browse results from the Constructor.io API. Supports various parameters for pagination, filtering, sorting, and formatting. ```javascript /** * Retrieve browse results from API * * @function getBrowseResults * @description Retrieve browse results from Constructor.io API * @param {string} filterName - Filter name to display results from * @param {string} filterValue - Filter value to display results from * @param {object} [parameters] - Additional parameters to refine result set * @param {number} [parameters.page] - The page number of the results (Can't be used together with offset) * @param {number} [parameters.offset] - The number of results to skip from the beginning (Can't be used together with page) * @param {number} [parameters.resultsPerPage] - The number of results per page to return * @param {object} [parameters.filters] - Key / value mapping (dictionary) of filters used to refine results * @param {string} [parameters.sortBy='relevance'] - The sort method for results * @param {string} [parameters.sortOrder='descending'] - The sort order for results * @param {string} [parameters.section='Products'] - The section name for results * @param {object} [parameters.fmtOptions] - The format options used to refine result groups. Please refer to https://docs.constructor.com/reference/browse-browse-results for details * @param {object} [parameters.preFilterExpression] - Faceting expression to scope browse results. Please refer to https://docs.constructor.com/reference/configuration-collections * @param {string[]} [parameters.hiddenFields] - Hidden metadata fields to return * @param {string[]} [parameters.hiddenFacets] - Hidden facets to return * @param {object} [parameters.variationsMap] - The variations map object to aggregate variations. Please refer to https://docs.constructor.com/reference/shared-variations-mapping for details * @param {object} [parameters.qsParam] - Parameters listed above can be serialized into a JSON object and parsed through this parameter. Please refer to https://docs.constructor.com/reference/browse-browse-results * @param {object} [parameters.filterMatchTypes] - An object specifying whether results must match `all`, `any` or `none` of a given filter. Please refer to https://docs.constructor.com/reference/v1-browse-get-browse-results * @param {object} [networkParameters] - Parameters relevant to the network request * @param {number} [networkParameters.timeout] - Request timeout (in milliseconds) * @returns {Promise} */ ``` -------------------------------- ### Get Recommendations Source: https://constructor-io.github.io/constructorio-client-javascript/module-recommendations.html Retrieve recommendation results from the Constructor.io API for a given pod ID. Supports refining results with parameters like number of results, filters, and item IDs. ```javascript constructorio.recommendations.getRecommendations('t-shirt-best-sellers', { numResults: 5, filters: { size: 'medium' }, }); ``` -------------------------------- ### Track Agent Result Load Started Source: https://constructor-io.github.io/constructorio-client-javascript/module-tracker.html Indicate the beginning of the agent results page load. This should be called before the results are fully loaded. ```javascript constructorio.tracker.trackAgentResultLoadStarted( { intent: 'show me a recipe for a cookie', intentResultId: 'Zde93fd-f955-4020-8b8d-6b21b93cb5a2', }, ); ``` -------------------------------- ### Get Search Results Source: https://constructor-io.github.io/constructorio-client-javascript/module-search.html Retrieve standard search results from the Constructor.io API. Use this for typical search queries, allowing for refinement through various parameters like filters, pagination, and sorting. ```javascript constructorio.search.getSearchResults('t-shirt', { resultsPerPage: 40, filters: { size: 'medium' }, filterMatchTypes: { size: 'all' } }); ``` -------------------------------- ### Track Assistant Result Load Started Source: https://constructor-io.github.io/constructorio-client-javascript/modules_tracker.js.html Call this method when the process of loading assistant search results begins, but before they are fully loaded. It requires the user's intent and optionally an intent result ID. ```javascript constructorio.tracker.trackAssistantResultLoadStarted({ intent: 'show me a recipe for a cookie', intentResultId: 'Zde93fd-f955-4020-8b8d-6b21b93cb5a2', }); ``` -------------------------------- ### Get Quiz Results Configuration Source: https://constructor-io.github.io/constructorio-client-javascript/module-quizzes.html Retrieve quiz results page configuration from the Constructor.io API. Pass the quiz ID and optional parameters like quiz version ID. ```javascript constructorio.quizzes.getQuizResultsConfig('quizId', { quizVersionId: '123' }); ``` -------------------------------- ### Get Browse Results Source: https://constructor-io.github.io/constructorio-client-javascript/module-browse.html Retrieve browse results from the Constructor.io API based on a specified filter name and value. Allows for advanced filtering and pagination. ```javascript constructorio.browse.getBrowseResults('group_id', 't-shirts', { resultsPerPage: 40, filters: { size: 'medium' }, filterMatchTypes: { size: 'all' } }); ``` -------------------------------- ### Track Assistant Result Load Started Source: https://constructor-io.github.io/constructorio-client-javascript/module-tracker.html Call this method when the assistant's results page load has begun. This method is deprecated and will be removed in a future version; use trackAgentResultLoadStarted instead. ```javascript constructorio.tracker.trackAssistantResultLoadStarted( { intent: 'show me a recipe for a cookie', intentResultId: 'Zde93fd-f955-4020-8b8d-6b21b93cb5a2', }, ); ``` -------------------------------- ### Initialize Constructor.io Client with User Information and Tracking Options Source: https://constructor-io.github.io/constructorio-client-javascript/constructorio.js.html Instantiate the Constructor.io client with user-specific parameters like segments, test cells, client ID, session ID, and user ID. Also includes options for configuring tracking event behavior. ```javascript const constructorio = require('@constructor-io/constructorio'); const constructorioClient = new constructorio({ apiKey: 'YOUR_API_KEY', segments: ['summer', 'sale'], testCells: { 'feature-A': '1', 'feature-B': '2' }, clientId: 'YOUR_CLIENT_ID', sessionId: 1, userId: 'YOUR_USER_ID', trackingSendDelay: 500, sendReferrerWithTrackingEvents: false, sendTrackingEvents: true }); ``` -------------------------------- ### Get Agent Results Stream Source: https://constructor-io.github.io/constructorio-client-javascript/module-agent.html Retrieve a stream of agent results from the Constructor.io API. Use this method to get real-time results for agent-based queries. ```javascript const readableStream = constructorio.agent.getAgentResultsStream('I want to get shoes', { domain: "nike_sportswear", }); const reader = readableStream.getReader(); const { value, done } = await reader.read(); ``` -------------------------------- ### Initialize ConstructorIO Client Source: https://constructor-io.github.io/constructorio-client-javascript/constructorio.js.html Initialize the ConstructorIO client with your API key and other options. This is the first step before making any API calls. ```javascript const ConstructorIO = require('@constructor-io/constructorio'); const cokieClient = new ConstructorIO({ apiKey: 'YOUR_API_KEY' }); const searchClient = new ConstructorIO({ apiKey: 'YOUR_API_KEY', serviceUrl: 'https://ac.cnstr.io' }); ``` -------------------------------- ### ConstructorIO Client Instantiation Source: https://constructor-io.github.io/constructorio-client-javascript/ConstructorIO.html Instantiate the ConstructorIO client with API key and other optional parameters. ```APIDOC ## new ConstructorIO(parameters) ### Description Class to instantiate the ConstructorIO client. ### Parameters #### Parameters - **parameters** (object) - Parameters for client instantiation - **apiKey** (string) - Constructor.io API key - **serviceUrl** (string) - Optional - API URL endpoint (default: 'https://ac.cnstrc.com') - **quizzesServiceUrl** (string) - Optional - Quizzes API URL endpoint (default: 'https://quizzes.cnstrc.com') - **agentServiceUrl** (string) - Optional - AI Shopping Agent API URL endpoint (default: 'https://agent.cnstrc.com') - **mediaServiceUrl** (string) - Optional - Media API URL endpoint (default: 'https://media-cnstrc.com') - **assistantServiceUrl** (string) - Optional - AI Shopping Assistant API URL endpoint (deprecated, use agentServiceUrl instead) - **segments** (array) - Optional - User segments - **testCells** (object) - Optional - User test cells - **clientId** (string) - Optional - Client ID, defaults to value supplied by 'constructorio-id' module - **sessionId** (number) - Optional - Session ID, defaults to value supplied by 'constructorio-id' module - **userId** (string) - Optional - User ID - **fetch** (function) - Optional - If supplied, will be utilized for requests rather than default Fetch API - **trackingSendDelay** (number) - Optional - Amount of time to wait before sending tracking events (in ms) (default: 250) - **sendReferrerWithTrackingEvents** (boolean) - Optional - Indicates if the referrer is sent with tracking events (default: true) - **sendTrackingEvents** (boolean) - Optional - Indicates if tracking events should be dispatched (default: false) - **idOptions** (object) - Optional - Options object to be supplied to 'constructorio-id' module - **eventDispatcher** (object) - Optional - Options related to 'EventDispatcher' class - **enabled** (boolean) - Optional - Determine if events should be dispatched (default: true) - **waitForBeacon** (boolean) - Optional - Wait for beacon before dispatching events (default: true) - **networkParameters** (object) - Optional - Parameters relevant to network requests - **timeout** (number) - Optional - Request timeout (in milliseconds) - **humanityCheckLocation** (string) - Optional - Storage location for the humanity check flag ('session' or 'local') (default: 'session') ### Returns - **class** - The instantiated ConstructorIO client object. ``` -------------------------------- ### Instantiate Constructor.io Client Source: https://constructor-io.github.io/constructorio-client-javascript/index.html Create an instance of the Constructor.io client by providing your API key. This client is intended for browser environments. ```javascript const ConstructorioClient = require('@constructor-io/constructorio-client-javascript'); const constructorio = new ConstructorioClient({ apiKey: 'YOUR API KEY', }); ``` -------------------------------- ### Initialize Constructor.io Client with Custom Fetch and Event Dispatcher Source: https://constructor-io.github.io/constructorio-client-javascript/constructorio.js.html Instantiate the Constructor.io client using a custom fetch implementation and configuring the event dispatcher. This is useful for advanced network handling and event management. ```javascript const constructorio = require('@constructor-io/constructorio'); const constructorioClient = new constructorio({ apiKey: 'YOUR_API_KEY', fetch: myCustomFetchImplementation, eventDispatcher: { enabled: false, waitForBeacon: false } }); ``` -------------------------------- ### Initialize Constructor.io Client with Custom Service URLs Source: https://constructor-io.github.io/constructorio-client-javascript/constructorio.js.html Instantiate the Constructor.io client with an API key and custom service URLs for different Constructor.io services. This allows for flexibility in API endpoint configuration. ```javascript const constructorio = require('@constructor-io/constructorio'); const constructorioClient = new constructorio({ apiKey: 'YOUR_API_KEY', serviceUrl: 'https://ac.cnstrc.com', quizzesServiceUrl: 'https://quizzes.cnstrc.com', agentServiceUrl: 'https://agent.cnstrc.com', mediaServiceUrl: 'https://media-cnstrc.com', assistantServiceUrl: 'https://assistant.cnstrc.com' }); ``` -------------------------------- ### NPM Development Commands Source: https://constructor-io.github.io/constructorio-client-javascript/index.html Common npm commands for linting, testing, generating coverage reports, and building documentation for the Constructor.io JavaScript client. ```bash npm run lint # run lint on source code and tests npm run test # run tests npm run coverage # run tests and serves coverage reports from localhost:8081 npm run docs # output documentation to "./docs" directory ``` -------------------------------- ### Initialize Constructor.io Client Source: https://constructor-io.github.io/constructorio-client-javascript/constructorio.js.html Initializes the Constructor.io client with provided options. It handles ID generation in DOM environments and validates required parameters like API key and session/client IDs in DOM-less environments. Defaults are provided for service URLs if not specified. ```javascript class Constructorio { constructor(options) { const { apiKey, version: versionFromOptions, serviceUrl, quizzesServiceUrl, agentServiceUrl, assistantServiceUrl, mediaServiceUrl, segments, testCells, clientId, sessionId, userId, fetch: fetchFromOptions, trackingSendDelay, sendReferrerWithTrackingEvents, sendTrackingEvents, eventDispatcher, idOptions, beaconMode, networkParameters, humanityCheckLocation, } = options; if (!apiKey || typeof apiKey !== 'string') { throw new Error('API key is a required parameter of type string'); } let session_id; let client_id; const versionFromGlobal = typeof global !== 'undefined' && global.CLIENT_VERSION; // Initialize ID session if DOM context is available if (helpers.canUseDOM()) { ({ session_id, client_id } = new ConstructorioID(idOptions || {})); } else { // Validate session ID is provided if (!sessionId || typeof sessionId !== 'number') { throw new Error('sessionId is a required user parameter of type number'); } // Validate client ID is provided if (!clientId || typeof clientId !== 'string') { throw new Error('clientId is a required user parameter of type string'); } } const normalizedServiceUrl = serviceUrl && serviceUrl.replace(//$/, ''); this.options = { apiKey, version: versionFromOptions || versionFromGlobal || computePackageVersion(), serviceUrl: helpers.addHTTPSToString(normalizedServiceUrl) || 'https://ac.cnstrc.com', quizzesServiceUrl: (quizzesServiceUrl && quizzesServiceUrl.replace(//$/, '')) || 'https://quizzes.cnstrc.com', agentServiceUrl: (agentServiceUrl && agentServiceUrl.replace(//$/, '')) || 'https://agent.cnstrc.com', assistantServiceUrl: (assistantServiceUrl && assistantServiceUrl.replace(//$/, '')) || 'https://assistant.cnstrc.com', mediaServiceUrl: (mediaServiceUrl && mediaServiceUrl.replace(//$/, '')) || 'https://media-cnstrc.com', sessionId: sessionId || session_id, clientId: clientId || client_id, userId, segments, testCells: helpers.toValidTestCells(testCells), fetch: fetchFromOptions || fetch, trackingSendDelay, sendTrackingEvents, sendReferrerWithTrackingEvents, eventDispatcher, beaconMode: (beaconMode === false) ? false : true, // Defaults to 'true', networkParameters: networkParameters || {}, humanityCheckLocation: humanityCheckLocation || 'session', }; // Expose global modules this.search = new Search(this.options); this.browse = new Browse(this.options); this.autocomplete = new Autocomplete(this.options); this.recommendations = new Recommendations(this.options); this.tracker = new Tracker(this.options); this.quizzes = new Quizzes(this.options); this.agent = new Agent(this.options); this.assistant = new Assistant(this.options); // Dispatch initialization event new EventDispatcher(options.eventDispatcher).queue('instantiated', this.options); } } ``` -------------------------------- ### Get Browse Facets Source: https://constructor-io.github.io/constructorio-client-javascript/modules_browse.js.html Retrieves facet information for a given set of parameters. Handles network timeouts and response validation. ```javascript getBrowseFacets(parameters = {}, networkParameters = {}) { let requestUrl; const { fetch } = this.options; let signal; if (typeof AbortController === 'function') { const controller = new AbortController(); signal = controller && controller.signal; // Handle network timeout if specified helpers.applyNetworkTimeout(this.options, networkParameters, controller); } try { requestUrl = createBrowseUrlForFacets(parameters, this.options); } catch (e) { return Promise.reject(e); } return fetch(requestUrl, { signal }) .then(helpers.convertResponseToJson) .then((json) => { if (json.response && json.response.facets) { this.eventDispatcher.queue('browse.getBrowseFacets.completed', json); return json; } throw new Error('getBrowseFacets response data is malformed'); }); } ``` -------------------------------- ### Get Quiz Results Source: https://constructor-io.github.io/constructorio-client-javascript/modules_quizzes.js.html Retrieves quiz results from the Constructor.io API. Ensure the response includes a 'quiz_version_id' for successful processing. ```javascript return fetch(requestUrl, { signal }) .then(helpers.convertResponseToJson) .then((json) => { if (json.quiz_version_id) { this.eventDispatcher.queue('quizzes.getQuizResults.completed', json); return json; } throw new Error('getQuizResults response data is malformed'); }); ``` -------------------------------- ### Initialize Constructor.io Client with Network Parameters and Humanity Check Location Source: https://constructor-io.github.io/constructorio-client-javascript/constructorio.js.html Instantiate the Constructor.io client with specific network parameters, such as a request timeout, and define the storage location for the humanity check flag. ```javascript const constructorio = require('@constructor-io/constructorio'); const constructorioClient = new constructorio({ apiKey: 'YOUR_API_KEY', networkParameters: { timeout: 5000 }, humanityCheckLocation: 'local' }); ``` -------------------------------- ### getQuizResults Source: https://constructor-io.github.io/constructorio-client-javascript/module-quizzes.html Retrieve quiz recommendation and filter expression from the Constructor.io API. This method is used to get the final results of a quiz. ```APIDOC ## getQuizResults(quizId, parameters, networkParametersopt) ### Description Retrieve quiz recommendation and filter expression from Constructor.io API. ### Method (inner) ### Endpoint See: https://docs.constructor.com/reference/v1-quizzes-get-quiz-results ### Parameters #### Path Parameters * **quizId** (string) - Required - The identifier of the quiz #### Query Parameters * **parameters** (string) - Required - Additional parameters to refine result set * **networkParameters** (object) - Optional - Parameters relevant to the network request * **timeout** (number) - Optional - Request timeout (in milliseconds) ### Returns Type: Promise ``` -------------------------------- ### Get All Quiz Questions Source: https://constructor-io.github.io/constructorio-client-javascript/module-quizzes.html Retrieve all questions for a specific quiz. Pass the quiz ID and optional parameters like quizVersionId. ```javascript constructorio.quizzes.getQuizAllQuestions('quizId', { quizVersionId: '123' }); ``` -------------------------------- ### Expose ConstructorIO Client on Window Source: https://constructor-io.github.io/constructorio-client-javascript/constructorio.js.html Expose the ConstructorIO client on the window object if the DOM is available, allowing global access. ```javascript if (helpers.canUseDOM()) { window.ConstructorioClient = ConstructorIO; } ``` -------------------------------- ### getRecommendations Source: https://constructor-io.github.io/constructorio-client-javascript/module-recommendations.html Retrieve recommendation results from Constructor.io API. This method allows for detailed refinement of recommendations using various parameters. ```APIDOC ## GET /recommendations ### Description Retrieve recommendation results from Constructor.io API. This method allows for detailed refinement of recommendations using various parameters. ### Method GET ### Endpoint /recommendations ### Parameters #### Path Parameters - **podId** (string) - Required - Pod identifier #### Query Parameters - **parameters** (object) - Optional - Additional parameters to refine results - **itemIds** (array) - Optional - Item ID(s) to retrieve recommendations for (strategy specific). Required for variationId - **variationId** (string) - Optional - Variation ID to retrieve recommendations for (strategy specific) - **numResults** (number) - Optional - The number of results to return - **section** (string) - Optional - The section to return results from - **term** (string) - Optional - The term to use to refine results (strategy specific) - **filters** (object) - Optional - Key / value mapping of filters used to refine results - **variationsMap** (object) - Optional - The variations map object to aggregate variations. Please refer to https://docs.constructor.com/reference/shared-variations-mapping for details - **preFilterExpression** (object) - Optional - Faceting expression to scope search results. Please refer to https://docs.constructor.com/reference/configuration-collections for details - **fmtOptions** (object) - Optional - An object containing options to format different aspects of the response. Please refer to https://docs.constructor.com/reference/v1-recommendations-get-pod-results for details - **hiddenFields** (Array) - Optional - Hidden metadata fields to return - **networkParameters** (object) - Optional - Parameters relevant to the network request - **timeout** (number) - Optional - Request timeout (in milliseconds) ### Request Example ```javascript constructorio.recommendations.getRecommendations('t-shirt-best-sellers', { numResults: 5, filters: { size: 'medium' }, }); ``` ### Response #### Success Response (200) - **Promise** - Type: Promise - Description: A promise that resolves with the recommendation results. ``` -------------------------------- ### Get Browse Facet Options Source: https://constructor-io.github.io/constructorio-client-javascript/module-browse.html Retrieve available options for a specific facet from the API. This is useful for populating filter controls in a user interface. ```javascript constructorio.browse.getBrowseFacetOptions('price', { }); ``` -------------------------------- ### getQuizAllQuestions Source: https://constructor-io.github.io/constructorio-client-javascript/module-quizzes.html Retrieve all questions for a particular quiz from Constructor.io API. This method is useful for fetching the entire set of questions for a quiz at once. ```APIDOC ## getQuizAllQuestions(quizId, parameters, networkParametersopt) ### Description Retrieve all questions for a particular quiz from Constructor.io API. ### Method (inner) ### Parameters #### Path Parameters * **quizId** (string) - Required - The identifier of the quiz #### Query Parameters * **parameters** (object) - Optional - Additional parameters * **section** (string) - Optional - Product catalog section * **quizVersionId** (string) - Optional - Version identifier for the quiz. Version ID will be returned with the first request and it should be passed with subsequent requests. More information can be found: https://docs.constructor.com/reference/configuration-quizzes * **quizSessionId** (string) - Optional - Session identifier for the quiz. Session ID will be returned with the first request or with getQuizResultsConfig and it should be passed with subsequent requests. More information can be found: https://docs.constructor.com/reference/configuration-quizzes * **networkParameters** (object) - Optional - Parameters relevant to the network request * **timeout** (number) - Optional - Request timeout (in milliseconds) ### Returns Type: Promise ``` -------------------------------- ### Get Quiz Results Source: https://constructor-io.github.io/constructorio-client-javascript/module-quizzes.html Retrieve quiz recommendations and filter expressions. Requires the quiz ID and parameters such as answers, section, quizVersionId, and quizSessionId. ```javascript constructorio.quizzes.getQuizResults('quizId', { answers: [[1,2],[1]], section: '123', quizVersionId: '123', quizSessionId: '234' }); ``` -------------------------------- ### Get Autocomplete Results Source: https://constructor-io.github.io/constructorio-client-javascript/module-autocomplete.html Retrieve autocomplete suggestions and results for a given query. Supports specifying the number of results per section and applying filters. ```javascript constructorio.autocomplete.getAutocompleteResults('t-shirt', { resultsPerSection: { Products: 5, 'Search Suggestions': 10, }, filters: { size: 'medium' }, }); ``` -------------------------------- ### Get Browse Groups Source: https://constructor-io.github.io/constructorio-client-javascript/module-browse.html Retrieve browse groups from the API, allowing for hierarchical navigation of products. Supports filtering and setting maximum depth for group results. ```javascript constructorio.browse.getBrowseGroups({ filters: { group_id: 'drill_collection' }, fmtOptions: { groups_max_depth: 2 } }); ``` -------------------------------- ### Get Browse Facets Source: https://constructor-io.github.io/constructorio-client-javascript/module-browse.html Retrieve browse facets from the API, which can be used to categorize and filter results. Supports pagination and specifying the number of results per page. ```javascript constructorio.browse.getBrowseFacets({ page: 1, resultsPerPage: 10, }); ``` -------------------------------- ### Get Next Quiz Question Source: https://constructor-io.github.io/constructorio-client-javascript/module-quizzes.html Retrieve the next question in a quiz. Requires the quiz ID and can include answers, section, quizVersionId, and quizSessionId. Tracking can be skipped. ```javascript constructorio.quizzes.getQuizNextQuestion('quizId', { answers: [[1,2],[1]], section: '123', quizVersionId: '123', quizSessionId: '1234' }); ``` -------------------------------- ### getQuizResults Source: https://constructor-io.github.io/constructorio-client-javascript/modules_quizzes.js.html Retrieves quiz results, including recommendations and filter expressions, based on the provided quiz ID and answers. This method is used to get the final outcome of a quiz. ```APIDOC ## GET /quizzes/{quizId}/results ### Description Retrieves quiz recommendation and filter expression from Constructor.io API based on the answers provided. ### Method GET ### Endpoint /quizzes/{quizId}/results ### Parameters #### Path Parameters - **quizId** (string) - Required - The identifier of the quiz. #### Query Parameters - **parameters.answers** (array) - Required - An array of answers in the format [[1,2], [1], ["true"], ["seen"], [""]]. Based on the question type, answers should either be an integer, "true"/"false", "seen" or an empty string (" ") if skipped. - **parameters.section** (string) - Optional - Product catalog section. - **parameters.quizVersionId** (string) - Optional - Version identifier for the quiz. Version ID will be returned with the first request and it should be passed with subsequent requests. - **parameters.quizSessionId** (string) - Optional - Session identifier for the quiz. Session ID will be returned with the first request and it should be passed with subsequent requests. - **parameters.page** (number) - Optional - The page number of the results. - **parameters.resultsPerPage** (number) - Optional - The number of results per page to return. - **parameters.filters** (object) - Optional - Key / value mapping (dictionary) of filters used to refine results. - **parameters.fmtOptions** (object) - Optional - Key / value mapping (dictionary) of options used for result formatting. - **parameters.hiddenFields** (string[]) - Optional - Hidden metadata fields to return. #### Network Parameters - **networkParameters.timeout** (number) - Optional - Request timeout (in milliseconds) ### Response #### Success Response (200) - **results** (array) - An array of recommended products. - **results[].product_id** (string) - The ID of the product. - **results[].title** (string) - The title of the product. - **results[].image_url** (string) - The URL of the product image. - **results[].description** (string) - The description of the product. - **results[].url** (string) - The URL of the product. - **results[].price** (string) - The price of the product. - **results[].display_name** (string) - The display name of the product. - **results[].brand** (string) - The brand of the product. - **results[].variants** (array) - An array of product variants. - **results[].categories** (array) - An array of product categories. - **result_id** (string) - The identifier for the result set. - **filter_expression** (object) - The filter expression used for the results. ### Request Example ```javascript constructorio.quizzes.getQuizResults('quizId', { answers: [[1,2],[1]], section: '123', quizVersionId: '123', quizSessionId: '234' }); ``` ### Response Example ```json { "results": [ { "product_id": "prod123", "title": "Example Product", "image_url": "http://example.com/image.jpg", "description": "This is an example product.", "url": "http://example.com/product", "price": "$19.99", "display_name": "Example Product", "brand": "Example Brand", "variants": [], "categories": ["Category A", "Category B"] } ], "result_id": "abc123xyz", "filter_expression": { "or": [ { "and": [ { "field": "categories", "operator": "CONTAINS_ALL", "value": ["Category A"] } ] } ] } } ``` ``` -------------------------------- ### Constructor Browse Class Source: https://constructor-io.github.io/constructorio-client-javascript/modules_browse.js.html Initializes the Browse class with options and an event dispatcher. This class provides an interface for browse-related API calls. ```javascript class Browse { constructor(options) { this.options = options || {}; this.eventDispatcher = new EventDispatcher(options.eventDispatcher); } // ... other methods ``` -------------------------------- ### setClientOptions Source: https://constructor-io.github.io/constructorio-client-javascript/ConstructorIO.html Sets or updates the client options after instantiation. ```APIDOC ## setClientOptions(options) ### Description Sets the client options. ### Method `setClientOptions` ### Parameters #### Parameters - **options** (object) - Client options to update - **apiKey** (string) - Optional - Constructor.io API key - **segments** (array) - Optional - User segments - **testCells** (object) - Optional - User test cells - **sessionId** (number) - Optional - Session ID - Will only be set in DOM-less environments - **userId** (string) - Optional - User ID - **sendTrackingEvents** (boolean) - Optional - Indicates if tracking events should be dispatched ``` -------------------------------- ### Get Assistant Results Stream (Deprecated) Source: https://constructor-io.github.io/constructorio-client-javascript/modules_assistant.js.html Retrieve a stream of assistant results from Constructor.io API. This method is deprecated; use getAssistantResultsStream from the Agent module instead. It returns a ReadableStream. ```javascript const readableStream = constructorio.assistant.getAssistantResultsStream('I want to get shoes', { domain: "nike_sportswear", }); const reader = readableStream.getReader(); const { value, done } = await reader.read(); ``` -------------------------------- ### Create Agent URL Source: https://constructor-io.github.io/constructorio-client-javascript/modules_agent.js.html Constructs the API URL for agent intents, incorporating various parameters and options. Ensure 'intent' and 'parameters.domain' are provided as strings. ```javascript const { cleanParams, trimNonBreakingSpaces, encodeURIComponentRFC3986, stringify, isNil } = require('../utils/helpers'); // Create URL from supplied intent (term) and parameters // eslint-disable-next-line complexity function createAgentUrl(intent, parameters, options) { const { apiKey, version, sessionId, clientId, userId, segments, testCells, agentServiceUrl, assistantServiceUrl, } = options; let queryParams = { c: version }; queryParams.key = apiKey; queryParams.i = clientId; queryParams.s = sessionId; const serviceUrl = agentServiceUrl || assistantServiceUrl; // Validate intent is provided if (!intent || typeof intent !== 'string') { throw new Error('intent is a required parameter of type string'); } // Validate domain is provided if (!parameters || !parameters.domain || typeof parameters.domain !== 'string') { throw new Error('parameters.domain is a required parameter of type string'); } // Pull test cells from options if (testCells) { Object.keys(testCells).forEach((testCellKey) => { queryParams[`ef-${testCellKey}`] = testCells[testCellKey]; }); } // Pull user segments from options if (segments && segments.length) { queryParams.us = segments; } // Pull user id from options and ensure string if (userId) { queryParams.ui = String(userId); } if (parameters) { const { domain, numResultsPerPage, threadId, guard, numResultsPerEvent, numResultEvents, qsParam, preFilterExpression, fmtOptions, } = parameters; // Pull domain from parameters if (domain) { queryParams.domain = domain; } // Pull results number from parameters if (numResultsPerPage) { queryParams.num_results_per_page = numResultsPerPage; } // Pull thread_id from parameters if (threadId) { queryParams.thread_id = threadId; } // Pull guard from parameters if (!isNil(guard)) { queryParams.guard = guard; } // Pull num_results_per_event from parameters if (numResultsPerEvent) { queryParams.num_results_per_event = numResultsPerEvent; } // Pull num_result_events from parameters if (numResultEvents) { queryParams.num_result_events = numResultEvents; } // Pull qsParam from parameters if (qsParam) { queryParams.qs = JSON.stringify(qsParam); } // Pull pre_filter_expression from parameters if (preFilterExpression) { queryParams.pre_filter_expression = JSON.stringify(preFilterExpression); } // Pull fmt_options from parameters if (fmtOptions) { queryParams.fmt_options = fmtOptions; } } // eslint-disable-next-line no-underscore-dangle queryParams._dt = Date.now(); queryParams = cleanParams(queryParams); const queryString = stringify(queryParams); const cleanedQuery = intent.replace(/^\//, '|'); // For compatibility with backend API return `${serviceUrl}/v1/intent/${encodeURIComponentRFC3986(trimNonBreakingSpaces(cleanedQuery))}?${queryString}`; } ``` -------------------------------- ### getQuizNextQuestion Source: https://constructor-io.github.io/constructorio-client-javascript/module-quizzes.html Retrieve the next question from the Constructor.io API based on the provided quiz ID and answers. This method is essential for progressing through a quiz. ```APIDOC ## getQuizNextQuestion(quizId, parametersopt, networkParametersopt) ### Description Retrieve next question from Constructor.io API. ### Method (inner) ### Endpoint See: https://docs.constructor.com/reference/v1-quizzes-get-quiz-results ### Parameters #### Path Parameters * **quizId** (string) - Required - The identifier of the quiz #### Query Parameters * **parameters** (string) - Optional - Additional parameters to refine result set * **section** (string) - Optional - Product catalog section * **answers** (array) - Optional - An array of answers in the format [[1,2], [1], ["true"], ["seen"], [""]]. Based on the question type, answers should either be an integer, "true"/"false", "seen" or an empty string (" ") if skipped * **quizVersionId** (string) - Optional - Version identifier for the quiz. Version ID will be returned with the first request and it should be passed with subsequent requests. More information can be found: https://docs.constructor.com/reference/configuration-quizzes * **quizSessionId** (string) - Optional - Session identifier for the quiz. Session ID will be returned with the first request and it should be passed with subsequent requests. More information can be found: https://docs.constructor.com/reference/configuration-quizzes * **skipTracking** (boolean) - Optional - If true, tracking for this question will be skipped. This is useful for preloading the first question of a quiz * **networkParameters** (object) - Optional - Parameters relevant to the network request * **timeout** (number) - Optional - Request timeout (in milliseconds) ### Returns Type: Promise ``` -------------------------------- ### Get Voice Search Results Source: https://constructor-io.github.io/constructorio-client-javascript/module-search.html Retrieve voice search results from the Constructor.io API. This method is optimized for processing natural language queries typically used in voice search applications. ```javascript constructorio.search.getVoiceSearchResults('show me lipstick'); ``` -------------------------------- ### Create Browse URL for Facet Options Source: https://constructor-io.github.io/constructorio-client-javascript/modules_browse.js.html Generates a URL to fetch options for a specific facet. Requires a facet name and supports additional parameters. The `_dt` parameter is excluded. ```javascript function createBrowseUrlForFacetOptions(facetName, parameters, options) { const { serviceUrl } = options; // Validate facet name is provided if (!facetName || typeof facetName !== 'string') { throw new Error('facetName is a required parameter of type string'); } const queryParams = { ...createQueryParams(parameters, options) }; queryParams.facet_name = facetName; // Endpoint does not accept _dt delete queryParams._dt; const queryString = helpers.stringify(queryParams); return `${serviceUrl}/browse/facet_options?${queryString}`; } ``` -------------------------------- ### Exporting Agent Module and Functions Source: https://constructor-io.github.io/constructorio-client-javascript/modules_agent.js.html Exports the main Agent class and utility functions like createAgentUrl and setupEventListeners from the module. ```javascript module.exports = Agent; module.exports.createAgentUrl = createAgentUrl; module.exports.setupEventListeners = setupEventListeners; ``` -------------------------------- ### Track Browse Results Loaded Source: https://constructor-io.github.io/constructorio-client-javascript/module-tracker.html Use this method when a user views a product listing page. It requires parameters like result count, page number, and selected filters. ```javascript constructorio.tracker.trackBrowseResultsLoaded( { resultCount: 22, resultPage: 2, resultId: '019927c2-f955-4020-8b8d-6b21b93cb5a2', selectedFilters: { brand: ['foo'], color: ['black'] }, sortOrder: 'ascending', sortBy: 'price', items: [{ itemId: 'KMH876' }, { itemId: 'KMH140' }], url: 'https://demo.constructor.io/sandbox/farmstand', filterName: 'brand', filterValue: 'XYZ', }, ); ``` -------------------------------- ### getAutocompleteResults Source: https://constructor-io.github.io/constructorio-client-javascript/module-autocomplete.html Retrieve autocomplete results from Constructor.io API. This method allows users to get autocomplete suggestions based on a query, with options to refine the results by specifying parameters like number of results, filters, and formatting options. ```APIDOC ## getAutocompleteResults(query, parametersopt, networkParametersopt) ### Description Retrieve autocomplete results from Constructor.io API. ### Method (inner) ### Endpoint (Not specified, typically an internal SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript constructorio.autocomplete.getAutocompleteResults('t-shirt', { resultsPerSection: { Products: 5, 'Search Suggestions': 10, }, filters: { size: 'medium' }, }); ``` ### Parameters #### `query` (string) - Required - Term to use to perform an autocomplete search #### `parameters` (object) - Optional - Additional parameters to refine result set ##### Properties - **`numResults`** (number) - Optional - The total number of results to return - **`filters`** (object) - Optional - Key / value mapping (dictionary) of filters used to refine results - **`filtersPerSection`** (object) - Optional - Filters used to refine results per section - **`resultsPerSection`** (object) - Optional - Number of results to return (value) per section (key) - **`fmtOptions`** (object) - Optional - An object containing options to format different aspects of the response. Please refer to https://docs.constructor.com/reference/v1-autocomplete-get-autocomplete-results for details - **`preFilterExpression`** (object) - Optional - Faceting expression to scope autocomplete results. Please refer to https://docs.constructor.com/reference/configuration-collections for details - **`preFilterExpressionPerSection`** (object) - Optional - Faceting expression to scope autocomplete results per section (key). Please refer to https://docs.constructor.com/reference/configuration-collections for details - **`hiddenFields`** (Array.) - Optional - Hidden metadata fields to return - **`variationsMap`** (object) - Optional - The variations map object to aggregate variations. Please refer to https://docs.constructor.com/reference/shared-variations-mapping for details - **`qsParam`** (object) - Optional - object of additional query parameters to be appended to requests for results #### `networkParameters` (object) - Optional - Parameters relevant to the network request ##### Properties - **`timeout`** (number) - Optional - Request timeout (in milliseconds) ### Response #### Success Response (Promise) (Type: Promise, details not specified in source) #### Response Example (Not specified in source) ``` -------------------------------- ### Get Browse Results by Item IDs Source: https://constructor-io.github.io/constructorio-client-javascript/module-browse.html Retrieve browse results from the API using a list of item IDs. This method allows for filtering results, such as by size, and specifying how filters should be matched (e.g., 'all' items must match). ```javascript constructorio.browse.getBrowseResultsForItemIds(['shirt-123', 'shirt-456', 'shirt-789'], { filters: { size: 'medium' }, filterMatchTypes: { size: 'all' } }); ``` -------------------------------- ### Setup Event Listeners for SSE Source: https://constructor-io.github.io/constructorio-client-javascript/modules_agent.js.html Attaches event listeners to an EventSource for Server-Sent Events (SSE). Handles data parsing, stream enqueuing, and stream closing upon receiving the END event. Errors are passed to the stream controller. ```javascript // Add event listeners to custom SSE that pushes data to the stream function setupEventListeners(eventSource, controller, eventTypes) { const addListener = (type) => { eventSource.addEventListener(type, (event) => { const data = JSON.parse(event.data); controller.enqueue({ type, data }); // Enqueue data into the stream }); }; // Set up listeners for all event types except END Object.values(eventTypes).forEach((type) => { if (type !== eventTypes.END) { addListener(type); } }); // Handle the END event separately to close the stream eventSource.addEventListener(eventTypes.END, () => { controller.close(); // Close the stream eventSource.close(); // Close the EventSource connection }); // Handle errors from the EventSource // eslint-disable-next-line no-param-reassign eventSource.onerror = (error) => { controller.error(error); // Pass the error to the stream }; } ```