Socket
Socket
Sign inDemoInstall

svelte-preprocess

Package Overview
Dependencies
2
Maintainers
3
Versions
173
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 5.1.4 to 6.0.0

2

dist/autoProcess.d.ts
import type { AutoPreprocessGroup, AutoPreprocessOptions, Processed, TransformerArgs, TransformerOptions } from './types';
export declare const transform: (name: string | null | undefined, options: TransformerOptions, { content, markup, map, filename, attributes }: TransformerArgs<any>) => Promise<Processed>;
export declare function sveltePreprocess({ aliases, markupTagName, preserve, sourceMap, ...rest }?: AutoPreprocessOptions): AutoPreprocessGroup;
export declare function sveltePreprocess({ aliases, markupTagName, sourceMap, ...rest }?: AutoPreprocessOptions): AutoPreprocessGroup;

@@ -58,3 +58,3 @@ "use strict";

var _b, _c;
var { aliases, markupTagName = 'template', preserve = [], sourceMap = (_c = ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.NODE_ENV) === 'development') !== null && _c !== void 0 ? _c : false, ...rest } = _a === void 0 ? {} : _a;
var { aliases, markupTagName = 'template', sourceMap = (_c = ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.NODE_ENV) === 'development') !== null && _c !== void 0 ? _c : false, ...rest } = _a === void 0 ? {} : _a;
const transformers = rest;

@@ -101,5 +101,2 @@ if (aliases === null || aliases === void 0 ? void 0 : aliases.length) {

}
if ((lang && preserve.includes(lang)) || preserve.includes(alias)) {
return { code: content };
}
const transformerOptions = getTransformerOptions(lang, alias);

@@ -106,0 +103,0 @@ content = (0, prepareContent_1.prepareContent)({

@@ -12,3 +12,3 @@ "use strict";

// TODO: maybe replace this ugly pattern with an actual selector parser? (https://github.com/leaverou/parsel, 2kb)
const combinatorPattern = /(?<!\\)(?:\\\\)*([ >+~,]\s*)(?![^[]+\]|\d)/g;
const combinatorPattern = /(?<!\\)(?:\\\\)*([ >+~,]\s*)(?![^(]*\))(?![^[]+\]|\d)/g;
function globalifySelector(selector) {

@@ -15,0 +15,0 @@ const parts = selector.trim().split(combinatorPattern);

import type { Transformer, Preprocessor } from '../types';
/** Create a tag matching regexp. */
export declare function createTagRegex(tagName: string, flags?: string): RegExp;
/** Strip script and style tags from markup. */
export declare function stripTags(markup: string): string;
/** Transform an attribute string into a key-value object */

@@ -7,0 +5,0 @@ export declare function parseAttributes(attributesStr: string): Record<string, any>;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformMarkup = exports.parseAttributes = exports.stripTags = exports.createTagRegex = void 0;
exports.transformMarkup = exports.parseAttributes = exports.createTagRegex = void 0;
/** Create a tag matching regexp. */

@@ -9,9 +9,2 @@ function createTagRegex(tagName, flags) {

exports.createTagRegex = createTagRegex;
/** Strip script and style tags from markup. */
function stripTags(markup) {
return markup
.replace(createTagRegex('style', 'gi'), '')
.replace(createTagRegex('script', 'gi'), '');
}
exports.stripTags = stripTags;
/** Transform an attribute string into a key-value object */

@@ -18,0 +11,0 @@ function parseAttributes(attributesStr) {

@@ -18,2 +18,1 @@ export declare function concat(...arrs: any[]): any[];

export declare function setProp(obj: any, keyList: string[], value: any): void;
export declare const JAVASCRIPT_RESERVED_KEYWORD_SET: Set<string>;

@@ -26,3 +26,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.JAVASCRIPT_RESERVED_KEYWORD_SET = exports.setProp = exports.findUp = exports.isValidLocalPath = exports.hasDepInstalled = exports.getIncludePaths = exports.concat = void 0;
exports.setProp = exports.findUp = exports.isValidLocalPath = exports.hasDepInstalled = exports.getIncludePaths = exports.concat = void 0;
const fs_1 = require("fs");

@@ -106,51 +106,1 @@ const path_1 = require("path");

exports.setProp = setProp;
exports.JAVASCRIPT_RESERVED_KEYWORD_SET = new Set([
'arguments',
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'enum',
'eval',
'export',
'extends',
'false',
'finally',
'for',
'function',
'if',
'implements',
'import',
'in',
'instanceof',
'interface',
'let',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'static',
'super',
'switch',
'this',
'throw',
'true',
'try',
'typeof',
'var',
'void',
'while',
'with',
'yield',
]);

@@ -9,10 +9,3 @@ "use strict";

const typescript_1 = __importDefault(require("typescript"));
const compiler_1 = require("svelte/compiler");
const magic_string_1 = __importDefault(require("magic-string"));
const sorcery_1 = require("sorcery");
const errors_1 = require("../modules/errors");
const markup_1 = require("../modules/markup");
const utils_1 = require("../modules/utils");
const package_json_1 = __importDefault(require("svelte/package.json"));
const injectedCodeSeparator = 'const $$$$$$$$ = null;';
/**

@@ -22,3 +15,2 @@ * Map of valid tsconfigs (no errors). Key is the path.

const tsconfigMap = new Map();
const importsNotUsedAsValuesDeprecated = parseInt(typescript_1.default.version.split('.')[0], 10) >= 5;
function createFormatDiagnosticsHost(cwd) {

@@ -37,126 +29,5 @@ return {

}
const importTransformer = (context) => {
const visit = (node) => {
var _a, _b, _c;
if (typescript_1.default.isImportDeclaration(node)) {
if ((_a = node.importClause) === null || _a === void 0 ? void 0 : _a.isTypeOnly) {
if (!((_b = typescript_1.default.factory) === null || _b === void 0 ? void 0 : _b.createEmptyStatement)) {
// @ts-expect-error removed in TS 5.0
return typescript_1.default.createEmptyStatement();
}
return typescript_1.default.factory.createEmptyStatement();
}
if (!((_c = typescript_1.default.factory) === null || _c === void 0 ? void 0 : _c.createImportDeclaration)) {
// @ts-expect-error removed in TS 5.0
return typescript_1.default.createImportDeclaration(
// @ts-expect-error removed in TS 5.0
node.decorators, node.modifiers, node.importClause, node.moduleSpecifier);
}
return typescript_1.default.factory.createImportDeclaration(node.modifiers, node.importClause, node.moduleSpecifier);
}
return typescript_1.default.visitEachChild(node, (child) => visit(child), context);
};
return (node) => {
typescript_1.default.visitNode(node, visit);
return node;
};
};
function getScriptContent(markup, module) {
const regex = (0, markup_1.createTagRegex)('script', 'gi');
let match;
while ((match = regex.exec(markup)) !== null) {
const { context } = (0, markup_1.parseAttributes)(match[1] || '');
if ((context !== 'module' && !module) || (context === 'module' && module)) {
return match[2];
}
}
return '';
}
function createSourceMapChain({ filename, content, compilerOptions, }) {
if (compilerOptions.sourceMap) {
return {
content: {
[filename]: content,
},
sourcemaps: {},
};
}
}
function injectVarsToCode({ content, markup, filename, attributes, sourceMapChain, }) {
if (!markup)
return content;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore different in Svelte 5
const { vars } = (0, compiler_1.compile)((0, markup_1.stripTags)(markup), {
generate: false,
varsReport: 'full',
errorMode: 'warn',
filename,
});
const sep = `\n${injectedCodeSeparator}\n`;
const varnames = vars.map((v) => v.name.startsWith('$') && !v.name.startsWith('$$')
? `${v.name},${v.name.slice(1)}`
: v.name);
const contentForCodestores = content +
// Append instance script content because it's valid
// to import a store in module script and autosubscribe to it in instance script
((attributes === null || attributes === void 0 ? void 0 : attributes.context) === 'module' ? getScriptContent(markup, false) : '');
// This regex extracts all possible store variables
// TODO investigate if it's possible to achieve this with a
// TS transformer (previous attemps have failed)
const codestores = Array.from(contentForCodestores.match(/\$[^\s();:,[\]{}.?!+\-=*/\\~|&%<>^`"'°§#0-9][^\s();:,[\]{}.?!+\-=*/\\~|&%<>^`"'°§#]*/g) || [], (name) => name.slice(1)).filter((name) => !utils_1.JAVASCRIPT_RESERVED_KEYWORD_SET.has(name));
const varsString = [...codestores, ...varnames].join(',');
const injectedVars = `const $$vars$$ = [${varsString}];`;
// Append instance/markup script content because it's valid
// to import things in one and reference it in the other.
const injectedCode = (attributes === null || attributes === void 0 ? void 0 : attributes.context) === 'module'
? `${sep}${getScriptContent(markup, false)}\n${injectedVars}`
: `${sep}${getScriptContent(markup, true)}\n${injectedVars}`;
if (sourceMapChain) {
const ms = new magic_string_1.default(content).append(injectedCode);
const fname = `${filename}.injected.ts`;
const code = ms.toString();
const map = ms.generateMap({
source: filename,
file: fname,
hires: true,
});
sourceMapChain.content[fname] = code;
sourceMapChain.sourcemaps[fname] = map;
return code;
}
return `${content}${injectedCode}`;
}
function stripInjectedCode({ transpiledCode, markup, filename, sourceMapChain, }) {
if (!markup)
return transpiledCode;
const injectedCodeStart = transpiledCode.indexOf(injectedCodeSeparator);
if (sourceMapChain) {
const ms = new magic_string_1.default(transpiledCode).snip(0, injectedCodeStart);
const source = `${filename}.transpiled.js`;
const file = `${filename}.js`;
const code = ms.toString();
const map = ms.generateMap({
source,
file,
hires: true,
});
sourceMapChain.content[file] = code;
sourceMapChain.sourcemaps[file] = map;
return code;
}
return transpiledCode.slice(0, injectedCodeStart);
}
async function concatSourceMaps({ filename, markup, sourceMapChain, }) {
if (!sourceMapChain)
return;
if (!markup) {
return sourceMapChain.sourcemaps[`${filename}.js`];
}
const chain = await (0, sorcery_1.load)(`${filename}.js`, sourceMapChain);
return chain.apply();
}
let warned = false;
let warned_verbatim = false;
function getCompilerOptions({ filename, options, basePath, }) {
var _a, _b;
var _a;
const inputOptions = (_a = options.compilerOptions) !== null && _a !== void 0 ? _a : {};

@@ -176,3 +47,3 @@ const { errors, options: convertedCompilerOptions } = options.tsconfigFile !== false || options.tsconfigDirectory

module: typescript_1.default.ModuleKind.ESNext,
moduleResolution: (_b = typescript_1.default.ModuleResolutionKind.NodeJs) !== null && _b !== void 0 ? _b : typescript_1.default.ModuleResolutionKind.Node10,
moduleResolution: typescript_1.default.ModuleResolutionKind.Node10,
allowNonTsExtensions: true,

@@ -182,20 +53,6 @@ // Clear outDir since it causes source map issues when the files aren't actually written to disk.

};
if (!importsNotUsedAsValuesDeprecated ||
(compilerOptions.ignoreDeprecations === '5.0' &&
!compilerOptions.verbatimModuleSyntax)) {
compilerOptions.importsNotUsedAsValues = typescript_1.default.ImportsNotUsedAsValues.Error;
if (!warned_verbatim && !compilerOptions.verbatimModuleSyntax) {
warned_verbatim = true;
console.warn('The TypeScript option verbatimModuleSyntax is now required when using Svelte files with lang="ts". Please add it to your tsconfig.json.');
}
// Ease TS 5 migration pains a little and add the deprecation flag automatically if needed
if (importsNotUsedAsValuesDeprecated &&
!compilerOptions.ignoreDeprecations &&
(compilerOptions.importsNotUsedAsValues ||
compilerOptions.preserveValueImports)) {
if (!warned) {
warned = true;
console.warn('tsconfig options "importsNotUsedAsValues" and "preserveValueImports" are deprecated. ' +
'Either set "ignoreDeprecations" to "5.0" in your tsconfig.json to silence this warning, ' +
'or replace them in favor of the new "verbatimModuleSyntax" flag.');
}
compilerOptions.ignoreDeprecations = '5.0';
}
if (compilerOptions.target === typescript_1.default.ScriptTarget.ES3 ||

@@ -217,5 +74,5 @@ compilerOptions.target === typescript_1.default.ScriptTarget.ES5) {

const hasError = diagnostics.some((d) => d.category === typescript_1.default.DiagnosticCategory.Error);
const formattedDiagnostics = formatDiagnostics(diagnostics, basePath);
console.log(formattedDiagnostics);
if (hasError) {
const formattedDiagnostics = formatDiagnostics(diagnostics, basePath);
console.log(formattedDiagnostics);
(0, errors_1.throwTypescriptError)();

@@ -263,59 +120,13 @@ }

exports.loadTsconfig = loadTsconfig;
async function mixedImportsTranspiler({ content, filename = 'source.svelte', markup, options = {}, attributes, compilerOptions, basePath, }) {
const sourceMapChain = createSourceMapChain({
filename,
content,
compilerOptions,
});
const injectedCode = injectVarsToCode({
content,
markup,
filename,
attributes,
sourceMapChain,
});
const { transpiledCode, sourceMapText, diagnostics } = transpileTs({
code: injectedCode,
fileName: `${filename}.injected.ts`,
basePath,
options,
compilerOptions,
});
if (sourceMapChain && sourceMapText) {
const fname = `${filename}.transpiled.js`;
sourceMapChain.content[fname] = transpiledCode;
sourceMapChain.sourcemaps[fname] = JSON.parse(sourceMapText);
let warned_mixed = false;
const transformer = async ({ content, filename = 'input.svelte', options = {}, }) => {
const basePath = process.cwd();
filename = (0, path_1.isAbsolute)(filename) ? filename : (0, path_1.resolve)(basePath, filename);
const compilerOptions = getCompilerOptions({ filename, options, basePath });
if ('handleMixedImports' in options && !warned_mixed) {
warned_mixed = true;
console.warn('The svelte-preprocess TypeScript option handleMixedImports was removed. Use the verbatimModuleSyntax TypeScript option instead.');
}
const code = stripInjectedCode({
transpiledCode,
markup,
filename,
sourceMapChain,
});
// Sorcery tries to load the code/map from disk if it's empty,
// prevent that because it would try to load inexistent files
// https://github.com/Rich-Harris/sorcery/issues/167
if (!code) {
return { code, diagnostics };
}
const map = await concatSourceMaps({
filename,
markup,
sourceMapChain,
});
return {
code,
map,
diagnostics,
};
}
async function simpleTranspiler({ content, filename = 'source.svelte', options = {}, compilerOptions, basePath, }) {
const { transpiledCode, sourceMapText, diagnostics } = transpileTs({
code: content,
// `preserveValueImports` essentially does the same as our import transformer,
// keeping all imports that are not type imports
transformers: compilerOptions.preserveValueImports ||
compilerOptions.verbatimModuleSyntax
? undefined
: { before: [importTransformer] },
fileName: filename,

@@ -331,41 +142,3 @@ basePath,

};
}
const transformer = async ({ content, filename, markup, options = {}, attributes, }) => {
const basePath = process.cwd();
if (filename == null)
return { code: content };
filename = (0, path_1.isAbsolute)(filename) ? filename : (0, path_1.resolve)(basePath, filename);
const compilerOptions = getCompilerOptions({ filename, options, basePath });
const versionParts = package_json_1.default.version.split('.');
const canUseMixedImportsTranspiler = +versionParts[0] === 4 ||
(+versionParts[0] === 3 && +versionParts[1] >= 39);
if (!canUseMixedImportsTranspiler && options.handleMixedImports) {
throw new Error('You need at least Svelte 3.39 and at most Svelte 4.x to use the handleMixedImports option. ' +
'The option is no longer available for Svelte 5 and beyond. Use the verbatimModuleSyntax TypeScript option instead.');
}
const handleMixedImports = !compilerOptions.preserveValueImports &&
!compilerOptions.verbatimModuleSyntax &&
(options.handleMixedImports === false
? false
: options.handleMixedImports || canUseMixedImportsTranspiler);
return handleMixedImports
? mixedImportsTranspiler({
content,
filename,
markup,
options,
attributes,
compilerOptions,
basePath,
})
: simpleTranspiler({
content,
filename,
markup,
options,
attributes,
compilerOptions,
basePath,
});
};
exports.transformer = transformer;

@@ -0,5 +1,6 @@

/// <reference types="svelte" />
import * as Options from './options';
import type { Processed as SvelteProcessed, Preprocessor as SveltePreprocessor, PreprocessorGroup } from 'svelte/types/compiler/preprocess';
import type { Processed as SvelteProcessed, Preprocessor as SveltePreprocessor, PreprocessorGroup } from 'svelte/compiler';
export { Options };
export { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
export { PreprocessorGroup };
export type PreprocessorArgs = Preprocessor extends (options: infer T) => any ? T : never;

@@ -49,3 +50,2 @@ export type TransformerArgs<T> = {

aliases?: Array<[string, string]>;
preserve?: string[];
sourceMap?: boolean;

@@ -52,0 +52,0 @@ babel?: TransformerOptions<Options.Babel>;

@@ -53,3 +53,2 @@ import type { LegacyStringOptions } from 'sass';

reportDiagnostics?: boolean;
handleMixedImports?: boolean;
} & ContentModifier;

@@ -56,0 +55,0 @@ export interface GlobalStyle {

{
"name": "svelte-preprocess",
"version": "5.1.4",
"version": "6.0.0",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"description": "A Svelte preprocessor wrapper with baked-in support for commonly used preprocessors",

@@ -13,2 +20,3 @@ "author": "Christian Kaisermann <christian@kaisermann.me>",

"preprocess",
"typescript",
"less",

@@ -22,5 +30,5 @@ "stylus",

"engines": {
"node": ">= 16.0.0"
"node": ">= 18.0.0"
},
"packageManager": "pnpm@8.12.1",
"packageManager": "pnpm@9.3.0",
"volta": {

@@ -36,3 +44,3 @@ "node": "20.10.0"

"dev": "pnpm build -w",
"test": "jest",
"test": "vitest run",
"lint": "eslint --ext js,ts .",

@@ -45,4 +53,3 @@ "format": "prettier --write \"**/*.{ts,js,json}\"",

"major": "npm version major -m 'chore(release): %s'",
"prepublishOnly": "pnpm test && pnpm build",
"prepare": "husky install"
"prepublishOnly": "pnpm test && pnpm build"
},

@@ -54,11 +61,2 @@ "commitlint": {

},
"lint-staged": {
"*.{ts,js,tsx,jsx}": [
"eslint --fix",
"prettier --write"
],
"*.json": [
"prettier --write"
]
},
"devDependencies": {

@@ -72,4 +70,4 @@ "@babel/core": "^7.23.6",

"@types/babel__core": "^7.20.5",
"@types/jest": "^27.5.2",
"@types/node": "^14.18.34",
"@types/node": "^18.0.0",
"@types/pug": "^2.0.6",
"@types/stylus": "^0.48.38",

@@ -81,10 +79,7 @@ "autoprefixer": "^10.4.16",

"eslint": "^8.29.0",
"husky": "^8.0.2",
"jest": "^29.5.0",
"less": "^3.13.1",
"lint-staged": "^10.5.4",
"postcss": "^8.4.32",
"postcss-easy-import": "^4.0.0",
"postcss-load-config": "^3.1.4",
"prettier": "^2.8.1",
"prettier": "^3.3.2",
"pug": "^3.0.2",

@@ -94,11 +89,8 @@ "sass": "^1.56.2",

"sugarss": "^4.0.0",
"svelte": "^3.54.0",
"ts-jest": "^29.1.1",
"typescript": "^5.0.2"
"svelte": "^4.0.0",
"typescript": "^5.0.2",
"vitest": "^1.6.0"
},
"dependencies": {
"@types/pug": "^2.0.6",
"detect-indent": "^6.1.0",
"magic-string": "^0.30.5",
"sorcery": "^0.11.0",
"strip-indent": "^3.0.0"

@@ -111,9 +103,9 @@ },

"postcss": "^7 || ^8",
"postcss-load-config": "^2.1.0 || ^3.0.0 || ^4.0.0 || ^5.0.0",
"postcss-load-config": ">=3",
"pug": "^3.0.0",
"sass": "^1.26.8",
"stylus": "^0.55.0",
"stylus": ">=0.55",
"sugarss": "^2.0.0 || ^3.0.0 || ^4.0.0",
"svelte": "^3.23.0 || ^4.0.0-next.0 || ^4.0.0 || ^5.0.0-next.0",
"typescript": ">=3.9.5 || ^4.0.0 || ^5.0.0"
"svelte": "^4.0.0 || ^5.0.0-next.100 || ^5.0.0",
"typescript": "^5.0.0"
},

@@ -120,0 +112,0 @@ "peerDependenciesMeta": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc