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
export function validateInlineOptions(inlineOptions) { const invalidKeys = Object.keys(inlineOptions || {}).filter( (key) => !allowedInlineOptions.has(key) ); if (invalidKeys.length) { log.warn(`invalid plugin options "${invalidKeys.join(', ')}" in inline config`, inlineOptions); } }
@param {Partial<import('../public.d.ts').Options>} [inlineOptions]
validateInlineOptions ( inlineOptions )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
function convertPluginOptions(config) { if (!config) { return; } const invalidRootOptions = Object.keys(config).filter((key) => allowedPluginOptions.has(key)); if (invalidRootOptions.length > 0) { throw new Error( `Invalid options in svelte config. Move the following options into 'vitePlugin:{...}': ${invalidRootOptions.join( ', ' )}` ); } if (!config.vitePlugin) { return config; } const pluginOptions = config.vitePlugin; const pluginOptionKeys = Object.keys(pluginOptions); const rootOptionsInPluginOptions = pluginOptionKeys.filter((key) => knownRootOptions.has(key)); if (rootOptionsInPluginOptions.length > 0) { throw new Error( `Invalid options in svelte config under vitePlugin:{...}', move them to the config root : ${rootOptionsInPluginOptions.join( ', ' )}` ); } const duplicateOptions = pluginOptionKeys.filter((key) => Object.prototype.hasOwnProperty.call(config, key) ); if (duplicateOptions.length > 0) { throw new Error( `Invalid duplicate options in svelte config under vitePlugin:{...}', they are defined in root too and must only exist once: ${duplicateOptions.join( ', ' )}` ); } const unknownPluginOptions = pluginOptionKeys.filter((key) => !allowedPluginOptions.has(key)); if (unknownPluginOptions.length > 0) { log.warn( `ignoring unknown plugin options in svelte config under vitePlugin:{...}: ${unknownPluginOptions.join( ', ' )}` ); unknownPluginOptions.forEach((unkownOption) => { // @ts-expect-error not typed delete pluginOptions[unkownOption]; }); } /** @type {import('../public.d.ts').Options} */ const result = { ...config, ...pluginOptions }; // @ts-expect-error it exists delete result.vitePlugin; return result; }
@param {Partial<import('../public.d.ts').SvelteConfig>} [config] @returns {Partial<import('../public.d.ts').Options> | undefined}
convertPluginOptions ( config )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
export function resolveOptions(preResolveOptions, viteConfig, cache) { const css = preResolveOptions.emitCss ? 'external' : 'injected'; /** @type {Partial<import('../public.d.ts').Options>} */ const defaultOptions = { compilerOptions: { css, dev: !viteConfig.isProduction, hmr: !viteConfig.isProduction && !preResolveOptions.isBuild && viteConfig.server && viteConfig.server.hmr !== false } }; /** @type {Partial<import('../types/options.d.ts').ResolvedOptions>} */ const extraOptions = { root: viteConfig.root, isProduction: viteConfig.isProduction }; const merged = /** @type {import('../types/options.d.ts').ResolvedOptions}*/ ( mergeConfigs(defaultOptions, preResolveOptions, extraOptions) ); removeIgnoredOptions(merged); handleDeprecatedOptions(merged); addExtraPreprocessors(merged, viteConfig); enforceOptionsForHmr(merged, viteConfig); enforceOptionsForProduction(merged); // mergeConfigs would mangle functions on the stats class, so do this afterwards if (log.debug.enabled && isDebugNamespaceEnabled('stats')) { merged.stats = new VitePluginSvelteStats(cache); } return merged; }
used in configResolved phase, merges a contextual default config, pre-resolved options, and some preprocessors. also validates the final config. @param {import('../types/options.d.ts').PreResolvedOptions} preResolveOptions @param {import('vite').ResolvedConfig} viteConfig @param {import('./vite-plugin-svelte-cache.js').VitePluginSvelteCache} cache @returns {import('../types/options.d.ts').ResolvedOptions}
resolveOptions ( preResolveOptions , viteConfig , cache )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
function enforceOptionsForHmr(options, viteConfig) { if (options.hot) { log.warn( 'svelte 5 has hmr integrated in core. Please remove the vitePlugin.hot option and use compilerOptions.hmr instead' ); delete options.hot; options.compilerOptions.hmr = true; } if (options.compilerOptions.hmr && viteConfig.server?.hmr === false) { log.warn( 'vite config server.hmr is false but compilerOptions.hmr is true. Forcing compilerOptions.hmr to false as it would not work.' ); options.compilerOptions.hmr = false; } }
@param {import('../types/options.d.ts').ResolvedOptions} options @param {import('vite').ResolvedConfig} viteConfig
enforceOptionsForHmr ( options , viteConfig )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
function enforceOptionsForProduction(options) { if (options.isProduction) { if (options.compilerOptions.hmr) { log.warn( 'you are building for production but compilerOptions.hmr is true, forcing it to false' ); options.compilerOptions.hmr = false; } if (options.compilerOptions.dev) { log.warn( 'you are building for production but compilerOptions.dev is true, forcing it to false' ); options.compilerOptions.dev = false; } } }
@param {import('../types/options.d.ts').ResolvedOptions} options
enforceOptionsForProduction ( options )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
function resolveViteRoot(viteConfig) { return normalizePath(viteConfig.root ? path.resolve(viteConfig.root) : process.cwd()); }
vite passes unresolved `root`option to config hook but we need the resolved value, so do it here @see https://github.com/sveltejs/vite-plugin-svelte/issues/113 @see https://github.com/vitejs/vite/blob/43c957de8a99bb326afd732c962f42127b0a4d1e/packages/vite/src/node/config.ts#L293 @param {import('vite').UserConfig} viteConfig @returns {string | undefined}
resolveViteRoot ( viteConfig )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
async function buildExtraConfigForDependencies(options, config) { // extra handling for svelte dependencies in the project const packagesWithoutSvelteExportsCondition = new Set(); const depsConfig = await crawlFrameworkPkgs({ root: options.root, isBuild: options.isBuild, viteUserConfig: config, isFrameworkPkgByJson(pkgJson) { let hasSvelteCondition = false; if (typeof pkgJson.exports === 'object') { // use replacer as a simple way to iterate over nested keys JSON.stringify(pkgJson.exports, (key, value) => { if (SVELTE_EXPORT_CONDITIONS.includes(key)) { hasSvelteCondition = true; } return value; }); } const hasSvelteField = !!pkgJson.svelte; if (hasSvelteField && !hasSvelteCondition) { packagesWithoutSvelteExportsCondition.add(`${pkgJson.name}@${pkgJson.version}`); } return hasSvelteCondition || hasSvelteField; }, isSemiFrameworkPkgByJson(pkgJson) { return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte; }, isFrameworkPkgByName(pkgName) { const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName); if (isNotSveltePackage) { return false; } else { return undefined; } } }); if ( !options.experimental?.disableSvelteResolveWarnings && packagesWithoutSvelteExportsCondition?.size > 0 ) { log.warn( `WARNING: The following packages have a svelte field in their package.json but no exports condition for svelte.\n\n${[ ...packagesWithoutSvelteExportsCondition ].join('\n')}\n\nPlease see ${FAQ_LINK_MISSING_EXPORTS_CONDITION} for details.` ); } log.debug('extra config for dependencies generated by vitefu', depsConfig, 'config'); if (options.prebundleSvelteLibraries) { // prebundling enabled, so we don't need extra dependency excludes depsConfig.optimizeDeps.exclude = []; // but keep dependency reinclusions of explicit user excludes const userExclude = config.optimizeDeps?.exclude; depsConfig.optimizeDeps.include = !userExclude ? [] : depsConfig.optimizeDeps.include.filter((dep) => { // reincludes look like this: foo > bar > baz // in case foo or bar are excluded, we have to retain the reinclude even with prebundling return ( dep.includes('>') && dep .split('>') .slice(0, -1) .some((d) => isDepExcluded(d.trim(), userExclude)) ); }); } if (options.disableDependencyReinclusion === true) { depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter( (dep) => !dep.includes('>') ); } else if (Array.isArray(options.disableDependencyReinclusion)) { const disabledDeps = options.disableDependencyReinclusion; depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => { if (!dep.includes('>')) return true; const trimDep = dep.replace(/\s+/g, ''); return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`)); }); } log.debug('post-processed extra config for dependencies', depsConfig, 'config'); return depsConfig; }
@param {import('../types/options.d.ts').PreResolvedOptions} options @param {import('vite').UserConfig} config @returns {Promise<import('vitefu').CrawlFrameworkPkgsResult>}
buildExtraConfigForDependencies ( options , config )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
export function patchResolvedViteConfig(viteConfig, options) { if (options.preprocess) { for (const preprocessor of arraify(options.preprocess)) { if (preprocessor.style && '__resolvedConfig' in preprocessor.style) { preprocessor.style.__resolvedConfig = viteConfig; } } } // replace facade esbuild plugin with a real one const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find( (plugin) => plugin.name === facadeEsbuildSveltePluginName ); if (facadeEsbuildSveltePlugin) { Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options)); } const facadeEsbuildSvelteModulePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find( (plugin) => plugin.name === facadeEsbuildSvelteModulePluginName ); if (facadeEsbuildSvelteModulePlugin) { Object.assign(facadeEsbuildSvelteModulePlugin, esbuildSvelteModulePlugin(options)); } }
@param {import('vite').ResolvedConfig} viteConfig @param {import('../types/options.d.ts').ResolvedOptions} options
patchResolvedViteConfig ( viteConfig , options )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
export function ensureConfigEnvironmentMainFields(name, config, opts) { config.resolve ??= {}; if (config.resolve.mainFields == null) { if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) { config.resolve.mainFields = [...defaultClientMainFields]; } else { config.resolve.mainFields = [...defaultServerMainFields]; } } return true; }
Mutates `config` to ensure `resolve.mainFields` is set. If unset, it emulates Vite's default fallback. @param {string} name @param {import('vite').EnvironmentOptions} config @param {{ isSsrTargetWebworker?: boolean }} opts
ensureConfigEnvironmentMainFields ( name , config , opts )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
export function ensureConfigEnvironmentConditions(name, config, opts) { config.resolve ??= {}; if (config.resolve.conditions == null) { if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) { config.resolve.conditions = [...defaultClientConditions]; } else { config.resolve.conditions = [...defaultServerConditions]; } } }
Mutates `config` to ensure `resolve.conditions` is set. If unset, it emulates Vite's default fallback. @param {string} name @param {import('vite').EnvironmentOptions} config @param {{ isSsrTargetWebworker?: boolean }} opts
ensureConfigEnvironmentConditions ( name , config , opts )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
function arraify(value) { return Array.isArray(value) ? value : [value]; }
@template T @param {T | T[]} value @returns {T[]}
arraify ( value )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
function buildExtraConfigForSvelte(config) { // include svelte imports for optimization unless explicitly excluded /** @type {string[]} */ const include = []; /** @type {string[]} */ const exclude = []; if (!isDepExcluded('svelte', config.optimizeDeps?.exclude ?? [])) { const svelteImportsToInclude = SVELTE_IMPORTS.filter( (si) => !(si.endsWith('/server') || si.includes('/server/')) ); log.debug( `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(', ')} `, undefined, 'config' ); include.push(...svelteImportsToInclude); } else { log.debug( '"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.', undefined, 'config' ); } /** @type {(string | RegExp)[]} */ const noExternal = []; /** @type {string[]} */ const external = []; // add svelte to ssr.noExternal unless it is present in ssr.external // so it is correctly resolving according to the conditions in sveltes exports map if (!isDepExternaled('svelte', config.ssr?.external ?? [])) { noExternal.push('svelte', /^svelte\//); } // esm-env needs to be bundled by default for the development/production condition // be properly used by svelte if (!isDepExternaled('esm-env', config.ssr?.external ?? [])) { noExternal.push('esm-env'); } return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } }; } /** * @param {import('vite').ResolvedConfig} viteConfig * @param {import('../types/options.d.ts').ResolvedOptions} options */ export function patchResolvedViteConfig(viteConfig, options) { if (options.preprocess) { for (const preprocessor of arraify(options.preprocess)) { if (preprocessor.style && '__resolvedConfig' in preprocessor.style) { preprocessor.style.__resolvedConfig = viteConfig; } } } // replace facade esbuild plugin with a real one const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find( (plugin) => plugin.name === facadeEsbuildSveltePluginName ); if (facadeEsbuildSveltePlugin) { Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options)); } const facadeEsbuildSvelteModulePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find( (plugin) => plugin.name === facadeEsbuildSvelteModulePluginName ); if (facadeEsbuildSvelteModulePlugin) { Object.assign(facadeEsbuildSvelteModulePlugin, esbuildSvelteModulePlugin(options)); } } /** * Mutates `config` to ensure `resolve.mainFields` is set. If unset, it emulates Vite's default fallback. * @param {string} name * @param {import('vite').EnvironmentOptions} config * @param {{ isSsrTargetWebworker?: boolean }} opts */ export function ensureConfigEnvironmentMainFields(name, config, opts) { config.resolve ??= {}; if (config.resolve.mainFields == null) { if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) { config.resolve.mainFields = [...defaultClientMainFields]; } else { config.resolve.mainFields = [...defaultServerMainFields]; } } return true; } /** * Mutates `config` to ensure `resolve.conditions` is set. If unset, it emulates Vite's default fallback. * @param {string} name * @param {import('vite').EnvironmentOptions} config * @param {{ isSsrTargetWebworker?: boolean }} opts */ export function ensureConfigEnvironmentConditions(name, config, opts) { config.resolve ??= {}; if (config.resolve.conditions == null) { if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) { config.resolve.conditions = [...defaultClientConditions]; } else { config.resolve.conditions = [...defaultServerConditions]; } } } /** * @template T * @param {T | T[]} value * @returns {T[]} */ function arraify(value) {
@param {import('vite').UserConfig} config @returns {import('vite').UserConfig & { optimizeDeps: { include: string[], exclude:string[] }, ssr: { noExternal:(string|RegExp)[], external: string[] } } }
buildExtraConfigForSvelte ( config )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/options.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/options.js
MIT
async function dynamicImportDefault(filePath, timestamp) { return await import(filePath + '?t=' + timestamp).then((m) => m.default); }
@param {string} filePath @param {number} timestamp
dynamicImportDefault ( filePath , timestamp )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/load-svelte-config.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/load-svelte-config.js
MIT
export async function loadSvelteConfig(viteConfig, inlineOptions) { if (inlineOptions?.configFile === false) { return; } const configFile = findConfigToLoad(viteConfig, inlineOptions); if (configFile) { let err; // try to use dynamic import for svelte.config.js first if (configFile.endsWith('.js') || configFile.endsWith('.mjs')) { try { const result = await dynamicImportDefault( pathToFileURL(configFile).href, fs.statSync(configFile).mtimeMs ); if (result != null) { return { ...result, configFile }; } else { throw new Error(`invalid export in ${configFile}`); } } catch (e) { log.error(`failed to import config ${configFile}`, e); err = e; } } // cjs or error with dynamic import if (!configFile.endsWith('.mjs')) { try { // identify which require function to use (esm and cjs mode) const _require = import.meta.url ? (esmRequire ?? (esmRequire = createRequire(import.meta.url))) : // eslint-disable-next-line no-undef require; // avoid loading cached version on reload delete _require.cache[_require.resolve(configFile)]; const result = _require(configFile); if (result != null) { return { ...result, configFile }; } else { throw new Error(`invalid export in ${configFile}`); } } catch (e) { log.error(`failed to require config ${configFile}`, e); if (!err) { err = e; } } } // failed to load existing config file throw err; } }
@param {import('vite').UserConfig} [viteConfig] @param {Partial<import('../public.d.ts').Options>} [inlineOptions] @returns {Promise<Partial<import('../public.d.ts').SvelteConfig> | undefined>}
loadSvelteConfig ( viteConfig , inlineOptions )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/load-svelte-config.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/load-svelte-config.js
MIT
function findConfigToLoad(viteConfig, inlineOptions) { const root = viteConfig?.root || process.cwd(); if (inlineOptions?.configFile) { const abolutePath = path.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : path.resolve(root, inlineOptions.configFile); if (!fs.existsSync(abolutePath)) { throw new Error(`failed to find svelte config file ${abolutePath}.`); } return abolutePath; } else { const existingKnownConfigFiles = knownSvelteConfigNames .map((candidate) => path.resolve(root, candidate)) .filter((file) => fs.existsSync(file)); if (existingKnownConfigFiles.length === 0) { log.debug(`no svelte config found at ${root}`, undefined, 'config'); return; } else if (existingKnownConfigFiles.length > 1) { log.warn( `found more than one svelte config file, using ${existingKnownConfigFiles[0]}. you should only have one!`, existingKnownConfigFiles ); } return existingKnownConfigFiles[0]; } }
@param {import('vite').UserConfig | undefined} viteConfig @param {Partial<import('../public.d.ts').Options> | undefined} inlineOptions @returns {string | undefined}
findConfigToLoad ( viteConfig , inlineOptions )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/load-svelte-config.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/load-svelte-config.js
MIT
export async function loadRaw(svelteRequest, compileSvelte, options) { const { id, filename, query } = svelteRequest; // raw svelte subrequest, compile on the fly and return requested subpart let compileData; const source = fs.readFileSync(filename, 'utf-8'); try { //avoid compileSvelte doing extra ssr stuff unless requested svelteRequest.ssr = query.compilerOptions?.generate === 'server'; compileData = await compileSvelte(svelteRequest, source, { ...options, // don't use dynamic vite-plugin-svelte defaults here to ensure stable result between ssr,dev and build compilerOptions: { dev: false, css: 'external', hmr: false, ...svelteRequest.query.compilerOptions }, emitCss: true }); } catch (e) { throw toRollupError(e, options); } let result; if (query.type === 'style') { result = compileData.compiled.css ?? { code: '', map: null }; } else if (query.type === 'script') { result = compileData.compiled.js; } else if (query.type === 'preprocessed') { result = compileData.preprocessed; } else if (query.type === 'all' && query.raw) { return allToRawExports(compileData, source); } else { throw new Error( `invalid "type=${query.type}" in ${id}. supported are script, style, preprocessed, all` ); } if (query.direct) { const supportedDirectTypes = ['script', 'style']; if (!supportedDirectTypes.includes(query.type)) { throw new Error( `invalid "type=${ query.type }" combined with direct in ${id}. supported are: ${supportedDirectTypes.join(', ')}` ); } log.debug(`load returns direct result for ${id}`, undefined, 'load'); let directOutput = result.code; // @ts-expect-error might not be SourceMap but toUrl check should suffice if (query.sourcemap && result.map?.toUrl) { // @ts-expect-error toUrl might not exist const map = `sourceMappingURL=${result.map.toUrl()}`; if (query.type === 'style') { directOutput += `\n\n/*# ${map} */\n`; } else if (query.type === 'script') { directOutput += `\n\n//# ${map}\n`; } } return directOutput; } else if (query.raw) { log.debug(`load returns raw result for ${id}`, undefined, 'load'); return toRawExports(result); } else { throw new Error(`invalid raw mode in ${id}, supported are raw, direct`); } }
utility function to compile ?raw and ?direct requests in load hook @param {import('../types/id.d.ts').SvelteRequest} svelteRequest @param {import('../types/compile.d.ts').CompileSvelte} compileSvelte @param {import('../types/options.d.ts').ResolvedOptions} options @returns {Promise<string>}
loadRaw ( svelteRequest , compileSvelte , options )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/load-raw.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/load-raw.js
MIT
function allToRawExports(compileData, source) { // flatten CompileData /** @type {Partial<import('../types/compile.d.ts').CompileData & { source: string }>} */ const exports = { ...compileData, ...compileData.compiled, source }; delete exports.compiled; delete exports.filename; // absolute path, remove to avoid it in output return toRawExports(exports); }
turn compileData and source into a flat list of raw exports @param {import('../types/compile.d.ts').CompileData} compileData @param {string} source
allToRawExports ( compileData , source )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/load-raw.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/load-raw.js
MIT
export async function saveSvelteMetadata(cacheDir, options) { const svelteMetadata = generateSvelteMetadata(options); const svelteMetadataPath = path.resolve(cacheDir, '_svelte_metadata.json'); const currentSvelteMetadata = JSON.stringify(svelteMetadata, (_, value) => { // Handle preprocessors return typeof value === 'function' ? value.toString() : value; }); /** @type {string | undefined} */ let existingSvelteMetadata; try { existingSvelteMetadata = await fs.readFile(svelteMetadataPath, 'utf8'); } catch { // ignore } await fs.mkdir(cacheDir, { recursive: true }); await fs.writeFile(svelteMetadataPath, currentSvelteMetadata); return currentSvelteMetadata !== existingSvelteMetadata; }
@param {string} cacheDir @param {import('../types/options.d.ts').ResolvedOptions} options @returns {Promise<boolean>} Whether the Svelte metadata has changed
saveSvelteMetadata ( cacheDir , options )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/optimizer.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/optimizer.js
MIT
function generateSvelteMetadata(options) { /** @type {Record<string, any>} */ const metadata = {}; for (const key of PREBUNDLE_SENSITIVE_OPTIONS) { metadata[key] = options[key]; } return metadata; }
@param {import('../types/options.d.ts').ResolvedOptions} options @returns {Partial<import('../types/options.d.ts').ResolvedOptions>}
generateSvelteMetadata ( options )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/optimizer.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/optimizer.js
MIT
function formatPackageStats(pkgStats) { const statLines = pkgStats.map((pkgStat) => { const duration = pkgStat.duration; const avg = duration / pkgStat.files; return [pkgStat.pkg, `${pkgStat.files}`, humanDuration(duration), humanDuration(avg)]; }); statLines.unshift(['package', 'files', 'time', 'avg']); const columnWidths = statLines.reduce( (widths, row) => { for (let i = 0; i < row.length; i++) { const cell = row[i]; if (widths[i] < cell.length) { widths[i] = cell.length; } } return widths; }, statLines[0].map(() => 0) ); const table = statLines .map((row) => row .map((cell, i) => { if (i === 0) { return cell.padEnd(columnWidths[i], ' '); } else { return cell.padStart(columnWidths[i], ' '); } }) .join('\t') ) .join('\n'); return table; }
@param {import('../types/vite-plugin-svelte-stats.d.ts').PackageStats[]} pkgStats @returns {string}
formatPackageStats ( pkgStats )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-stats.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-stats.js
MIT
constructor(cache) { this.#cache = cache; }
@param {import('./vite-plugin-svelte-cache.js').VitePluginSvelteCache} cache
constructor ( cache )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-stats.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-stats.js
MIT
startCollection(name, opts) { const options = { ...defaultCollectionOptions, ...opts }; /** @type {import('../types/vite-plugin-svelte-stats.d.ts').Stat[]} */ const stats = []; const collectionStart = performance.now(); const _this = this; let hasLoggedProgress = false; /** @type {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection} */ const collection = { name, options, stats, collectionStart, finished: false, start(file) { if (collection.finished) { throw new Error('called after finish() has been used'); } file = normalizePath(file); const start = performance.now(); /** @type {import('../types/vite-plugin-svelte-stats.d.ts').Stat} */ const stat = { file, start, end: start }; return () => { const now = performance.now(); stat.end = now; stats.push(stat); if (!hasLoggedProgress && options.logInProgress(collection, now)) { hasLoggedProgress = true; log.debug(`${name} in progress ...`, undefined, 'stats'); } }; }, async finish() { await _this.#finish(collection); } }; _this.#collections.push(collection); return collection; }
@param {string} name @param {Partial<import('../types/vite-plugin-svelte-stats.d.ts').CollectionOptions>} [opts] @returns {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection}
startCollection ( name , opts )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-stats.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-stats.js
MIT
function setLevel(level) { if (level === _level) { return; } const levelIndex = levels.indexOf(level); if (levelIndex > -1) { _level = level; for (let i = 0; i < levels.length; i++) { loggers[levels[i]].enabled = i >= levelIndex; } } else { _log(loggers.error, `invalid log level: ${level} `); } }
@param {import('../types/log.d.ts').LogLevel} level @returns {void}
setLevel ( level )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
function _log(logger, message, payload, namespace) { if (!logger.enabled) { return; } if (logger.isDebug) { let log = logger.log; if (namespace) { if (!isDebugNamespaceEnabled(namespace)) { return; } log = logger.log.extend(namespace); } if (payload !== undefined) { log(message, payload); } else { log(message); } } else { logger.log( logger.color( `${new Date().toLocaleTimeString()} [${prefix}${ namespace ? `:${namespace}` : '' }] ${message}` ) ); if (payload) { logger.log(payload); } } }
@param {any} logger @param {string} message @param {any} [payload] @param {string} [namespace] @returns
_log ( logger , message , payload , namespace )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
function createLogger(level) { const logger = loggers[level]; const logFn = /** @type {import('../types/log.d.ts').LogFn} */ (_log.bind(null, logger)); /** @type {Set<string>} */ const logged = new Set(); /** @type {import('../types/log.d.ts').SimpleLogFn} */ const once = function (message, payload, namespace) { if (!logger.enabled || logged.has(message)) { return; } logged.add(message); logFn.apply(null, [message, payload, namespace]); }; Object.defineProperty(logFn, 'enabled', { get() { return logger.enabled; } }); Object.defineProperty(logFn, 'once', { get() { return once; } }); return logFn; }
@param {import('../types/log.d.ts').LogLevel} level @returns {import('../types/log.d.ts').LogFn}
createLogger ( level )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
function ignoreCompilerWarning(warning, isBuild, emitCss) { return ( (!emitCss && warning.code === 'css_unused_selector') || // same as rollup-plugin-svelte (!isBuild && isNoScopableElementWarning(warning)) ); }
@param {import('svelte/compiler').Warning} warning @param {boolean} isBuild @param {boolean} [emitCss] @returns {boolean}
ignoreCompilerWarning ( warning , isBuild , emitCss )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
function isNoScopableElementWarning(warning) { // see https://github.com/sveltejs/vite-plugin-svelte/issues/153 return warning.code === 'css_unused_selector' && warning.message.includes('"*"'); }
@param {import('svelte/compiler').Warning} warning @returns {boolean}
isNoScopableElementWarning ( warning )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
function buildExtraWarnings(warnings, isBuild) { const extraWarnings = []; if (!isBuild) { const noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w)); if (noScopableElementWarnings.length > 0) { // in case there are multiple, use last one as that is the one caused by our *{} rule const noScopableElementWarning = noScopableElementWarnings[noScopableElementWarnings.length - 1]; extraWarnings.push({ ...noScopableElementWarning, code: 'vite-plugin-svelte-css-no-scopable-elements', message: "No scopable elements found in template. If you're using global styles in the style tag, you should move it into an external stylesheet file and import it in JS. See https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#where-should-i-put-my-global-styles." }); } } return extraWarnings; }
@param {import('svelte/compiler').Warning[]} warnings @param {boolean} isBuild @returns {import('svelte/compiler').Warning[]}
buildExtraWarnings ( warnings , isBuild )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
function warnDev(w) { if (w.filename?.includes('node_modules')) { if (isDebugNamespaceEnabled('node-modules-onwarn')) { log.debug(buildExtendedLogMessage(w), undefined, 'node-modules-onwarn'); } } else if (log.info.enabled) { log.info(buildExtendedLogMessage(w)); } }
@param {import('svelte/compiler').Warning} w
warnDev ( w )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
function warnBuild(w) { if (w.filename?.includes('node_modules')) { if (isDebugNamespaceEnabled('node-modules-onwarn')) { log.debug(buildExtendedLogMessage(w), w.frame, 'node-modules-onwarn'); } } else if (log.warn.enabled) { log.warn(buildExtendedLogMessage(w), w.frame); } }
@param {import('svelte/compiler').Warning & {frame?: string}} w
warnBuild ( w )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
export function isDebugNamespaceEnabled(namespace) { return debug.enabled(`${prefix}:${namespace}`); }
@param {string} namespace @returns {boolean}
isDebugNamespaceEnabled ( namespace )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/log.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/log.js
MIT
export function ensureWatchedFile(watcher, file, root) { if ( file && // only need to watch if out of root !file.startsWith(root + '/') && // some rollup plugins use null bytes for private resolved Ids !file.includes('\0') && fs.existsSync(file) ) { // resolve file to normalized system path watcher.add(path.resolve(file)); } }
taken from vite utils @param {import('vite').FSWatcher} watcher @param {string | null} file @param {string} root @returns {void}
ensureWatchedFile ( watcher , file , root )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/watch.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/watch.js
MIT
function lineFromFrame(lineNo, frame) { if (!frame) { return ''; } const lines = frame.split('\n'); const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `)); return errorLine ? errorLine.substring(errorLine.indexOf(': ') + 3) : ''; }
extract line with number from codeframe @param {number} lineNo @param {string} [frame] @returns {string}
lineFromFrame ( lineNo , frame )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/error.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/error.js
MIT
function couldBeFixedByCssPreprocessor(code) { return code === 'expected_token' || code === 'unexpected_eof' || code?.startsWith('css_'); }
@param {string} code the svelte error code @see https://github.com/sveltejs/svelte/blob/main/packages/svelte/src/compiler/errors.js @returns {boolean}
couldBeFixedByCssPreprocessor ( code )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/error.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/error.js
MIT
export function enhanceCompileError(err, originalCode, preprocessors) { preprocessors = arraify(preprocessors ?? []); /** @type {string[]} */ const additionalMessages = []; // Handle incorrect CSS preprocessor usage if (couldBeFixedByCssPreprocessor(err.code)) { // Reference from Svelte: https://github.com/sveltejs/svelte/blob/9926347ad9dbdd0f3324d5538e25dcb7f5e442f8/packages/svelte/src/compiler/preprocess/index.js#L257 const styleRe = /<!--[^]*?-->|<style((?:\s+[^=>'"/]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"/]+)*\s*)(?:\/>|>([\S\s]*?)<\/style>)/g; let m; while ((m = styleRe.exec(originalCode))) { // Warn missing lang attribute if (!m[1]?.includes('lang=')) { additionalMessages.push('Did you forget to add a lang attribute to your style tag?'); } // Warn missing style preprocessor if ( preprocessors.every((p) => p.style == null || p.name === 'inject-scope-everything-rule') ) { const preprocessorType = m[1]?.match(/lang="(.+?)"/)?.[1] ?? 'style'; additionalMessages.push( `Did you forget to add a ${preprocessorType} preprocessor? See https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/preprocess.md for more information.` ); } } } if (additionalMessages.length) { err.message += '\n\n- ' + additionalMessages.join('\n- '); } return err; } /** * @param {T | T[]} value * @template T */ function arraify(value) {
@param {import('svelte/compiler').Warning & Error} err a svelte compiler error, which is a mix of Warning and an error @param {string} originalCode @param {import('../public.d.ts').Options['preprocess']} [preprocessors]
enhanceCompileError ( err , originalCode , preprocessors )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/error.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/error.js
MIT
export function isCommonDepWithoutSvelteField(dependency) { return ( COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some( (prefix) => prefix.startsWith('@') ? dependency.startsWith(prefix) : dependency.substring(dependency.lastIndexOf('/') + 1).startsWith(prefix) // check prefix omitting @scope/ ) ); }
Test for common dependency names that tell us it is not a package including a svelte field, eg. eslint + plugins. This speeds up the find process as we don't have to try and require the package.json for all of them @param {string} dependency @returns {boolean} true if it is a dependency without a svelte field
isCommonDepWithoutSvelteField ( dependency )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/dependencies.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/dependencies.js
MIT
async function compileSvelte(options, { filename, code }, statsCollection) { let css = options.compilerOptions.css; if (css !== 'injected') { // TODO ideally we'd be able to externalize prebundled styles too, but for now always put them in the js css = 'injected'; } /** @type {import('svelte/compiler').CompileOptions} */ const compileOptions = { dev: true, // default to dev: true because prebundling is only used in dev ...options.compilerOptions, css, filename, generate: 'client' }; if (compileOptions.hmr && options.emitCss) { const hash = `s-${safeBase64Hash(normalize(filename, options.root))}`; compileOptions.cssHash = () => hash; } let preprocessed; if (options.preprocess) { try { preprocessed = await svelte.preprocess(code, options.preprocess, { filename }); } catch (e) { e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ''}`; throw e; } if (preprocessed.map) compileOptions.sourcemap = preprocessed.map; } const finalCode = preprocessed ? preprocessed.code : code; const dynamicCompileOptions = await options?.dynamicCompileOptions?.({ filename, code: finalCode, compileOptions }); if (dynamicCompileOptions && log.debug.enabled) { log.debug( `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`, undefined, 'compile' ); } const finalCompileOptions = dynamicCompileOptions ? { ...compileOptions, ...dynamicCompileOptions } : compileOptions; const endStat = statsCollection?.start(filename); const compiled = svelte.compile(finalCode, finalCompileOptions); if (endStat) { endStat(); } return compiled.js.map ? compiled.js.code + '//# sourceMappingURL=' + compiled.js.map.toUrl() : compiled.js.code; }
@param {import('../types/options.d.ts').ResolvedOptions} options @param {{ filename: string, code: string }} input @param {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection} [statsCollection] @returns {Promise<string>}
compileSvelte ( options , { filename , code } , statsCollection )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/esbuild.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/esbuild.js
MIT
async function compileSvelteModule(options, { filename, code }, statsCollection) { const endStat = statsCollection?.start(filename); const compiled = svelte.compileModule(code, { dev: options.compilerOptions?.dev ?? true, // default to dev: true because prebundling is only used in dev filename, generate: 'client' }); if (endStat) { endStat(); } return compiled.js.map ? compiled.js.code + '//# sourceMappingURL=' + compiled.js.map.toUrl() : compiled.js.code; }
@param {import('../types/options.d.ts').ResolvedOptions} options @param {{ filename: string; code: string }} input @param {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection} [statsCollection] @returns {Promise<string>}
compileSvelteModule ( options , { filename , code } , statsCollection )
javascript
sveltejs/vite-plugin-svelte
packages/vite-plugin-svelte/src/utils/esbuild.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/esbuild.js
MIT
export function transformValidation() { return [ { name: 'transform-validation:1', enforce: 'pre', transform(code, id) { if (id.endsWith('.svelte')) { return code.replace('__JS_TRANSFORM_1__', '__JS_TRANSFORM_2__'); } else if (id.endsWith('.css')) { return code.replace('__CSS_TRANSFORM_1__', '__CSS_TRANSFORM_2__'); } } }, { name: 'transform-validation:2', transform(code, id) { if (id.endsWith('.svelte')) { return code.replace('__JS_TRANSFORM_2__', '__JS_TRANSFORM_3__'); } else if (id.endsWith('.css')) { return code.replace('__CSS_TRANSFORM_2__', 'red'); } } }, { name: 'transform-validation:3', enforce: 'post', transform(code, id) { if (id.endsWith('.svelte')) { return code.replace('__JS_TRANSFORM_3__', 'Hello world'); } // can't handle css here as in build, it would be `export default {}` } } ]; }
Ensure transform flow is not interrupted @returns {import('vite').Plugin[]}
transformValidation ( )
javascript
sveltejs/vite-plugin-svelte
packages/e2e-tests/_test_dependencies/vite-plugins/index.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/e2e-tests/_test_dependencies/vite-plugins/index.js
MIT
function workaroundInlineSvelteCssIssue() { return { name: 'workaround-inline-svelte-css-issue', enforce: 'pre', resolveId(id) { // SvelteKit relies on a previous behaviour in v-p-s where it strips out the inline // query to get the CSS result, however this no longer works in Vite 6 and should be // fixed in SvelteKit instead, otherwise FOUC will happen in dev. if (id.includes('?svelte')) { return id.replace(/&inline=$/, ''); } } }; }
Workaround until https://github.com/sveltejs/kit/pull/13007 is merged @returns {import('vite').Plugin}
workaroundInlineSvelteCssIssue ( )
javascript
sveltejs/vite-plugin-svelte
packages/e2e-tests/kit-node/vite.config.js
https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/e2e-tests/kit-node/vite.config.js
MIT
const SidebarMenuItemLink = (props) => ( (props.to || props.href) ? ( props.to ? ( <Link to={ props.to } className={`${props.classBase}__entry__link`}> { props.children } </Link> ) : ( <a href={ props.href } target="_blank" rel="noopener noreferrer" className={`${props.classBase}__entry__link`} > { props.children } </a> ) ) : ( <a href="javascript:;" className={`${props.classBase}__entry__link`} onClick={ () => props.onToggle() } > { props.children } </a> ) ) SidebarMenuItemLink.propTypes = {
Renders a collapse trigger or a ReactRouter Link
SidebarMenuItemLink
javascript
0wczar/airframe-react
app/components/SidebarMenu/SidebarMenuItem.js
https://github.com/0wczar/airframe-react/blob/master/app/components/SidebarMenu/SidebarMenuItem.js
MIT
_findClosestBreakpoint = (breakpoint, definition) => { let found = 12; for (let bp of _.drop(breakPointSteps, _.indexOf(breakPointSteps, breakpoint))) { if (!_.isUndefined(definition[bp])) { found = definition[bp]; } } return found; }
Finds the nearest breakpoint relative to the one provided in the first param. For example - when the `definition` param contains such bps - { md: 6, xs: 8 }, for `breakpoint` - xl/md will return 6
=
javascript
0wczar/airframe-react
app/components/FloatGrid/Row.js
https://github.com/0wczar/airframe-react/blob/master/app/components/FloatGrid/Row.js
MIT
SlimSidebarAnimate.prototype.assignParentElement = function (parentElement) { // Reassign Observer Element this._nodesObserver.disconnect(); this._nodesObserver.observe(parentElement, { attributes: true, attributeFilter: ['class'], attributeOldValue: true, subtree: false }); };
Assigns the parent sidebar element, and attaches a Mutation Observer which watches the coallapsable nodes inside of the sidebar menu and animates them on chenages @param {HTMLElement} parentElement SidebarMenu parent
SlimSidebarAnimate.prototype.assignParentElement ( parentElement )
javascript
0wczar/airframe-react
packages/dashboard-style/js-modules/slim-sidebar-animate.js
https://github.com/0wczar/airframe-react/blob/master/packages/dashboard-style/js-modules/slim-sidebar-animate.js
MIT
function getDashboardFetcher(serviceUrl) { var dashboardVersions = null; return function dashboardFetcher() { if (!dashboardVersions) { var targetUrl = urlJoin(serviceUrl, "/dashboards/versions"); return fetch(targetUrl) .then(function(response) { return response.json() }) .then(function(versions) { // Store in cache dashboardVersions = versions; return versions; }) .catch(function(reason) { console.log("Failed to fetch dashbaords versions from remote service. Reason: " + reason); }); } else { var resultPromise = new Promise(function(resolve) { resolve(dashboardVersions); }); return resultPromise; } } };
Returns a fetcher function which retrieves the available dashboard versions. @param {string} serviceUrl url of the service which returns all of the dashboards
getDashboardFetcher ( serviceUrl )
javascript
0wczar/airframe-react
packages/dashboard-style/js-modules/dashboard-version.js
https://github.com/0wczar/airframe-react/blob/master/packages/dashboard-style/js-modules/dashboard-version.js
MIT
function getVersions(fetcher) { return fetcher(); }
Returns all of the available dashboards versions @param {FetcherFunction} fetcher fetcher function created by getDashboardFetcher
getVersions ( fetcher )
javascript
0wczar/airframe-react
packages/dashboard-style/js-modules/dashboard-version.js
https://github.com/0wczar/airframe-react/blob/master/packages/dashboard-style/js-modules/dashboard-version.js
MIT
function getCurrentVersion(fetcher, label, name) { return fetcher() .then(function (dashboards) { var output = null; dashboards.forEach(function(dashboardDef) { if ( dashboardDef.label === label && dashboardDef.dashboardName === name ) { output = dashboardDef; } }); return output; }); }
Returns the latest version of a specific dashboard @param {FetcherFunction} fetcher fetcher function created by getDashboardFetcher @param {string} label label of the dashboard (jQuery, react, angular etc...) @param {string} name name of the dashboard (default, spin etc...)
getCurrentVersion ( fetcher , label , name )
javascript
0wczar/airframe-react
packages/dashboard-style/js-modules/dashboard-version.js
https://github.com/0wczar/airframe-react/blob/master/packages/dashboard-style/js-modules/dashboard-version.js
MIT
SlimMenuAnimate.prototype.assignSidebarElement = function (sidebarElement) { var _this = this; _this._sidebarElement = sidebarElement; _this._triggerElements = Array.from( _this._sidebarElement.querySelectorAll( '.sidebar-menu .sidebar-menu__entry.sidebar-menu__entry--nested' ) ); _this._triggerElements.forEach(function (triggerElement) { triggerElement.addEventListener('mouseenter', _this.mouseInHandler); triggerElement.addEventListener('mouseleave', _this.mouseOutHandler); }); };
Assigns the parent sidebar element, and attaches hover listeners @param {HTMLElement} parentElement SidebarMenu parent
SlimMenuAnimate.prototype.assignSidebarElement ( sidebarElement )
javascript
0wczar/airframe-react
packages/dashboard-style/js-modules/slim-menu-animate.js
https://github.com/0wczar/airframe-react/blob/master/packages/dashboard-style/js-modules/slim-menu-animate.js
MIT
function Router (options) { if (!(this instanceof Router)) { return new Router(options) } const opts = options || {} function router (req, res, next) { router.handle(req, res, next) } // inherit from the correct prototype Object.setPrototypeOf(router, this) router.caseSensitive = opts.caseSensitive router.mergeParams = opts.mergeParams router.params = {} router.strict = opts.strict router.stack = [] return router }
Initialize a new `Router` with the given `options`. @param {object} [options] @return {Router} which is a callable function @public
Router ( options )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
Router.prototype.param = function param (name, fn) { if (!name) { throw new TypeError('argument name is required') } if (typeof name !== 'string') { throw new TypeError('argument name must be a string') } if (!fn) { throw new TypeError('argument fn is required') } if (typeof fn !== 'function') { throw new TypeError('argument fn must be a function') } let params = this.params[name] if (!params) { params = this.params[name] = [] } params.push(fn) return this }
Map the given param placeholder `name`(s) to the given callback. Parameter mapping is used to provide pre-conditions to routes which use normalized placeholders. For example a _:user_id_ parameter could automatically load a user's information from the database without any additional code. The callback uses the same signature as middleware, the only difference being that the value of the placeholder is passed, in this case the _id_ of the user. Once the `next()` function is invoked, just like middleware it will continue on to execute the route, or subsequent parameter functions. Just like in middleware, you must either respond to the request or call next to avoid stalling the request. router.param('user_id', function(req, res, next, id){ User.find(id, function(err, user){ if (err) { return next(err) } else if (!user) { return next(new Error('failed to load user')) } req.user = user next() }) }) @param {string} name @param {function} fn @public
param ( name , fn )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
Router.prototype.use = function use (handler) { let offset = 0 let path = '/' // default path to '/' // disambiguate router.use([handler]) if (typeof handler !== 'function') { let arg = handler while (Array.isArray(arg) && arg.length !== 0) { arg = arg[0] } // first arg is the path if (typeof arg !== 'function') { offset = 1 path = handler } } const callbacks = flatten.call(slice.call(arguments, offset), Infinity) if (callbacks.length === 0) { throw new TypeError('argument handler is required') } for (let i = 0; i < callbacks.length; i++) { const fn = callbacks[i] if (typeof fn !== 'function') { throw new TypeError('argument handler must be a function') } // add the middleware debug('use %o %s', path, fn.name || '<anonymous>') const layer = new Layer(path, { sensitive: this.caseSensitive, strict: false, end: false }, fn) layer.route = undefined this.stack.push(layer) } return this }
Use the given middleware function, with optional path, defaulting to "/". Use (like `.all`) will run for any http METHOD, but it will not add handlers for those methods so OPTIONS requests will not consider `.use` functions even if they could respond. The other difference is that _route_ path is stripped and not visible to the handler function. The main effect of this feature is that mounted handlers can operate without any code changes regardless of the "prefix" pathname. @public
use ( handler )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
Router.prototype.route = function route (path) { const route = new Route(path) const layer = new Layer(path, { sensitive: this.caseSensitive, strict: this.strict, end: true }, handle) function handle (req, res, next) { route.dispatch(req, res, next) } layer.route = route this.stack.push(layer) return route }
Create a new Route for the given path. Each route contains a separate middleware stack and VERB handlers. See the Route api documentation for details on adding handlers and middleware to routes. @param {string} path @return {Route} @public
route ( path )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
function generateOptionsResponder (res, methods) { return function onDone (fn, err) { if (err || methods.length === 0) { return fn(err) } trySendOptionsResponse(res, methods, fn) } }
Generate a callback that will make an OPTIONS response. @param {OutgoingMessage} res @param {array} methods @private
generateOptionsResponder ( res , methods )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
function getPathname (req) { try { return parseUrl(req).pathname } catch (err) { return undefined } }
Get pathname of request. @param {IncomingMessage} req @private
getPathname ( req )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
function mergeParams (params, parent) { if (typeof parent !== 'object' || !parent) { return params } // make copy of parent for base const obj = Object.assign({}, parent) // simple non-numeric merging if (!(0 in params) || !(0 in parent)) { return Object.assign(obj, params) } let i = 0 let o = 0 // determine numeric gap in params while (i in params) { i++ } // determine numeric gap in parent while (o in parent) { o++ } // offset numeric indices in params before merge for (i--; i >= 0; i--) { params[i + o] = params[i] // create holes for the merge when necessary if (i < o) { delete params[i] } } return Object.assign(obj, params) }
Merge params with parent params @private
mergeParams ( params , parent )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
function processParams (params, layer, called, req, res, done) { // captured parameters from the layer, keys and values const keys = layer.keys // fast track if (!keys || keys.length === 0) { return done() } let i = 0 let paramIndex = 0 let key let paramVal let paramCallbacks let paramCalled // process params in order // param callbacks can be async function param (err) { if (err) { return done(err) } if (i >= keys.length) { return done() } paramIndex = 0 key = keys[i++] paramVal = req.params[key] paramCallbacks = params[key] paramCalled = called[key] if (paramVal === undefined || !paramCallbacks) { return param() } // param previously called with same value or error occurred if (paramCalled && (paramCalled.match === paramVal || (paramCalled.error && paramCalled.error !== 'route'))) { // restore value req.params[key] = paramCalled.value // next param return param(paramCalled.error) } called[key] = paramCalled = { error: null, match: paramVal, value: paramVal } paramCallback() } // single param callbacks function paramCallback (err) { const fn = paramCallbacks[paramIndex++] // store updated value paramCalled.value = req.params[key] if (err) { // store error paramCalled.error = err param(err) return } if (!fn) return param() try { const ret = fn(req, res, paramCallback, paramVal, key) if (isPromise(ret)) { if (!(ret instanceof Promise)) { deprecate('parameters that are Promise-like are deprecated, use a native Promise instead') } ret.then(null, function (error) { paramCallback(error || new Error('Rejected promise')) }) } } catch (e) { paramCallback(e) } } param() }
Process any parameters for the layer. @private
processParams ( params , layer , called , req , res , done )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
function restore (fn, obj) { const props = new Array(arguments.length - 2) const vals = new Array(arguments.length - 2) for (let i = 0; i < props.length; i++) { props[i] = arguments[i + 2] vals[i] = obj[props[i]] } return function () { // restore vals for (let i = 0; i < props.length; i++) { obj[props[i]] = vals[i] } return fn.apply(this, arguments) } }
Restore obj props after function @private
restore ( fn , obj )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
function trySendOptionsResponse (res, methods, next) { try { sendOptionsResponse(res, methods) } catch (err) { next(err) } }
Try to send an OPTIONS response. @private
trySendOptionsResponse ( res , methods , next )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
function getProtohost (url) { if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { return undefined } const searchIndex = url.indexOf('?') const pathLength = searchIndex !== -1 ? searchIndex : url.length const fqdnIndex = url.substring(0, pathLength).indexOf('://') return fqdnIndex !== -1 ? url.substring(0, url.indexOf('/', 3 + fqdnIndex)) : undefined } /** * Match path to a layer. * * @param {Layer} layer * @param {string} path * @private */ function matchLayer (layer, path) { try { return layer.match(path) } catch (err) { return err } } /** * Merge params with parent params * * @private */ function mergeParams (params, parent) { if (typeof parent !== 'object' || !parent) { return params } // make copy of parent for base const obj = Object.assign({}, parent) // simple non-numeric merging if (!(0 in params) || !(0 in parent)) { return Object.assign(obj, params) } let i = 0 let o = 0 // determine numeric gap in params while (i in params) { i++ } // determine numeric gap in parent while (o in parent) { o++ } // offset numeric indices in params before merge for (i--; i >= 0; i--) { params[i + o] = params[i] // create holes for the merge when necessary if (i < o) { delete params[i] } } return Object.assign(obj, params) } /** * Process any parameters for the layer. * * @private */ function processParams (params, layer, called, req, res, done) { // captured parameters from the layer, keys and values const keys = layer.keys // fast track if (!keys || keys.length === 0) { return done() } let i = 0 let paramIndex = 0 let key let paramVal let paramCallbacks let paramCalled // process params in order // param callbacks can be async function param (err) { if (err) { return done(err) } if (i >= keys.length) { return done() } paramIndex = 0 key = keys[i++] paramVal = req.params[key] paramCallbacks = params[key] paramCalled = called[key] if (paramVal === undefined || !paramCallbacks) { return param() } // param previously called with same value or error occurred if (paramCalled && (paramCalled.match === paramVal || (paramCalled.error && paramCalled.error !== 'route'))) { // restore value req.params[key] = paramCalled.value // next param return param(paramCalled.error) } called[key] = paramCalled = { error: null, match: paramVal, value: paramVal } paramCallback() } // single param callbacks function paramCallback (err) { const fn = paramCallbacks[paramIndex++] // store updated value paramCalled.value = req.params[key] if (err) { // store error paramCalled.error = err param(err) return } if (!fn) return param() try { const ret = fn(req, res, paramCallback, paramVal, key) if (isPromise(ret)) { if (!(ret instanceof Promise)) { deprecate('parameters that are Promise-like are deprecated, use a native Promise instead') } ret.then(null, function (error) { paramCallback(error || new Error('Rejected promise')) }) } } catch (e) { paramCallback(e) } } param() } /** * Restore obj props after function * * @private */ function restore (fn, obj) { const props = new Array(arguments.length - 2) const vals = new Array(arguments.length - 2) for (let i = 0; i < props.length; i++) { props[i] = arguments[i + 2] vals[i] = obj[props[i]] } return function () { // restore vals for (let i = 0; i < props.length; i++) { obj[props[i]] = vals[i] } return fn.apply(this, arguments) } } /** * Send an OPTIONS response. * * @private */ function sendOptionsResponse (res, methods) { const options = Object.create(null) // build unique method map for (let i = 0; i < methods.length; i++) { options[methods[i]] = true } // construct the allow list const allow = Object.keys(options).sort().join(', ') // send response res.setHeader('Allow', allow) res.setHeader('Content-Length', Buffer.byteLength(allow)) res.setHeader('Content-Type', 'text/plain') res.setHeader('X-Content-Type-Options', 'nosniff') res.end(allow) } /** * Try to send an OPTIONS response. * * @private */ function trySendOptionsResponse (res, methods, next) { try { sendOptionsResponse(res, methods) } catch (err) { next(err) } } /** * Wrap a function * * @private */ function wrap (old, fn) {
Get get protocol + host for a URL. @param {string} url @private
getProtohost ( url )
javascript
pillarjs/router
index.js
https://github.com/pillarjs/router/blob/master/index.js
MIT
Layer.prototype.handleError = function handleError (error, req, res, next) { const fn = this.handle if (fn.length !== 4) { // not a standard error handler return next(error) } try { // invoke function const ret = fn(error, req, res, next) // wait for returned promise if (isPromise(ret)) { if (!(ret instanceof Promise)) { deprecate('handlers that are Promise-like are deprecated, use a native Promise instead') } ret.then(null, function (error) { next(error || new Error('Rejected promise')) }) } } catch (err) { next(err) } }
Handle the error for the layer. @param {Error} error @param {Request} req @param {Response} res @param {function} next @api private
handleError ( error , req , res , next )
javascript
pillarjs/router
lib/layer.js
https://github.com/pillarjs/router/blob/master/lib/layer.js
MIT
Layer.prototype.handleRequest = function handleRequest (req, res, next) { const fn = this.handle if (fn.length > 3) { // not a standard request handler return next() } try { // invoke function const ret = fn(req, res, next) // wait for returned promise if (isPromise(ret)) { if (!(ret instanceof Promise)) { deprecate('handlers that are Promise-like are deprecated, use a native Promise instead') } ret.then(null, function (error) { next(error || new Error('Rejected promise')) }) } } catch (err) { next(err) } }
Handle the request for the layer. @param {Request} req @param {Response} res @param {function} next @api private
handleRequest ( req , res , next )
javascript
pillarjs/router
lib/layer.js
https://github.com/pillarjs/router/blob/master/lib/layer.js
MIT
Layer.prototype.match = function match (path) { let match if (path != null) { // fast path non-ending match for / (any path matches) if (this.slash) { this.params = {} this.path = '' return true } let i = 0 while (!match && i < this.matchers.length) { // match the path match = this.matchers[i](path) i++ } } if (!match) { this.params = undefined this.path = undefined return false } // store values this.params = match.params this.path = match.path this.keys = Object.keys(match.params) return true }
Check if this route matches `path`, if so populate `.params`. @param {String} path @return {Boolean} @api private
match ( path )
javascript
pillarjs/router
lib/layer.js
https://github.com/pillarjs/router/blob/master/lib/layer.js
MIT
function decodeParam (val) { if (typeof val !== 'string' || val.length === 0) { return val } try { return decodeURIComponent(val) } catch (err) { if (err instanceof URIError) { err.message = 'Failed to decode param \'' + val + '\'' err.status = 400 } throw err } }
Decode param value. @param {string} val @return {string} @private
decodeParam ( val )
javascript
pillarjs/router
lib/layer.js
https://github.com/pillarjs/router/blob/master/lib/layer.js
MIT
function loosen (path) { if (path instanceof RegExp || path === '/') { return path } return Array.isArray(path) ? path.map(function (p) { return loosen(p) }) : String(path).replace(TRAILING_SLASH_REGEXP, '') }
Loosens the given path for path-to-regexp matching.
loosen ( path )
javascript
pillarjs/router
lib/layer.js
https://github.com/pillarjs/router/blob/master/lib/layer.js
MIT
function Route (path) { debug('new %o', path) this.path = path this.stack = [] // route handlers for various http methods this.methods = Object.create(null) }
Initialize `Route` with the given `path`, @param {String} path @api private
Route ( path )
javascript
pillarjs/router
lib/route.js
https://github.com/pillarjs/router/blob/master/lib/route.js
MIT
Route.prototype._methods = function _methods () { const methods = Object.keys(this.methods) // append automatic head if (this.methods.get && !this.methods.head) { methods.push('head') } for (let i = 0; i < methods.length; i++) { // make upper case methods[i] = methods[i].toUpperCase() } return methods }
@return {array} supported HTTP methods @private
_methods ( )
javascript
pillarjs/router
lib/route.js
https://github.com/pillarjs/router/blob/master/lib/route.js
MIT
Route.prototype.dispatch = function dispatch (req, res, done) { let idx = 0 const stack = this.stack let sync = 0 if (stack.length === 0) { return done() } let method = typeof req.method === 'string' ? req.method.toLowerCase() : req.method if (method === 'head' && !this.methods.head) { method = 'get' } req.route = this next() function next (err) { // signal to exit route if (err && err === 'route') { return done() } // signal to exit router if (err && err === 'router') { return done(err) } // no more matching layers if (idx >= stack.length) { return done(err) } // max sync stack if (++sync > 100) { return setImmediate(next, err) } let layer let match // find next matching layer while (match !== true && idx < stack.length) { layer = stack[idx++] match = !layer.method || layer.method === method } // no match if (match !== true) { return done(err) } if (err) { layer.handleError(err, req, res, next) } else { layer.handleRequest(req, res, next) } sync = 0 } }
dispatch req, res into this route @private
dispatch ( req , res , done )
javascript
pillarjs/router
lib/route.js
https://github.com/pillarjs/router/blob/master/lib/route.js
MIT
Route.prototype.all = function all (handler) { const callbacks = flatten.call(slice.call(arguments), Infinity) if (callbacks.length === 0) { throw new TypeError('argument handler is required') } for (let i = 0; i < callbacks.length; i++) { const fn = callbacks[i] if (typeof fn !== 'function') { throw new TypeError('argument handler must be a function') } const layer = Layer('/', {}, fn) layer.method = undefined this.methods._all = true this.stack.push(layer) } return this }
Add a handler for all HTTP verbs to this route. Behaves just like middleware and can respond or call `next` to continue processing. You can use multiple `.all` call to add multiple handlers. function check_something(req, res, next){ next() } function validate_user(req, res, next){ next() } route .all(validate_user) .all(check_something) .get(function(req, res, next){ res.send('hello world') }) @param {array|function} handler @return {Route} for chaining @api public
all ( handler )
javascript
pillarjs/router
lib/route.js
https://github.com/pillarjs/router/blob/master/lib/route.js
MIT
module.exports = function projectPath(...paths) { return path.resolve(process.env.INIT_CWD, ...paths); }
A function that can be used to resolve a path relatively to the project directory. We often want to resolve paths relatively to the project root directory. To do that, we use the `INIT_CWD` environment variable provided by Gulp. This variable always resolves to the project root directory so we use it as the seed path and then add the remaining arguments passed and resolving everything using the `path.resolve` function. The returned path is a fully resolved absolute path relative to the project root directory.
projectPath ( ... paths )
javascript
vigetlabs/blendid
gulpfile.js/lib/projectPath.js
https://github.com/vigetlabs/blendid/blob/master/gulpfile.js/lib/projectPath.js
MIT
function registerReqListeners(req, fn){ req.on('response', function (res) { fn(null, res); }); req.on('error', fn); }
Register event listeners on a request object to convert standard http request events into appropriate call backs. @param {Request} req The http request @param {Function} fn(err, res) The callback function. err - The exception if an exception occurred while sending the http request (for example if internet connection was lost). res - The http response if no exception occurred. @api private
registerReqListeners ( req , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
var Client = module.exports = exports = function Client(options) { if (!options.key) throw new Error('aws "key" required'); if (!options.secret) throw new Error('aws "secret" required'); if (!options.bucket) throw new Error('aws "bucket" required'); if (options.style && options.style !== 'virtualHosted' && options.style !== 'path') { throw new Error('style must be "virtualHosted" or "path"'); } if (options.port !== undefined && isNaN(parseInt(options.port))) { throw new Error('port must be a number.'); } var invalidness = isInvalid(options.bucket); var dnsUncompliance = isNotDnsCompliant(options.bucket); if (invalidness) { throw new Error('Bucket name "' + options.bucket + '" ' + invalidness + '.'); } // Save original options, we will need them for Client#copyTo this.options = utils.merge({}, options); // Make sure we don't override options the user passes in. options = utils.merge({}, options); autoDetermineStyle(options); if (!options.endpoint) { if (!options.region || options.region === 'us-standard' || options.region === 'us-east-1') { options.endpoint = 's3.amazonaws.com'; options.region = 'us-standard'; } else { options.endpoint = 's3-' + options.region + '.amazonaws.com'; } if (options.region !== 'us-standard') { if (dnsUncompliance) { throw new Error('Outside of the us-standard region, bucket names must' + ' be DNS-compliant. The name "' + options.bucket + '" ' + dnsUncompliance + '.'); } } } else { options.region = undefined; } var portSuffix = 'undefined' == typeof options.port ? "" : ":" + options.port; this.secure = 'undefined' == typeof options.port; if (options.style === 'virtualHosted') { this.host = options.bucket + '.' + options.endpoint; this.urlBase = options.bucket + '.' + options.endpoint + portSuffix; } else { this.host = options.endpoint; this.urlBase = options.endpoint + portSuffix + '/' + options.bucket; } // HTTP in Node.js < 0.12 is horribly broken, and leads to lots of "socket // hang up" errors: https://github.com/LearnBoost/knox/issues/116. See // https://github.com/LearnBoost/knox/issues/116#issuecomment-15045187 and // https://github.com/substack/hyperquest#rant this.agent = false; utils.merge(this, options); this.url = this.secure ? this.https : this.http;
Initialize a `Client` with the given `options`. Required: - `key` amazon api key - `secret` amazon secret - `bucket` bucket name string, ex: "learnboost" @param {Object} options @api public
Client ( options )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.put = function(filename, headers){ headers = utils.merge({}, headers || {}); return this.request('PUT', encodeSpecialCharacters(filename), headers);
PUT data to `filename` with optional `headers`. Example: // Fetch the size fs.stat('Readme.md', function(err, stat){ // Create our request var req = client.put('/test/Readme.md', { 'Content-Length': stat.size , 'Content-Type': 'text/plain' }); fs.readFile('Readme.md', function(err, buf){ // Output response req.on('response', function(res){ console.log(res.statusCode); console.log(res.headers); res.pipe(fs.createWriteStream('Readme.md')); }); // Send the request with the file's Buffer obj req.end(buf); }); }); @param {String} filename @param {Object} headers @return {ClientRequest} @api public
Client.prototype.put ( filename , headers )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.putFile = function(src, filename, headers, fn){ var self = this; var emitter = new Emitter; if ('function' == typeof headers) { fn = headers; headers = {}; } debug('put %s', src); fs.stat(src, function (err, stat) { if (err) return fn(err); var contentType = mime.lookup(src); // Add charset if it's known. var charset = mime.charsets.lookup(contentType); if (charset) { contentType += '; charset=' + charset; } headers = utils.merge({ 'Content-Length': stat.size , 'Content-Type': contentType }, headers); var stream = fs.createReadStream(src); var req = self.putStream(stream, filename, headers, fn); req.on('progress', emitter.emit.bind(emitter, 'progress')); }); return emitter;
PUT the file at `src` to `filename`, with callback `fn` receiving a possible exception, and the response object. Example: client .putFile('package.json', '/test/package.json', function(err, res){ if (err) throw err; console.log(res.statusCode); console.log(res.headers); }); @param {String} src @param {String} filename @param {Object|Function} headers @param {Function} fn @return {EventEmitter} @api public
Client.prototype.putFile ( src , filename , headers , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.putStream = function(stream, filename, headers, fn){ var contentLength = getHeader(headers, 'content-length'); if (contentLength === null) { process.nextTick(function () { fn(new Error('You must specify a Content-Length header.')); }); return; } var self = this; var req = self.put(filename, headers); fn = once(fn); registerReqListeners(req, fn); stream.on('error', fn); var counter = new StreamCounter(); counter.on('progress', function(){ req.emit('progress', { percent: counter.bytes / contentLength * 100 | 0 , written: counter.bytes , total: contentLength }); }); stream.pipe(counter); stream.pipe(req); return req;
PUT the given `stream` as `filename` with `headers`. `headers` must contain `'Content-Length'` at least. @param {Stream} stream @param {String} filename @param {Object} headers @param {Function} fn @return {ClientRequest} @api public
Client.prototype.putStream ( stream , filename , headers , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.putBuffer = function(buffer, filename, headers, fn){ if ('function' == typeof headers) { fn = headers; headers = {}; } headers['Content-Length'] = buffer.length; var req = this.put(filename, headers); fn = once(fn); registerReqListeners(req, fn); req.end(buffer); return req;
PUT the given `buffer` as `filename` with optional `headers`. Callback `fn` receives a possible exception and the response object. @param {Buffer} buffer @param {String} filename @param {Object|Function} headers @param {Function} fn @return {ClientRequest} @api public
Client.prototype.putBuffer ( buffer , filename , headers , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.copy = function(sourceFilename, destFilename, headers){ return this.put(destFilename, getCopyHeaders(this.bucket, sourceFilename, headers));
Copy files from `sourceFilename` to `destFilename` with optional `headers`. @param {String} sourceFilename @param {String} destFilename @param {Object} headers @return {ClientRequest} @api public
Client.prototype.copy ( sourceFilename , destFilename , headers )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.copyFile = function(sourceFilename, destFilename, headers, fn){ if ('function' == typeof headers) { fn = headers; headers = {}; } var req = this.copy(sourceFilename, destFilename, headers); fn = once(fn); registerReqListeners(req, fn); req.end(); return req;
Copy files from `sourceFilename` to `destFilename` with optional `headers` and callback `fn` with a possible exception and the response. @param {String} sourceFilename @param {String} destFilename @param {Object|Function} headers @param {Function} fn @api public
Client.prototype.copyFile ( sourceFilename , destFilename , headers , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.copyTo = function(sourceFilename, destBucket, destFilename, headers){ var options = utils.merge({}, this.options); if (typeof destBucket == 'string') { options.bucket = destBucket; } else { utils.merge(options, destBucket); } var client = exports.createClient(options); return client.put(destFilename, getCopyHeaders(this.bucket, sourceFilename, headers));
Copy files from `sourceFilename` to `destFilename` of the bucket `destBucket` with optional `headers`. @param {String} sourceFilename @param {String|Object} destBucket @param {String} destFilename @param {Object} headers @return {ClientRequest} @api public
Client.prototype.copyTo ( sourceFilename , destBucket , destFilename , headers )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.copyFileTo = function(sourceFilename, destBucket, destFilename, headers, fn){ if ('function' == typeof headers) { fn = headers; headers = {}; } var req = this.copyTo(sourceFilename, destBucket, destFilename, headers); fn = once(fn); registerReqListeners(req, fn); req.end(); return req;
Copy file from `sourceFilename` to `destFilename` of the bucket `destBucket with optional `headers` and callback `fn` with a possible exception and the response. @param {String} sourceFilename @param {String} destBucket @param {String} destFilename @param {Object|Function} headers @param {Function} fn @api public
Client.prototype.copyFileTo ( sourceFilename , destBucket , destFilename , headers , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.get = function(filename, headers){ return this.request('GET', encodeSpecialCharacters(filename), headers);
GET `filename` with optional `headers`. @param {String} filename @param {Object} headers @return {ClientRequest} @api public
Client.prototype.get ( filename , headers )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.getFile = function(filename, headers, fn){ if ('function' == typeof headers) { fn = headers; headers = {}; } var req = this.get(filename, headers); registerReqListeners(req, fn); req.end(); return req;
GET `filename` with optional `headers` and callback `fn` with a possible exception and the response. @param {String} filename @param {Object|Function} headers @param {Function} fn @api public
Client.prototype.getFile ( filename , headers , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.head = function(filename, headers){ return this.request('HEAD', encodeSpecialCharacters(filename), headers);
Issue a HEAD request on `filename` with optional `headers. @param {String} filename @param {Object} headers @return {ClientRequest} @api public
Client.prototype.head ( filename , headers )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.headFile = function(filename, headers, fn){ if ('function' == typeof headers) { fn = headers; headers = {}; } var req = this.head(filename, headers); fn = once(fn); registerReqListeners(req, fn); req.end(); return req;
Issue a HEAD request on `filename` with optional `headers` and callback `fn` with a possible exception and the response. @param {String} filename @param {Object|Function} headers @param {Function} fn @api public
Client.prototype.headFile ( filename , headers , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.del = function(filename, headers){ return this.request('DELETE', encodeSpecialCharacters(filename), headers);
DELETE `filename` with optional `headers. @param {String} filename @param {Object} headers @return {ClientRequest} @api public
Client.prototype.del ( filename , headers )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
Client.prototype.deleteFile = function(filename, headers, fn){ if ('function' == typeof headers) { fn = headers; headers = {}; } var req = this.del(filename, headers); fn = once(fn); registerReqListeners(req, fn); req.end(); return req;
DELETE `filename` with optional `headers` and callback `fn` with a possible exception and the response. @param {String} filename @param {Object|Function} headers @param {Function} fn @api public
Client.prototype.deleteFile ( filename , headers , fn )
javascript
Automattic/knox
lib/client.js
https://github.com/Automattic/knox/blob/master/lib/client.js
MIT
exports.merge = function(a, b){ var keys = Object.keys(b); for (var i = 0, len = keys.length; i < len; ++i) { var key = keys[i]; a[key] = b[key] } return a; };
Merge object `b` with object `a`. @param {Object} a @param {Object} b @return {Object} a @api private
exports.merge ( a , b )
javascript
Automattic/knox
lib/utils.js
https://github.com/Automattic/knox/blob/master/lib/utils.js
MIT
encode: function(str){ return new Buffer(str).toString('base64'); },
Base64 encode the given `str`. @param {String} str @return {String} @api private
encode ( str )
javascript
Automattic/knox
lib/utils.js
https://github.com/Automattic/knox/blob/master/lib/utils.js
MIT
decode: function(str){ return new Buffer(str, 'base64').toString(); }
Base64 decode the given `str`. @param {String} str @return {String} @api private
decode ( str )
javascript
Automattic/knox
lib/utils.js
https://github.com/Automattic/knox/blob/master/lib/utils.js
MIT
exports.authorization = function(options){ return 'AWS ' + options.key + ':' + exports.sign(options); };
Return an "Authorization" header value with the given `options` in the form of "AWS <key>:<signature>" @param {Object} options @return {String} @api private
exports.authorization ( options )
javascript
Automattic/knox
lib/auth.js
https://github.com/Automattic/knox/blob/master/lib/auth.js
MIT
exports.hmacSha1 = function(options){ return crypto.createHmac('sha1', options.secret).update(new Buffer(options.message, 'utf-8')).digest('base64'); };
Simple HMAC-SHA1 Wrapper @param {Object} options @return {String} @api private
exports.hmacSha1 ( options )
javascript
Automattic/knox
lib/auth.js
https://github.com/Automattic/knox/blob/master/lib/auth.js
MIT
exports.sign = function(options){ options.message = exports.stringToSign(options); return exports.hmacSha1(options); };
Create a base64 sha1 HMAC for `options`. @param {Object} options @return {String} @api private
exports.sign ( options )
javascript
Automattic/knox
lib/auth.js
https://github.com/Automattic/knox/blob/master/lib/auth.js
MIT
exports.signQuery = function(options){ options.message = exports.queryStringToSign(options); return exports.hmacSha1(options); };
Create a base64 sha1 HMAC for `options`. Specifically to be used with S3 presigned URLs @param {Object} options @return {String} @api private
exports.signQuery ( options )
javascript
Automattic/knox
lib/auth.js
https://github.com/Automattic/knox/blob/master/lib/auth.js
MIT
exports.stringToSign = function(options){ var headers = options.amazonHeaders || ''; if (headers) headers += '\n'; return [ options.verb , options.md5 , options.contentType , options.date instanceof Date ? options.date.toUTCString() : options.date , headers + options.resource ].join('\n'); };
Return a string for sign() with the given `options`. Spec: <verb>\n <md5>\n <content-type>\n <date>\n [headers\n] <resource> @param {Object} options @return {String} @api private
exports.stringToSign ( options )
javascript
Automattic/knox
lib/auth.js
https://github.com/Automattic/knox/blob/master/lib/auth.js
MIT
exports.canonicalizeHeaders = function(headers){ var buf = [] , fields = Object.keys(headers); for (var i = 0, len = fields.length; i < len; ++i) { var field = fields[i] , val = headers[field]; field = field.toLowerCase(); if (field.indexOf('x-amz') !== 0 || field === 'x-amz-date') { continue; } buf.push(field + ':' + val); } var headerSort = function(a, b) { // Headers are sorted lexigraphically based on the header name only. a = a.split(":")[0] b = b.split(":")[0] return a > b ? 1 : -1; } return buf.sort(headerSort).join('\n'); };
Perform the following: - ignore non-amazon headers - lowercase fields - sort lexicographically - trim whitespace between ":" - join with newline @param {Object} headers @return {String} @api private
exports.canonicalizeHeaders ( headers )
javascript
Automattic/knox
lib/auth.js
https://github.com/Automattic/knox/blob/master/lib/auth.js
MIT
function define(id, dependencies, factory) {}
@param {string} id @param {Array.<string>} dependencies @param {Function} factory
define ( id , dependencies , factory )
javascript
googlearchive/code-prettify
tools/closure-compiler/amd-externs.js
https://github.com/googlearchive/code-prettify/blob/master/tools/closure-compiler/amd-externs.js
Apache-2.0
function recombineTagsAndDecorations(job) { var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent); isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8; var newlineRe = /\n/g; var source = job.sourceCode; var sourceLength = source.length; // Index into source after the last code-unit recombined. var sourceIndex = 0; var spans = job.spans; var nSpans = spans.length; // Index into spans after the last span which ends at or before sourceIndex. var spanIndex = 0; var decorations = job.decorations; var nDecorations = decorations.length; // Index into decorations after the last decoration which ends at or before // sourceIndex. var decorationIndex = 0; // Remove all zero-length decorations. decorations[nDecorations] = sourceLength; var decPos, i; for (i = decPos = 0; i < nDecorations;) { if (decorations[i] !== decorations[i + 2]) { decorations[decPos++] = decorations[i++]; decorations[decPos++] = decorations[i++]; } else { i += 2; } } nDecorations = decPos; // Simplify decorations. for (i = decPos = 0; i < nDecorations;) { var startPos = decorations[i]; // Conflate all adjacent decorations that use the same style. var startDec = decorations[i + 1]; var end = i + 2; while (end + 2 <= nDecorations && decorations[end + 1] === startDec) { end += 2; } decorations[decPos++] = startPos; decorations[decPos++] = startDec; i = end; } nDecorations = decorations.length = decPos; var sourceNode = job.sourceNode; var oldDisplay = ""; if (sourceNode) { oldDisplay = sourceNode.style.display; sourceNode.style.display = 'none'; } try { var decoration = null; while (spanIndex < nSpans) { var spanStart = spans[spanIndex]; var spanEnd = /** @type{number} */ (spans[spanIndex + 2]) || sourceLength; var decEnd = decorations[decorationIndex + 2] || sourceLength; var end = Math.min(spanEnd, decEnd); var textNode = /** @type{Node} */ (spans[spanIndex + 1]); var styledText; if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s // Don't introduce spans around empty text nodes. && (styledText = source.substring(sourceIndex, end))) { // This may seem bizarre, and it is. Emitting LF on IE causes the // code to display with spaces instead of line breaks. // Emitting Windows standard issue linebreaks (CRLF) causes a blank // space to appear at the beginning of every line but the first. // Emitting an old Mac OS 9 line separator makes everything spiffy. if (isIE8OrEarlier) { styledText = styledText.replace(newlineRe, '\r'); } textNode.nodeValue = styledText; var document = textNode.ownerDocument; var span = document.createElement('span'); span.className = decorations[decorationIndex + 1]; var parentNode = textNode.parentNode; parentNode.replaceChild(span, textNode); span.appendChild(textNode); if (sourceIndex < spanEnd) { // Split off a text node. spans[spanIndex + 1] = textNode // TODO: Possibly optimize by using '' if there's no flicker. = document.createTextNode(source.substring(end, spanEnd)); parentNode.insertBefore(textNode, span.nextSibling); } } sourceIndex = end; if (sourceIndex >= spanEnd) { spanIndex += 2; } if (sourceIndex >= decEnd) { decorationIndex += 2; } } } finally { if (sourceNode) { sourceNode.style.display = oldDisplay; } } }
Breaks {@code job.sourceCode} around style boundaries in {@code job.decorations} and modifies {@code job.sourceNode} in place. @param {JobT} job @private
recombineTagsAndDecorations ( job )
javascript
googlearchive/code-prettify
js-modules/recombineTagsAndDecorations.js
https://github.com/googlearchive/code-prettify/blob/master/js-modules/recombineTagsAndDecorations.js
Apache-2.0
PR.registerLangHandler = function registerLangHandler(handler, fileExtensions) {};
@param {function (Object)} handler @param {Array.<string>} fileExtensions
registerLangHandler ( handler , fileExtensions )
javascript
googlearchive/code-prettify
js-modules/externs.js
https://github.com/googlearchive/code-prettify/blob/master/js-modules/externs.js
Apache-2.0
PR.createSimpleLexer = function createSimpleLexer( shortcutStylePatterns, fallthroughStylePatterns) {};
@param {Array} shortcutStylePatterns @param {Array} fallthroughStylePatterns @return {function (Object)}
createSimpleLexer ( shortcutStylePatterns , fallthroughStylePatterns )
javascript
googlearchive/code-prettify
js-modules/externs.js
https://github.com/googlearchive/code-prettify/blob/master/js-modules/externs.js
Apache-2.0
PR.sourceDecorator = function sourceDecorator(options) {};
@param {Object} options a set of optional parameters. @return {function (Object)} a function that examines the source code in the input job and builds the decoration list.
sourceDecorator ( options )
javascript
googlearchive/code-prettify
js-modules/externs.js
https://github.com/googlearchive/code-prettify/blob/master/js-modules/externs.js
Apache-2.0
function numberLines(node, startLineNum, isPreformatted) { var nocode = /(?:^|\s)nocode(?:\s|$)/; var lineBreak = /\r\n?|\n/; var document = node.ownerDocument; var li = document.createElement('li'); while (node.firstChild) { li.appendChild(node.firstChild); } // An array of lines. We split below, so this is initialized to one // un-split line. var listItems = [li]; function walk(node) { var type = node.nodeType; if (type == 1 && !nocode.test(node.className)) { // Element if ('br' === node.nodeName.toLowerCase()) { breakAfter(node); // Discard the <BR> since it is now flush against a </LI>. if (node.parentNode) { node.parentNode.removeChild(node); } } else { for (var child = node.firstChild; child; child = child.nextSibling) { walk(child); } } } else if ((type == 3 || type == 4) && isPreformatted) { // Text var text = node.nodeValue; var match = text.match(lineBreak); if (match) { var firstLine = text.substring(0, match.index); node.nodeValue = firstLine; var tail = text.substring(match.index + match[0].length); if (tail) { var parent = node.parentNode; parent.insertBefore( document.createTextNode(tail), node.nextSibling); } breakAfter(node); if (!firstLine) { // Don't leave blank text nodes in the DOM. node.parentNode.removeChild(node); } } } } // Split a line after the given node. function breakAfter(lineEndNode) { // If there's nothing to the right, then we can skip ending the line // here, and move root-wards since splitting just before an end-tag // would require us to create a bunch of empty copies. while (!lineEndNode.nextSibling) { lineEndNode = lineEndNode.parentNode; if (!lineEndNode) { return; } } function breakLeftOf(limit, copy) { // Clone shallowly if this node needs to be on both sides of the break. var rightSide = copy ? limit.cloneNode(false) : limit; var parent = limit.parentNode; if (parent) { // We clone the parent chain. // This helps us resurrect important styling elements that cross lines. // E.g. in <i>Foo<br>Bar</i> // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>. var parentClone = breakLeftOf(parent, 1); // Move the clone and everything to the right of the original // onto the cloned parent. var next = limit.nextSibling; parentClone.appendChild(rightSide); for (var sibling = next; sibling; sibling = next) { next = sibling.nextSibling; parentClone.appendChild(sibling); } } return rightSide; } var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0); // Walk the parent chain until we reach an unattached LI. for (var parent; // Check nodeType since IE invents document fragments. (parent = copiedListItem.parentNode) && parent.nodeType === 1;) { copiedListItem = parent; } // Put it on the list of lines for later processing. listItems.push(copiedListItem); } // Split lines while there are lines left to split. for (var i = 0; // Number of lines that have been split so far. i < listItems.length; // length updated by breakAfter calls. ++i) { walk(listItems[i]); } // Make sure numeric indices show correctly. if (startLineNum === (startLineNum|0)) { listItems[0].setAttribute('value', startLineNum); } var ol = document.createElement('ol'); ol.className = 'linenums'; var offset = Math.max(0, ((startLineNum - 1 /* zero index */)) | 0) || 0; for (var i = 0, n = listItems.length; i < n; ++i) { li = listItems[i]; // Stick a class on the LIs so that stylesheets can // color odd/even rows, or any other row pattern that // is co-prime with 10. li.className = 'L' + ((i + offset) % 10); if (!li.firstChild) { li.appendChild(document.createTextNode('\xA0')); } ol.appendChild(li); } node.appendChild(ol); }
Given a DOM subtree, wraps it in a list, and puts each line into its own list item. @param {Node} node modified in place. Its content is pulled into an HTMLOListElement, and each line is moved into a separate list item. This requires cloning elements, so the input might not have unique IDs after numbering. @param {number|null|boolean} startLineNum If truthy, coerced to an integer which is the 1-indexed line number of the first line of code. The number of the first line will be attached to the list. @param {boolean} isPreformatted true iff white-space in text nodes should be treated as significant.
numberLines ( node , startLineNum , isPreformatted )
javascript
googlearchive/code-prettify
js-modules/numberLines.js
https://github.com/googlearchive/code-prettify/blob/master/js-modules/numberLines.js
Apache-2.0
function appendDecorations( sourceNode, basePos, sourceCode, langHandler, out) { if (!sourceCode) { return; } /** @type {JobT} */ var job = { sourceNode: sourceNode, pre: 1, langExtension: null, numberLines: null, sourceCode: sourceCode, spans: null, basePos: basePos, decorations: null }; langHandler(job); out.push.apply(out, job.decorations); }
Apply the given language handler to sourceCode and add the resulting decorations to out. @param {!Element} sourceNode @param {number} basePos the index of sourceCode within the chunk of source whose decorations are already present on out. @param {string} sourceCode @param {function(JobT)} langHandler @param {DecorationsT} out
appendDecorations ( sourceNode , basePos , sourceCode , langHandler , out )
javascript
googlearchive/code-prettify
js-modules/prettify.js
https://github.com/googlearchive/code-prettify/blob/master/js-modules/prettify.js
Apache-2.0