init
This commit is contained in:
commit
42ef2f9674
468 files changed
+645161
No files matched your search
+89
@@ -0,0 +1,89 @@
|
||||
export interface ImportGlobOptions<
|
||||
Eager extends boolean,
|
||||
AsType extends string,
|
||||
> {
|
||||
/**
|
||||
* Import type for the import url.
|
||||
*
|
||||
* @deprecated Use `query` instead, e.g. `as: 'url'` -> `query: '?url', import: 'default'`
|
||||
*/
|
||||
as?: AsType
|
||||
/**
|
||||
* Import as static or dynamic
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
eager?: Eager
|
||||
/**
|
||||
* Import only the specific named export. Set to `default` to import the default export.
|
||||
*/
|
||||
import?: string
|
||||
/**
|
||||
* Custom queries
|
||||
*/
|
||||
query?: string | Record<string, string | number | boolean>
|
||||
/**
|
||||
* Search files also inside `node_modules/` and hidden directories (e.g. `.git/`). This might have impact on performance.
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
exhaustive?: boolean
|
||||
/**
|
||||
* Base path to resolve relative paths.
|
||||
*/
|
||||
base?: string
|
||||
}
|
||||
|
||||
export type GeneralImportGlobOptions = ImportGlobOptions<boolean, string>
|
||||
|
||||
/**
|
||||
* Declare Worker in case DOM is not added to the tsconfig lib causing
|
||||
* Worker interface is not defined. For developers with DOM lib added,
|
||||
* the Worker interface will be merged correctly.
|
||||
*/
|
||||
declare global {
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
interface Worker {}
|
||||
}
|
||||
|
||||
export interface KnownAsTypeMap {
|
||||
raw: string
|
||||
url: string
|
||||
worker: Worker
|
||||
}
|
||||
|
||||
export interface ImportGlobFunction {
|
||||
/**
|
||||
* Import a list of files with a glob pattern.
|
||||
*
|
||||
* Overload 1: No generic provided, infer the type from `eager` and `as`
|
||||
*/
|
||||
<
|
||||
Eager extends boolean,
|
||||
As extends string,
|
||||
T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown,
|
||||
>(
|
||||
glob: string | string[],
|
||||
options?: ImportGlobOptions<Eager, As>,
|
||||
): (Eager extends true ? true : false) extends true
|
||||
? Record<string, T>
|
||||
: Record<string, () => Promise<T>>
|
||||
/**
|
||||
* Import a list of files with a glob pattern.
|
||||
*
|
||||
* Overload 2: Module generic provided, infer the type from `eager: false`
|
||||
*/
|
||||
<M>(
|
||||
glob: string | string[],
|
||||
options?: ImportGlobOptions<false, string>,
|
||||
): Record<string, () => Promise<M>>
|
||||
/**
|
||||
* Import a list of files with a glob pattern.
|
||||
*
|
||||
* Overload 3: Module generic provided, infer the type from `eager: true`
|
||||
*/
|
||||
<M>(
|
||||
glob: string | string[],
|
||||
options: ImportGlobOptions<true, string>,
|
||||
): Record<string, M>
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { MenuItemBase, newMenu } from './base.js';
|
||||
import { invoke } from '../core.js';
|
||||
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
/**
|
||||
* A check menu item inside a {@linkcode Menu} or {@linkcode Submenu}
|
||||
* and usually contains a text and a check mark or a similar toggle
|
||||
* that corresponds to a checked and unchecked states.
|
||||
*/
|
||||
class CheckMenuItem extends MenuItemBase {
|
||||
/** @ignore */
|
||||
constructor(rid, id) {
|
||||
super(rid, id, 'Check');
|
||||
}
|
||||
/** Create a new check menu item. */
|
||||
static async new(opts) {
|
||||
return newMenu('Check', opts).then(([rid, id]) => new CheckMenuItem(rid, id));
|
||||
}
|
||||
/** Returns the text of this check menu item. */
|
||||
async text() {
|
||||
return invoke('plugin:menu|text', { rid: this.rid, kind: this.kind });
|
||||
}
|
||||
/** Sets the text for this check menu item. */
|
||||
async setText(text) {
|
||||
return invoke('plugin:menu|set_text', {
|
||||
rid: this.rid,
|
||||
kind: this.kind,
|
||||
text
|
||||
});
|
||||
}
|
||||
/** Returns whether this check menu item is enabled or not. */
|
||||
async isEnabled() {
|
||||
return invoke('plugin:menu|is_enabled', { rid: this.rid, kind: this.kind });
|
||||
}
|
||||
/** Sets whether this check menu item is enabled or not. */
|
||||
async setEnabled(enabled) {
|
||||
return invoke('plugin:menu|set_enabled', {
|
||||
rid: this.rid,
|
||||
kind: this.kind,
|
||||
enabled
|
||||
});
|
||||
}
|
||||
/** Sets the accelerator for this check menu item. */
|
||||
async setAccelerator(accelerator) {
|
||||
return invoke('plugin:menu|set_accelerator', {
|
||||
rid: this.rid,
|
||||
kind: this.kind,
|
||||
accelerator
|
||||
});
|
||||
}
|
||||
/** Returns whether this check menu item is checked or not. */
|
||||
async isChecked() {
|
||||
return invoke('plugin:menu|is_checked', { rid: this.rid });
|
||||
}
|
||||
/** Sets whether this check menu item is checked or not. */
|
||||
async setChecked(checked) {
|
||||
return invoke('plugin:menu|set_checked', {
|
||||
rid: this.rid,
|
||||
checked
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { CheckMenuItem };
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
import { readdir, readdirSync, realpath, realpathSync, stat, statSync } from "fs";
|
||||
import { isAbsolute, posix, resolve } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { fdir } from "fdir";
|
||||
import picomatch from "picomatch";
|
||||
//#region src/utils.ts
|
||||
const isReadonlyArray = Array.isArray;
|
||||
const BACKSLASHES = /\\/g;
|
||||
const DRIVE_RELATIVE_PATH = /^[A-Za-z]:$/;
|
||||
const isWin = process.platform === "win32";
|
||||
const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
|
||||
function getPartialMatcher(patterns, options = {}) {
|
||||
const patternsCount = patterns.length;
|
||||
const patternsParts = Array(patternsCount);
|
||||
const matchers = Array(patternsCount);
|
||||
let i, j;
|
||||
for (i = 0; i < patternsCount; i++) {
|
||||
const parts = splitPattern(patterns[i]);
|
||||
patternsParts[i] = parts;
|
||||
const partsCount = parts.length;
|
||||
const partMatchers = Array(partsCount);
|
||||
for (j = 0; j < partsCount; j++) partMatchers[j] = picomatch(parts[j], options);
|
||||
matchers[i] = partMatchers;
|
||||
}
|
||||
return (input) => {
|
||||
const inputParts = input.split("/");
|
||||
if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
|
||||
for (i = 0; i < patternsCount; i++) {
|
||||
const patternParts = patternsParts[i];
|
||||
const matcher = matchers[i];
|
||||
const inputPatternCount = inputParts.length;
|
||||
const minParts = Math.min(inputPatternCount, patternParts.length);
|
||||
j = 0;
|
||||
while (j < minParts) {
|
||||
const part = patternParts[j];
|
||||
if (part.includes("/")) return true;
|
||||
if (!matcher[j](inputParts[j])) break;
|
||||
if (!options.noglobstar && part === "**") return true;
|
||||
j++;
|
||||
}
|
||||
if (j === inputPatternCount) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
/* node:coverage ignore next 2 */
|
||||
const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
|
||||
const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
|
||||
function buildFormat(cwd, root, absolute) {
|
||||
if (cwd === root || root.startsWith(`${cwd}/`)) {
|
||||
if (absolute) {
|
||||
const start = cwd.length + +!isRoot(cwd);
|
||||
return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
|
||||
}
|
||||
const prefix = root.slice(cwd.length + 1);
|
||||
if (prefix) return (p, isDir) => {
|
||||
if (p === ".") return prefix;
|
||||
const result = `${prefix}/${p}`;
|
||||
return isDir ? result.slice(0, -1) : result;
|
||||
};
|
||||
return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
|
||||
}
|
||||
if (absolute) return (p) => posix.relative(cwd, p) || ".";
|
||||
return (p) => posix.relative(cwd, `${root}/${p}`) || ".";
|
||||
}
|
||||
function buildRelative(cwd, root) {
|
||||
if (root.startsWith(`${cwd}/`)) {
|
||||
const prefix = root.slice(cwd.length + 1);
|
||||
return (p) => `${prefix}/${p}`;
|
||||
}
|
||||
return (p) => {
|
||||
const result = posix.relative(cwd, `${root}/${p}`);
|
||||
return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || ".";
|
||||
};
|
||||
}
|
||||
function ensureNonDriveRelativePath(path) {
|
||||
return path.replace(DRIVE_RELATIVE_PATH, (match) => `${match}/`);
|
||||
}
|
||||
const splitPatternOptions = { parts: true };
|
||||
function splitPattern(path) {
|
||||
var _result$parts;
|
||||
const result = picomatch.scan(path, splitPatternOptions);
|
||||
return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path];
|
||||
}
|
||||
const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g;
|
||||
function convertPosixPathToPattern(path) {
|
||||
return escapePosixPath(path);
|
||||
}
|
||||
function convertWin32PathToPattern(path) {
|
||||
return escapeWin32Path(path).replace(ESCAPED_WIN32_BACKSLASHES, "/");
|
||||
}
|
||||
/**
|
||||
* Converts a path to a pattern depending on the platform.
|
||||
* Identical to {@link escapePath} on POSIX systems.
|
||||
* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern}
|
||||
*/
|
||||
/* node:coverage ignore next 3 */
|
||||
const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern;
|
||||
const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
|
||||
const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
|
||||
const escapePosixPath = (path) => path.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
|
||||
const escapeWin32Path = (path) => path.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
|
||||
/**
|
||||
* Escapes a path's special characters depending on the platform.
|
||||
* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
|
||||
*/
|
||||
/* node:coverage ignore next */
|
||||
const escapePath = isWin ? escapeWin32Path : escapePosixPath;
|
||||
/**
|
||||
* Checks if a pattern has dynamic parts.
|
||||
*
|
||||
* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
|
||||
*
|
||||
* - Doesn't necessarily return `false` on patterns that include `\`.
|
||||
* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
|
||||
* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
|
||||
* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
|
||||
*
|
||||
* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
|
||||
*/
|
||||
function isDynamicPattern(pattern, options) {
|
||||
if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
|
||||
const scan = picomatch.scan(pattern);
|
||||
return scan.isGlob || scan.negated;
|
||||
}
|
||||
function log(...tasks) {
|
||||
console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
|
||||
}
|
||||
function ensureStringArray(value) {
|
||||
return typeof value === "string" ? [value] : value !== null && value !== void 0 ? value : [];
|
||||
}
|
||||
//#endregion
|
||||
//#region src/patterns.ts
|
||||
const PARENT_DIRECTORY = /^(\/?\.\.)+/;
|
||||
const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
|
||||
function normalizePattern(pattern, opts, props, isIgnore) {
|
||||
var _PARENT_DIRECTORY$exe;
|
||||
const cwd = opts.cwd;
|
||||
let result = pattern;
|
||||
if (pattern[pattern.length - 1] === "/") result = pattern.slice(0, -1);
|
||||
if (result[result.length - 1] !== "*" && opts.expandDirectories) result += "/**";
|
||||
const escapedCwd = escapePath(cwd);
|
||||
result = isAbsolute(result.replace(ESCAPING_BACKSLASHES, "")) ? posix.relative(escapedCwd, result) : posix.normalize(result);
|
||||
const parentDir = (_PARENT_DIRECTORY$exe = PARENT_DIRECTORY.exec(result)) === null || _PARENT_DIRECTORY$exe === void 0 ? void 0 : _PARENT_DIRECTORY$exe[0];
|
||||
const parts = splitPattern(result);
|
||||
if (parentDir) {
|
||||
const n = (parentDir.length + 1) / 3;
|
||||
let i = 0;
|
||||
const cwdParts = escapedCwd.split("/");
|
||||
while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
|
||||
result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
|
||||
i++;
|
||||
}
|
||||
const potentialRoot = posix.join(cwd, parentDir.slice(i * 3));
|
||||
if (potentialRoot[0] !== "." && props.root.length > potentialRoot.length) {
|
||||
props.root = ensureNonDriveRelativePath(potentialRoot);
|
||||
props.depthOffset = -n + i;
|
||||
}
|
||||
}
|
||||
if (!isIgnore && props.depthOffset >= 0) {
|
||||
var _props$commonPath;
|
||||
(_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
|
||||
const newCommonPath = [];
|
||||
const length = Math.min(props.commonPath.length, parts.length);
|
||||
for (let i = 0; i < length; i++) {
|
||||
const part = parts[i];
|
||||
if (part === "**" && !parts[i + 1]) {
|
||||
newCommonPath.pop();
|
||||
break;
|
||||
}
|
||||
if (i === parts.length - 1 || part !== props.commonPath[i] || isDynamicPattern(part)) break;
|
||||
newCommonPath.push(part);
|
||||
}
|
||||
props.depthOffset = newCommonPath.length;
|
||||
props.commonPath = newCommonPath;
|
||||
props.root = ensureNonDriveRelativePath(newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function processPatterns(options, patterns, props) {
|
||||
const matchPatterns = [];
|
||||
const ignorePatterns = [];
|
||||
for (const pattern of options.ignore) {
|
||||
if (!pattern) continue;
|
||||
if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, options, props, true));
|
||||
}
|
||||
for (const pattern of patterns) {
|
||||
if (!pattern) continue;
|
||||
if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, options, props, false));
|
||||
else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), options, props, true));
|
||||
}
|
||||
return {
|
||||
match: matchPatterns,
|
||||
ignore: ignorePatterns
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
//#region src/crawler.ts
|
||||
function buildCrawler(options, patterns) {
|
||||
const cwd = options.cwd;
|
||||
const props = {
|
||||
root: cwd,
|
||||
depthOffset: 0
|
||||
};
|
||||
const processed = processPatterns(options, patterns, props);
|
||||
if (options.debug) log("internal processing patterns:", processed);
|
||||
const { absolute, caseSensitiveMatch, debug, dot, followSymbolicLinks, onlyDirectories } = options;
|
||||
const root = props.root.replace(BACKSLASHES, "");
|
||||
const matchOptions = {
|
||||
dot,
|
||||
nobrace: options.braceExpansion === false,
|
||||
nocase: !caseSensitiveMatch,
|
||||
noextglob: options.extglob === false,
|
||||
noglobstar: options.globstar === false,
|
||||
posix: true
|
||||
};
|
||||
const matcher = picomatch(processed.match, matchOptions);
|
||||
const ignore = picomatch(processed.ignore, matchOptions);
|
||||
const partialMatcher = getPartialMatcher(processed.match, matchOptions);
|
||||
const format = buildFormat(cwd, root, absolute);
|
||||
const excludeFormatter = absolute ? format : buildFormat(cwd, root, true);
|
||||
const excludePredicate = (_, p) => {
|
||||
const relativePath = excludeFormatter(p, true);
|
||||
return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
|
||||
};
|
||||
let maxDepth;
|
||||
if (options.deep !== void 0) maxDepth = Math.round(options.deep - props.depthOffset);
|
||||
const crawler = new fdir({
|
||||
filters: [debug ? (p, isDirectory) => {
|
||||
const path = format(p, isDirectory);
|
||||
const matches = matcher(path) && !ignore(path);
|
||||
if (matches) log(`matched ${path}`);
|
||||
return matches;
|
||||
} : (p, isDirectory) => {
|
||||
const path = format(p, isDirectory);
|
||||
return matcher(path) && !ignore(path);
|
||||
}],
|
||||
exclude: debug ? (_, p) => {
|
||||
const skipped = excludePredicate(_, p);
|
||||
log(`${skipped ? "skipped" : "crawling"} ${p}`);
|
||||
return skipped;
|
||||
} : excludePredicate,
|
||||
fs: options.fs,
|
||||
pathSeparator: "/",
|
||||
relativePaths: !absolute,
|
||||
resolvePaths: absolute,
|
||||
includeBasePath: absolute,
|
||||
resolveSymlinks: followSymbolicLinks,
|
||||
excludeSymlinks: !followSymbolicLinks,
|
||||
excludeFiles: onlyDirectories,
|
||||
includeDirs: onlyDirectories || !options.onlyFiles,
|
||||
maxDepth,
|
||||
signal: options.signal
|
||||
}).crawl(root);
|
||||
if (options.debug) log("internal properties:", {
|
||||
...props,
|
||||
root
|
||||
});
|
||||
return [crawler, cwd !== root && !absolute && buildRelative(cwd, root)];
|
||||
}
|
||||
//#endregion
|
||||
//#region src/index.ts
|
||||
function formatPaths(paths, mapper) {
|
||||
if (mapper) for (let i = paths.length - 1; i >= 0; i--) paths[i] = mapper(paths[i]);
|
||||
return paths;
|
||||
}
|
||||
const defaultOptions = {
|
||||
caseSensitiveMatch: true,
|
||||
debug: !!process.env.TINYGLOBBY_DEBUG,
|
||||
expandDirectories: true,
|
||||
followSymbolicLinks: true,
|
||||
onlyFiles: true
|
||||
};
|
||||
function getOptions(options) {
|
||||
const opts = Object.assign({}, options);
|
||||
for (const key in defaultOptions) if (opts[key] === void 0) Object.assign(opts, { [key]: defaultOptions[key] });
|
||||
opts.cwd = (opts.cwd instanceof URL ? fileURLToPath(opts.cwd) : resolve(opts.cwd || process.cwd())).replace(BACKSLASHES, "/");
|
||||
opts.ignore = ensureStringArray(opts.ignore);
|
||||
opts.fs && (opts.fs = {
|
||||
readdir: opts.fs.readdir || readdir,
|
||||
readdirSync: opts.fs.readdirSync || readdirSync,
|
||||
realpath: opts.fs.realpath || realpath,
|
||||
realpathSync: opts.fs.realpathSync || realpathSync,
|
||||
stat: opts.fs.stat || stat,
|
||||
statSync: opts.fs.statSync || statSync
|
||||
});
|
||||
if (opts.debug) log("globbing with options:", opts);
|
||||
return opts;
|
||||
}
|
||||
function getCrawler(globInput, inputOptions = {}) {
|
||||
var _ref;
|
||||
if (globInput && (inputOptions === null || inputOptions === void 0 ? void 0 : inputOptions.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
|
||||
const isModern = isReadonlyArray(globInput) || typeof globInput === "string";
|
||||
const patterns = ensureStringArray((_ref = isModern ? globInput : globInput.patterns) !== null && _ref !== void 0 ? _ref : "**/*");
|
||||
const options = getOptions(isModern ? inputOptions : globInput);
|
||||
return patterns.length > 0 ? buildCrawler(options, patterns) : [];
|
||||
}
|
||||
async function glob(globInput, options) {
|
||||
const [crawler, relative] = getCrawler(globInput, options);
|
||||
return crawler ? formatPaths(await crawler.withPromise(), relative) : [];
|
||||
}
|
||||
function globSync(globInput, options) {
|
||||
const [crawler, relative] = getCrawler(globInput, options);
|
||||
return crawler ? formatPaths(crawler.sync(), relative) : [];
|
||||
}
|
||||
//#endregion
|
||||
export { convertPathToPattern, escapePath, glob, globSync, isDynamicPattern };
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import Document from './document.js'
|
||||
import LazyResult from './lazy-result.js'
|
||||
import NoWorkResult from './no-work-result.js'
|
||||
import {
|
||||
AcceptedPlugin,
|
||||
Plugin,
|
||||
ProcessOptions,
|
||||
TransformCallback,
|
||||
Transformer
|
||||
} from './postcss.js'
|
||||
import Result from './result.js'
|
||||
import Root from './root.js'
|
||||
|
||||
declare namespace Processor {
|
||||
export { Processor_ as default }
|
||||
}
|
||||
|
||||
/**
|
||||
* Contains plugins to process CSS. Create one `Processor` instance,
|
||||
* initialize its plugins, and then use that instance on numerous CSS files.
|
||||
*
|
||||
* ```js
|
||||
* const processor = postcss([autoprefixer, postcssNested])
|
||||
* processor.process(css1).then(result => console.log(result.css))
|
||||
* processor.process(css2).then(result => console.log(result.css))
|
||||
* ```
|
||||
*/
|
||||
declare class Processor_ {
|
||||
/**
|
||||
* Plugins added to this processor.
|
||||
*
|
||||
* ```js
|
||||
* const processor = postcss([autoprefixer, postcssNested])
|
||||
* processor.plugins.length //=> 2
|
||||
* ```
|
||||
*/
|
||||
plugins: (Plugin | TransformCallback | Transformer)[]
|
||||
|
||||
/**
|
||||
* Current PostCSS version.
|
||||
*
|
||||
* ```js
|
||||
* if (result.processor.version.split('.')[0] !== '6') {
|
||||
* throw new Error('This plugin works only with PostCSS 6')
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
version: string
|
||||
|
||||
/**
|
||||
* @param plugins PostCSS plugins
|
||||
*/
|
||||
constructor(plugins?: readonly AcceptedPlugin[])
|
||||
|
||||
/**
|
||||
* Parses source CSS and returns a `LazyResult` Promise proxy.
|
||||
* Because some plugins can be asynchronous it doesn’t make
|
||||
* any transformations. Transformations will be applied
|
||||
* in the `LazyResult` methods.
|
||||
*
|
||||
* ```js
|
||||
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
|
||||
* .then(result => {
|
||||
* console.log(result.css)
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @param css String with input CSS or any object with a `toString()` method,
|
||||
* like a Buffer. Optionally, send a `Result` instance
|
||||
* and the processor will take the `Root` from it.
|
||||
* @param opts Options.
|
||||
* @return Promise proxy.
|
||||
*/
|
||||
process(
|
||||
css: { toString(): string } | LazyResult | Result | Root | string
|
||||
): LazyResult | NoWorkResult
|
||||
process<RootNode extends Document | Root = Root>(
|
||||
css: { toString(): string } | LazyResult | Result | Root | string,
|
||||
options: ProcessOptions<RootNode>
|
||||
): LazyResult<RootNode>
|
||||
|
||||
/**
|
||||
* Adds a plugin to be used as a CSS processor.
|
||||
*
|
||||
* PostCSS plugin can be in 4 formats:
|
||||
* * A plugin in `Plugin` format.
|
||||
* * A plugin creator function with `pluginCreator.postcss = true`.
|
||||
* PostCSS will call this function without argument to get plugin.
|
||||
* * A function. PostCSS will pass the function a {@link Root}
|
||||
* as the first argument and current `Result` instance
|
||||
* as the second.
|
||||
* * Another `Processor` instance. PostCSS will copy plugins
|
||||
* from that instance into this one.
|
||||
*
|
||||
* Plugins can also be added by passing them as arguments when creating
|
||||
* a `postcss` instance (see [`postcss(plugins)`]).
|
||||
*
|
||||
* Asynchronous plugins should return a `Promise` instance.
|
||||
*
|
||||
* ```js
|
||||
* const processor = postcss()
|
||||
* .use(autoprefixer)
|
||||
* .use(postcssNested)
|
||||
* ```
|
||||
*
|
||||
* @param plugin PostCSS plugin or `Processor` with plugins.
|
||||
* @return Current processor to make methods chain.
|
||||
*/
|
||||
use(plugin: AcceptedPlugin): this
|
||||
}
|
||||
|
||||
declare class Processor extends Processor_ {}
|
||||
|
||||
export = Processor
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
import { __classPrivateFieldSet, __classPrivateFieldGet } from './external/tslib/tslib.es6.js';
|
||||
|
||||
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
var _Channel_onmessage, _Channel_nextMessageIndex, _Channel_pendingMessages, _Channel_messageEndIndex, _Resource_rid;
|
||||
/**
|
||||
* Invoke your custom commands.
|
||||
*
|
||||
* This package is also accessible with `window.__TAURI__.core` when [`app.withGlobalTauri`](https://v2.tauri.app/reference/config/#withglobaltauri) in `tauri.conf.json` is set to `true`.
|
||||
* @module
|
||||
*/
|
||||
/**
|
||||
* A key to be used to implement a special function
|
||||
* on your types that define how your type should be serialized
|
||||
* when passing across the IPC.
|
||||
* @example
|
||||
* Given a type in Rust that looks like this
|
||||
* ```rs
|
||||
* #[derive(serde::Serialize, serde::Deserialize)
|
||||
* enum UserId {
|
||||
* String(String),
|
||||
* Number(u32),
|
||||
* }
|
||||
* ```
|
||||
* `UserId::String("id")` would be serialized into `{ String: "id" }`
|
||||
* and so we need to pass the same structure back to Rust
|
||||
* ```ts
|
||||
* import { SERIALIZE_TO_IPC_FN } from "@tauri-apps/api/core"
|
||||
*
|
||||
* class UserIdString {
|
||||
* id
|
||||
* constructor(id) {
|
||||
* this.id = id
|
||||
* }
|
||||
*
|
||||
* [SERIALIZE_TO_IPC_FN]() {
|
||||
* return { String: this.id }
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* class UserIdNumber {
|
||||
* id
|
||||
* constructor(id) {
|
||||
* this.id = id
|
||||
* }
|
||||
*
|
||||
* [SERIALIZE_TO_IPC_FN]() {
|
||||
* return { Number: this.id }
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* type UserId = UserIdString | UserIdNumber
|
||||
* ```
|
||||
*
|
||||
*/
|
||||
// if this value changes, make sure to update it in:
|
||||
// 1. ipc.js
|
||||
// 2. process-ipc-message-fn.js
|
||||
const SERIALIZE_TO_IPC_FN = '__TAURI_TO_IPC_KEY__';
|
||||
/**
|
||||
* Stores the callback in a known location, and returns an identifier that can be passed to the backend.
|
||||
* The backend uses the identifier to `eval()` the callback.
|
||||
*
|
||||
* @return An unique identifier associated with the callback function.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
function transformCallback(
|
||||
// TODO: Make this not optional in v3
|
||||
callback, once = false) {
|
||||
return window.__TAURI_INTERNALS__.transformCallback(callback, once);
|
||||
}
|
||||
class Channel {
|
||||
constructor(onmessage) {
|
||||
_Channel_onmessage.set(this, void 0);
|
||||
// the index is used as a mechanism to preserve message order
|
||||
_Channel_nextMessageIndex.set(this, 0);
|
||||
_Channel_pendingMessages.set(this, []);
|
||||
_Channel_messageEndIndex.set(this, void 0);
|
||||
__classPrivateFieldSet(this, _Channel_onmessage, onmessage || (() => { }), "f");
|
||||
this.id = transformCallback((rawMessage) => {
|
||||
const index = rawMessage.index;
|
||||
if ('end' in rawMessage) {
|
||||
if (index == __classPrivateFieldGet(this, _Channel_nextMessageIndex, "f")) {
|
||||
this.cleanupCallback();
|
||||
}
|
||||
else {
|
||||
__classPrivateFieldSet(this, _Channel_messageEndIndex, index, "f");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const message = rawMessage.message;
|
||||
// Process the message if we're at the right order
|
||||
if (index == __classPrivateFieldGet(this, _Channel_nextMessageIndex, "f")) {
|
||||
__classPrivateFieldGet(this, _Channel_onmessage, "f").call(this, message);
|
||||
__classPrivateFieldSet(this, _Channel_nextMessageIndex, __classPrivateFieldGet(this, _Channel_nextMessageIndex, "f") + 1, "f");
|
||||
// process pending messages
|
||||
while (__classPrivateFieldGet(this, _Channel_nextMessageIndex, "f") in __classPrivateFieldGet(this, _Channel_pendingMessages, "f")) {
|
||||
const message = __classPrivateFieldGet(this, _Channel_pendingMessages, "f")[__classPrivateFieldGet(this, _Channel_nextMessageIndex, "f")];
|
||||
__classPrivateFieldGet(this, _Channel_onmessage, "f").call(this, message);
|
||||
// eslint-disable-next-line @typescript-eslint/no-array-delete
|
||||
delete __classPrivateFieldGet(this, _Channel_pendingMessages, "f")[__classPrivateFieldGet(this, _Channel_nextMessageIndex, "f")];
|
||||
__classPrivateFieldSet(this, _Channel_nextMessageIndex, __classPrivateFieldGet(this, _Channel_nextMessageIndex, "f") + 1, "f");
|
||||
}
|
||||
if (__classPrivateFieldGet(this, _Channel_nextMessageIndex, "f") === __classPrivateFieldGet(this, _Channel_messageEndIndex, "f")) {
|
||||
this.cleanupCallback();
|
||||
}
|
||||
}
|
||||
// Queue the message if we're not
|
||||
else {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
__classPrivateFieldGet(this, _Channel_pendingMessages, "f")[index] = message;
|
||||
}
|
||||
});
|
||||
}
|
||||
cleanupCallback() {
|
||||
window.__TAURI_INTERNALS__.unregisterCallback(this.id);
|
||||
}
|
||||
set onmessage(handler) {
|
||||
__classPrivateFieldSet(this, _Channel_onmessage, handler, "f");
|
||||
}
|
||||
get onmessage() {
|
||||
return __classPrivateFieldGet(this, _Channel_onmessage, "f");
|
||||
}
|
||||
[(_Channel_onmessage = new WeakMap(), _Channel_nextMessageIndex = new WeakMap(), _Channel_pendingMessages = new WeakMap(), _Channel_messageEndIndex = new WeakMap(), SERIALIZE_TO_IPC_FN)]() {
|
||||
return `__CHANNEL__:${this.id}`;
|
||||
}
|
||||
toJSON() {
|
||||
// eslint-disable-next-line security/detect-object-injection
|
||||
return this[SERIALIZE_TO_IPC_FN]();
|
||||
}
|
||||
}
|
||||
class PluginListener {
|
||||
constructor(plugin, event, channelId) {
|
||||
this.plugin = plugin;
|
||||
this.event = event;
|
||||
this.channelId = channelId;
|
||||
}
|
||||
async unregister() {
|
||||
return invoke(`plugin:${this.plugin}|remove_listener`, {
|
||||
event: this.event,
|
||||
channelId: this.channelId
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Adds a listener to a plugin event.
|
||||
*
|
||||
* @returns The listener object to stop listening to the events.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function addPluginListener(plugin, event, cb) {
|
||||
const handler = new Channel(cb);
|
||||
try {
|
||||
await invoke(`plugin:${plugin}|register_listener`, {
|
||||
event,
|
||||
handler
|
||||
});
|
||||
return new PluginListener(plugin, event, handler.id);
|
||||
}
|
||||
catch {
|
||||
// TODO(v3): remove this fallback
|
||||
// note: we must try with camelCase here for backwards compatibility
|
||||
await invoke(`plugin:${plugin}|registerListener`, { event, handler });
|
||||
return new PluginListener(plugin, event, handler.id);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Get permission state for a plugin.
|
||||
*
|
||||
* This should be used by plugin authors to wrap their actual implementation.
|
||||
*/
|
||||
async function checkPermissions(plugin) {
|
||||
return invoke(`plugin:${plugin}|check_permissions`);
|
||||
}
|
||||
/**
|
||||
* Request permissions.
|
||||
*
|
||||
* This should be used by plugin authors to wrap their actual implementation.
|
||||
*/
|
||||
async function requestPermissions(plugin) {
|
||||
return invoke(`plugin:${plugin}|request_permissions`);
|
||||
}
|
||||
/**
|
||||
* Sends a message to the backend.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { invoke } from '@tauri-apps/api/core';
|
||||
* await invoke('login', { user: 'tauri', password: 'poiwe3h4r5ip3yrhtew9ty' });
|
||||
* ```
|
||||
*
|
||||
* @param cmd The command name.
|
||||
* @param args The optional arguments to pass to the command.
|
||||
* @param options The request options.
|
||||
* @return A promise resolving or rejecting to the backend response.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
async function invoke(cmd, args = {}, options) {
|
||||
return window.__TAURI_INTERNALS__.invoke(cmd, args, options);
|
||||
}
|
||||
/**
|
||||
* Convert a device file path to an URL that can be loaded by the webview.
|
||||
* Note that `asset:` and `http://asset.localhost` must be added to [`app.security.csp`](https://v2.tauri.app/reference/config/#csp-1) in `tauri.conf.json`.
|
||||
* Example CSP value: `"csp": "default-src 'self' ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost"` to use the asset protocol on image sources.
|
||||
*
|
||||
* Additionally, `"enable" : "true"` must be added to [`app.security.assetProtocol`](https://v2.tauri.app/reference/config/#assetprotocolconfig)
|
||||
* in `tauri.conf.json` and its access scope must be defined on the `scope` array on the same `assetProtocol` object.
|
||||
*
|
||||
* @param filePath The file path.
|
||||
* @param protocol The protocol to use. Defaults to `asset`. You only need to set this when using a custom protocol.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { appDataDir, join } from '@tauri-apps/api/path';
|
||||
* import { convertFileSrc } from '@tauri-apps/api/core';
|
||||
* const appDataDirPath = await appDataDir();
|
||||
* const filePath = await join(appDataDirPath, 'assets/video.mp4');
|
||||
* const assetUrl = convertFileSrc(filePath);
|
||||
*
|
||||
* const video = document.getElementById('my-video');
|
||||
* const source = document.createElement('source');
|
||||
* source.type = 'video/mp4';
|
||||
* source.src = assetUrl;
|
||||
* video.appendChild(source);
|
||||
* video.load();
|
||||
* ```
|
||||
*
|
||||
* @return the URL that can be used as source on the webview.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
function convertFileSrc(filePath, protocol = 'asset') {
|
||||
return window.__TAURI_INTERNALS__.convertFileSrc(filePath, protocol);
|
||||
}
|
||||
/**
|
||||
* A rust-backed resource stored through `tauri::Manager::resources_table` API.
|
||||
*
|
||||
* The resource lives in the main process and does not exist
|
||||
* in the Javascript world, and thus will not be cleaned up automatically
|
||||
* except on application exit. If you want to clean it up early, call {@linkcode Resource.close}
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { Resource, invoke } from '@tauri-apps/api/core';
|
||||
* export class DatabaseHandle extends Resource {
|
||||
* static async open(path: string): Promise<DatabaseHandle> {
|
||||
* const rid: number = await invoke('open_db', { path });
|
||||
* return new DatabaseHandle(rid);
|
||||
* }
|
||||
*
|
||||
* async execute(sql: string): Promise<void> {
|
||||
* await invoke('execute_sql', { rid: this.rid, sql });
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
class Resource {
|
||||
get rid() {
|
||||
return __classPrivateFieldGet(this, _Resource_rid, "f");
|
||||
}
|
||||
constructor(rid) {
|
||||
_Resource_rid.set(this, void 0);
|
||||
__classPrivateFieldSet(this, _Resource_rid, rid, "f");
|
||||
}
|
||||
/**
|
||||
* Destroys and cleans up this resource from memory.
|
||||
* **You should not call any method on this object anymore and should drop any reference to it.**
|
||||
*/
|
||||
async close() {
|
||||
return invoke('plugin:resources|close', {
|
||||
rid: this.rid
|
||||
});
|
||||
}
|
||||
}
|
||||
_Resource_rid = new WeakMap();
|
||||
function isTauri() {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
|
||||
return !!(globalThis || window).isTauri;
|
||||
}
|
||||
|
||||
export { Channel, PluginListener, Resource, SERIALIZE_TO_IPC_FN, addPluginListener, checkPermissions, convertFileSrc, invoke, isTauri, requestPermissions, transformCallback };
|
||||
Reference in new issue
Block a user