1/** 2 * Extracts the base path from the current URL by removing a specified suffix. 3 * This is useful for handling subdirectory deployments where the application 4 * might not be hosted at the root path. 5 * 6 * Example: 7 * - URL: /my-app/docs/ 8 * - Suffix: /docs/ 9 * - Result: /my-app 10 * 11 * @param {string} suffix - The URL suffix to remove (can be empty) 12 * @returns {string} The normalized base path with no trailing slash 13 */ 14export const getBasePath = (suffix) => { 15 // Decode the suffix to handle percent-encoded paths coming from the server 16 const decodedSuffix = decodeURIComponent(suffix ?? '') 17 const path = window.location.pathname 18 if (path.endsWith(decodedSuffix)) { 19 return path.slice(0, -decodedSuffix.length) 20 } 21 return '' 22} 23 24/** 25 * Initialize Scalar with the given configuration 26 * 27 * @param {string} path - The current request path used to calculate the base URL 28 * @param {boolean} useDynamicBaseServerUrl - When true, uses the current server URL as the base URL 29 * @param {Object} configuration - Scalar configuration object 30 * @param {Array<Object>} [configuration.sources=[]] - Array of OpenAPI source configurations 31 * @param {string} [modulePath] - Optional path to the custom configuration script 32 */ 33export const initialize = async (path, useDynamicBaseServerUrl, configuration = { sources: [] }, modulePath) => { 34 const basePath = getBasePath(path) 35 const httpUrlPattern = /^https?:\/\//i 36 37 const normalizedConfig = { 38 ...configuration, 39 sources: configuration?.sources?.map((source) => ({ ...source })) || [], 40 } 41 42 // Construct full URLs for subdirectory hosting support if URLs are relative 43 normalizedConfig.sources = normalizedConfig.sources.map((source) => { 44 if (!source.url || httpUrlPattern.test(source.url)) { 45 return source 46 } 47 48 return { 49 ...source, 50 url: new URL(source.url, `${window.location.origin}${basePath}/`).toString(), 51 } 52 }) 53 54 if (useDynamicBaseServerUrl) { 55 normalizedConfig.baseServerURL = `${window.location.origin}${basePath}` 56 } 57 58 // Only load custom configuration if modulePath is provided 59 if (modulePath) { 60 // Normalize modulePath if it's a relative path 61 const normalizedConfigPath = httpUrlPattern.test(modulePath) 62 ? modulePath 63 : new URL(modulePath, `${window.location.origin}${basePath}/`).toString() 64 65 try { 66 const customConfiguration = await import(normalizedConfigPath) 67 Object.assign(normalizedConfig, customConfiguration.default) 68 } catch (e) { 69 console.error('Failed to load custom configuration', e) 70 } 71 } 72 73 window.Scalar.createApiReference('#app', normalizedConfig) 74}
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.