Modified sql prettier plugin

This commit is contained in:
2025-09-20 19:18:33 +08:00
parent c3670bb8cd
commit 9222a52d91
44 changed files with 1099 additions and 2211 deletions

View File

@@ -55,7 +55,6 @@
"jinx-rust": "^0.1.6", "jinx-rust": "^0.1.6",
"jsox": "^1.2.123", "jsox": "^1.2.123",
"linguist-languages": "^9.0.0", "linguist-languages": "^9.0.0",
"node-sql-parser": "^5.3.12",
"php-parser": "^3.2.5", "php-parser": "^3.2.5",
"pinia": "^3.0.3", "pinia": "^3.0.3",
"pinia-plugin-persistedstate": "^4.5.0", "pinia-plugin-persistedstate": "^4.5.0",
@@ -63,7 +62,6 @@
"remarkable": "^2.0.1", "remarkable": "^2.0.1",
"sass": "^1.92.1", "sass": "^1.92.1",
"sh-syntax": "^0.5.8", "sh-syntax": "^0.5.8",
"sql-formatter": "^15.6.9",
"vue": "^3.5.21", "vue": "^3.5.21",
"vue-i18n": "^11.1.12", "vue-i18n": "^11.1.12",
"vue-pick-colors": "^1.8.0", "vue-pick-colors": "^1.8.0",
@@ -2279,12 +2277,6 @@
"undici-types": "~7.10.0" "undici-types": "~7.10.0"
} }
}, },
"node_modules/@types/pegjs": {
"version": "0.10.6",
"resolved": "https://registry.npmmirror.com/@types/pegjs/-/pegjs-0.10.6.tgz",
"integrity": "sha512-eLYXDbZWXh2uxf+w8sXS8d6KSoXTswfps6fvCUuVAGN8eRpfe7h9eSRydxiSJvo9Bf+GzifsDOr9TMQlmJdmkw==",
"license": "MIT"
},
"node_modules/@types/remarkable": { "node_modules/@types/remarkable": {
"version": "2.0.8", "version": "2.0.8",
"resolved": "https://registry.npmmirror.com/@types/remarkable/-/remarkable-2.0.8.tgz", "resolved": "https://registry.npmmirror.com/@types/remarkable/-/remarkable-2.0.8.tgz",
@@ -2894,6 +2886,7 @@
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz", "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz",
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
"dev": true,
"license": "Python-2.0" "license": "Python-2.0"
}, },
"node_modules/asn1.js": { "node_modules/asn1.js": {
@@ -2982,15 +2975,6 @@
], ],
"license": "MIT" "license": "MIT"
}, },
"node_modules/big-integer": {
"version": "1.6.52",
"resolved": "https://registry.npmmirror.com/big-integer/-/big-integer-1.6.52.tgz",
"integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",
"license": "Unlicense",
"engines": {
"node": ">=0.6"
}
},
"node_modules/binary-extensions": { "node_modules/binary-extensions": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmmirror.com/binary-extensions/-/binary-extensions-2.3.0.tgz", "resolved": "https://registry.npmmirror.com/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -3507,12 +3491,6 @@
"url": "https://jaywcjlove.github.io/#/sponsor" "url": "https://jaywcjlove.github.io/#/sponsor"
} }
}, },
"node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmmirror.com/commander/-/commander-2.20.3.tgz",
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
"license": "MIT"
},
"node_modules/concat-map": { "node_modules/concat-map": {
"version": "0.0.1", "version": "0.0.1",
"resolved": "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz", "resolved": "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz",
@@ -3852,12 +3830,6 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/discontinuous-range": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/discontinuous-range/-/discontinuous-range-1.0.0.tgz",
"integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==",
"license": "MIT"
},
"node_modules/domain-browser": { "node_modules/domain-browser": {
"version": "4.22.0", "version": "4.22.0",
"resolved": "https://registry.npmmirror.com/domain-browser/-/domain-browser-4.22.0.tgz", "resolved": "https://registry.npmmirror.com/domain-browser/-/domain-browser-4.22.0.tgz",
@@ -5340,12 +5312,6 @@
"pathe": "^2.0.1" "pathe": "^2.0.1"
} }
}, },
"node_modules/moo": {
"version": "0.5.2",
"resolved": "https://registry.npmmirror.com/moo/-/moo-0.5.2.tgz",
"integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==",
"license": "BSD-3-Clause"
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
@@ -5395,28 +5361,6 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/nearley": {
"version": "2.20.1",
"resolved": "https://registry.npmmirror.com/nearley/-/nearley-2.20.1.tgz",
"integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==",
"license": "MIT",
"dependencies": {
"commander": "^2.19.0",
"moo": "^0.5.0",
"railroad-diagrams": "^1.0.0",
"randexp": "0.4.6"
},
"bin": {
"nearley-railroad": "bin/nearley-railroad.js",
"nearley-test": "bin/nearley-test.js",
"nearley-unparse": "bin/nearley-unparse.js",
"nearleyc": "bin/nearleyc.js"
},
"funding": {
"type": "individual",
"url": "https://nearley.js.org/#give-to-nearley"
}
},
"node_modules/node-addon-api": { "node_modules/node-addon-api": {
"version": "7.1.1", "version": "7.1.1",
"resolved": "https://registry.npmmirror.com/node-addon-api/-/node-addon-api-7.1.1.tgz", "resolved": "https://registry.npmmirror.com/node-addon-api/-/node-addon-api-7.1.1.tgz",
@@ -5432,19 +5376,6 @@
"optional": true, "optional": true,
"peer": true "peer": true
}, },
"node_modules/node-sql-parser": {
"version": "5.3.12",
"resolved": "https://registry.npmmirror.com/node-sql-parser/-/node-sql-parser-5.3.12.tgz",
"integrity": "sha512-GQBwA2e44qjbK0MzFwh5bNYefniV6cKT4KfjNDpuh/2EWipUEK1BCMc//moSidp8EF6fHB/EqJwUH9GCh9MAPg==",
"license": "Apache-2.0",
"dependencies": {
"@types/pegjs": "^0.10.0",
"big-integer": "^1.6.48"
},
"engines": {
"node": ">=8"
}
},
"node_modules/node-stdlib-browser": { "node_modules/node-stdlib-browser": {
"version": "1.3.1", "version": "1.3.1",
"resolved": "https://registry.npmmirror.com/node-stdlib-browser/-/node-stdlib-browser-1.3.1.tgz", "resolved": "https://registry.npmmirror.com/node-stdlib-browser/-/node-stdlib-browser-1.3.1.tgz",
@@ -6103,25 +6034,6 @@
], ],
"license": "MIT" "license": "MIT"
}, },
"node_modules/railroad-diagrams": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz",
"integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==",
"license": "CC0-1.0"
},
"node_modules/randexp": {
"version": "0.4.6",
"resolved": "https://registry.npmmirror.com/randexp/-/randexp-0.4.6.tgz",
"integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==",
"license": "MIT",
"dependencies": {
"discontinuous-range": "1.0.0",
"ret": "~0.1.10"
},
"engines": {
"node": ">=0.12"
}
},
"node_modules/randombytes": { "node_modules/randombytes": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmmirror.com/randombytes/-/randombytes-2.1.0.tgz", "resolved": "https://registry.npmmirror.com/randombytes/-/randombytes-2.1.0.tgz",
@@ -6255,15 +6167,6 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/ret": {
"version": "0.1.15",
"resolved": "https://registry.npmmirror.com/ret/-/ret-0.1.15.tgz",
"integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==",
"license": "MIT",
"engines": {
"node": ">=0.12"
}
},
"node_modules/reusify": { "node_modules/reusify": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmmirror.com/reusify/-/reusify-1.1.0.tgz", "resolved": "https://registry.npmmirror.com/reusify/-/reusify-1.1.0.tgz",
@@ -6674,19 +6577,6 @@
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"license": "BSD-3-Clause" "license": "BSD-3-Clause"
}, },
"node_modules/sql-formatter": {
"version": "15.6.9",
"resolved": "https://registry.npmmirror.com/sql-formatter/-/sql-formatter-15.6.9.tgz",
"integrity": "sha512-r9VKnkRfKW7jbhTgytwbM+JqmFclQYN9L58Z3UTktuy9V1f1Y+rGK3t70Truh2wIOJzvZkzobAQ2PwGjjXsr6Q==",
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1",
"nearley": "^2.20.1"
},
"bin": {
"sql-formatter": "bin/sql-formatter-cli.cjs"
}
},
"node_modules/std-env": { "node_modules/std-env": {
"version": "3.9.0", "version": "3.9.0",
"resolved": "https://registry.npmmirror.com/std-env/-/std-env-3.9.0.tgz", "resolved": "https://registry.npmmirror.com/std-env/-/std-env-3.9.0.tgz",

View File

@@ -59,7 +59,6 @@
"jinx-rust": "^0.1.6", "jinx-rust": "^0.1.6",
"jsox": "^1.2.123", "jsox": "^1.2.123",
"linguist-languages": "^9.0.0", "linguist-languages": "^9.0.0",
"node-sql-parser": "^5.3.12",
"php-parser": "^3.2.5", "php-parser": "^3.2.5",
"pinia": "^3.0.3", "pinia": "^3.0.3",
"pinia-plugin-persistedstate": "^4.5.0", "pinia-plugin-persistedstate": "^4.5.0",
@@ -67,7 +66,6 @@
"remarkable": "^2.0.1", "remarkable": "^2.0.1",
"sass": "^1.92.1", "sass": "^1.92.1",
"sh-syntax": "^0.5.8", "sh-syntax": "^0.5.8",
"sql-formatter": "^15.6.9",
"vue": "^3.5.21", "vue": "^3.5.21",
"vue-i18n": "^11.1.12", "vue-i18n": "^11.1.12",
"vue-pick-colors": "^1.8.0", "vue-pick-colors": "^1.8.0",

View File

@@ -1,23 +1,31 @@
/** /**
* Prettier Plugin for C/C++ formatting using clang-format WebAssembly * Prettier Plugin for C/C++/C#/Java/Protobuf formatting using clang-format WebAssembly
* *
* This plugin provides support for formatting C/C++ files using the clang-format WASM implementation. * This plugin provides support for formatting multiple languages using the clang-format WASM implementation.
* It supports various C/C++ file extensions and common clang-format styles. * Supported languages:
* - C / C++
* - Objective-C / Objective-C++
* - C#
* - Java
* - Protocol Buffer (Protobuf)
*
* It supports various file extensions and common clang-format styles.
*/ */
import type { Plugin, Parser, Printer } from 'prettier'; import type { Plugin, Parser, Printer } from 'prettier';
// Import the clang-format WASM module // Import the clang-format WASM module
import clangFormatInit, { format } from './clang-format-vite.js'; import clangFormatInit, { format } from './clang-format-vite.js';
const parserName = 'clang'; const parserName = 'clang-format';
// Language configuration // Language configuration
const languages = [ const languages = [
{ {
name: 'C', name: 'C',
aliases: ['c'], aliases: ['c'],
parsers: [parserName], parsers: ['c'],
extensions: ['.c', '.h'], extensions: ['.c', '.h'],
filenames: ['*.c', '*.h'],
aceMode: 'c_cpp', aceMode: 'c_cpp',
tmScope: 'source.c', tmScope: 'source.c',
linguistLanguageId: 50, linguistLanguageId: 50,
@@ -26,8 +34,9 @@ const languages = [
{ {
name: 'C++', name: 'C++',
aliases: ['cpp', 'cxx', 'cc'], aliases: ['cpp', 'cxx', 'cc'],
parsers: [parserName], parsers: ['cpp'],
extensions: ['.cpp', '.cxx', '.cc', '.hpp', '.hxx', '.hh', '.C', '.H'], extensions: ['.cpp', '.cxx', '.cc', '.hpp', '.hxx', '.hh', '.C', '.H'],
filenames: ['*.cpp', '*.cxx', '*.cc', '*.hpp', '*.hxx', '*.hh', '*.C', '*.H'],
aceMode: 'c_cpp', aceMode: 'c_cpp',
tmScope: 'source.cpp', tmScope: 'source.cpp',
linguistLanguageId: 43, linguistLanguageId: 43,
@@ -36,12 +45,57 @@ const languages = [
{ {
name: 'Objective-C', name: 'Objective-C',
aliases: ['objc', 'objectivec'], aliases: ['objc', 'objectivec'],
parsers: [parserName], parsers: ['objective-c'],
extensions: ['.m', '.mm'], extensions: ['.m'],
filenames: ['*.m'],
aceMode: 'objectivec', aceMode: 'objectivec',
tmScope: 'source.objc', tmScope: 'source.objc',
linguistLanguageId: 259, linguistLanguageId: 259,
vscodeLanguageIds: ['objective-c'] vscodeLanguageIds: ['objective-c']
},
{
name: 'Objective-C++',
aliases: ['objcpp', 'objectivecpp'],
parsers: ['objective-cpp'],
extensions: ['.mm'],
filenames: ['*.mm'],
aceMode: 'objectivec',
tmScope: 'source.objcpp',
linguistLanguageId: 260,
vscodeLanguageIds: ['objective-cpp']
},
{
name: 'C#',
aliases: ['csharp', 'cs'],
parsers: ['cs'],
extensions: ['.cs'],
filenames: ['*.cs'],
aceMode: 'csharp',
tmScope: 'source.cs',
linguistLanguageId: 42,
vscodeLanguageIds: ['csharp']
},
{
name: 'Java',
aliases: ['java'],
parsers: ['java'],
extensions: ['.java'],
filenames: ['*.java'],
aceMode: 'java',
tmScope: 'source.java',
linguistLanguageId: 181,
vscodeLanguageIds: ['java']
},
{
name: 'Protocol Buffer',
aliases: ['protobuf', 'proto'],
parsers: ['proto'],
extensions: ['.proto'],
filenames: ['*.proto'],
aceMode: 'protobuf',
tmScope: 'source.proto',
linguistLanguageId: 297,
vscodeLanguageIds: ['proto']
} }
]; ];
@@ -85,7 +139,7 @@ const clangPrinter: Printer<string> = {
const style = getClangStyle(options); const style = getClangStyle(options);
// Format using clang-format (synchronous call) // Format using clang-format (synchronous call)
const formatted = format(text, undefined, style); const formatted = format(text, options.filename, style);
return formatted.trim(); return formatted.trim();
} catch (error) { } catch (error) {
@@ -129,6 +183,13 @@ const options = {
{ value: 'Microsoft', description: "Microsoft's style guide" }, { value: 'Microsoft', description: "Microsoft's style guide" },
{ value: 'GNU', description: 'GNU coding standards' } { value: 'GNU', description: 'GNU coding standards' }
] ]
},
filename: {
// since: '0.1.0',
category: 'Config',
type: 'string',
default: undefined,
description: 'Custom filename to use for web_fmt processing (affects language detection)',
} }
}; };
@@ -141,7 +202,7 @@ const clangPlugin: Plugin = {
printers: { printers: {
[parserName]: clangPrinter, [parserName]: clangPrinter,
}, },
options, ...options,
}; };
// Initialize WASM module when plugin loads // Initialize WASM module when plugin loads

View File

@@ -0,0 +1,44 @@
set -Eeo pipefail
cd $(dirname $0)/..
project_root=$(pwd)
rm -rf pkg
mkdir -p pkg build
cd build
export CC=$(which clang)
export CXX=$(which clang++)
emcmake cmake -G Ninja ..
ninja clang-format-wasm
cd $project_root
if [[ ! -z "${WASM_OPT}" ]]; then
wasm-opt -Os build/clang-format-esm.wasm -o build/clang-format-esm-Os.wasm
wasm-opt -Oz build/clang-format-esm.wasm -o build/clang-format-esm-Oz.wasm
fi
SMALLEST_WASM=$(ls -Sr build/clang-format-e*.wasm | head -1)
cp $SMALLEST_WASM pkg/clang-format.wasm
cat src/template.js build/clang-format-esm.js >pkg/clang-format.js
# add shebang
echo '#!/usr/bin/env node' | cat - ./build/clang-format-cli.js >./pkg/clang-format-cli.cjs
cp ./build/clang-format-cli.wasm ./pkg/
cp ./src/clang-format.d.ts src/clang-format-*.js ./pkg/
cp ./package.json LICENSE README.md .npmignore ./pkg/
# copy git-clang-format and clang-format-diff.py
cp ./build/_deps/llvm_project-src/clang/tools/clang-format/git-clang-format ./pkg/
cp ./build/_deps/llvm_project-src/clang/tools/clang-format/clang-format-diff.py ./pkg/
ls -lh ./pkg
./scripts/package.mjs ./package.json
# make sure repo is clean
# git diff --exit-code

View File

@@ -0,0 +1,95 @@
diff --git a/src/cli.cc b/src/cli.cc
index 2861005..69ec009 100644
--- a/src/cli.cc
+++ b/src/cli.cc
@@ -12,7 +12,7 @@
///
//===----------------------------------------------------------------------===//
-#include "../../lib/Format/MatchFilePath.h"
+#include "clang/../../lib/Format/MatchFilePath.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
@@ -27,6 +27,8 @@
#include "llvm/Support/Process.h"
#include <fstream>
+#include "CustomFileSystem.h"
+
using namespace llvm;
using clang::tooling::Replacements;
@@ -448,9 +450,12 @@ static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) {
return true;
}
+ auto RealFS = vfs::getRealFileSystem();
+ auto CustomFS = new vfs::CustomFileSystem(RealFS);
+ IntrusiveRefCntPtr<vfs::FileSystem> CustomFSPtr(CustomFS);
Expected<FormatStyle> FormatStyle =
getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer(),
- nullptr, WNoErrorList.isSet(WNoError::Unknown));
+ CustomFSPtr.get(), WNoErrorList.isSet(WNoError::Unknown));
if (!FormatStyle) {
llvm::errs() << toString(FormatStyle.takeError()) << "\n";
return true;
@@ -571,10 +576,15 @@ static int dumpConfig() {
}
Code = std::move(CodeOrErr.get());
}
+
+ auto RealFS = vfs::getRealFileSystem();
+ auto CustomFS = new vfs::CustomFileSystem(RealFS);
+ IntrusiveRefCntPtr<vfs::FileSystem> CustomFSPtr(CustomFS);
+
Expected<clang::format::FormatStyle> FormatStyle = clang::format::getStyle(
Style,
FileNames.empty() || FileNames[0] == "-" ? AssumeFileName : FileNames[0],
- FallbackStyle, Code ? Code->getBuffer() : "");
+ FallbackStyle, Code ? Code->getBuffer() : "", CustomFSPtr.get());
if (!FormatStyle) {
llvm::errs() << toString(FormatStyle.takeError()) << "\n";
return 1;
@@ -607,24 +617,26 @@ static bool isIgnored(StringRef FilePath) {
String Path;
String AbsPath{FilePath};
+ auto PathStyle = vfs::getPathStyle();
+
using namespace llvm::sys::path;
- make_absolute(AbsPath);
- remove_dots(AbsPath, /*remove_dot_dot=*/true);
+ vfs::make_absolute(AbsPath);
+ remove_dots(AbsPath, /*remove_dot_dot=*/true, PathStyle);
- if (StringRef Dir{parent_path(AbsPath)}; PrevDir != Dir) {
+ if (StringRef Dir{parent_path(AbsPath, PathStyle)}; PrevDir != Dir) {
PrevDir = Dir;
for (;;) {
Path = Dir;
- append(Path, ".clang-format-ignore");
+ append(Path, PathStyle, ".clang-format-ignore");
if (is_regular_file(Path))
break;
- Dir = parent_path(Dir);
+ Dir = parent_path(Dir, PathStyle);
if (Dir.empty())
return false;
}
- IgnoreDir = convert_to_slash(Dir);
+ IgnoreDir = convert_to_slash(Dir, PathStyle);
std::ifstream IgnoreFile{Path.c_str()};
if (!IgnoreFile.good())
@@ -644,7 +656,7 @@ static bool isIgnored(StringRef FilePath) {
if (IgnoreDir.empty())
return false;
- const auto Pathname{convert_to_slash(AbsPath)};
+ const auto Pathname{convert_to_slash(AbsPath, PathStyle)};
for (const auto &Pat : Patterns) {
const bool IsNegated = Pat[0] == '!';
StringRef Pattern{Pat};

View File

@@ -0,0 +1,27 @@
current_dir=$(pwd)
tmp_dir=$(mktemp -d)
cd $tmp_dir
git init
cp $current_dir/build/_deps/llvm_project-src/clang/tools/clang-format/ClangFormat.cpp ./cli.cc
git add -f .
git commit -m "init"
cp $current_dir/src/cli.cc ./cli.cc
git add -f .
git diff \
--cached \
--no-color \
--ignore-space-at-eol \
--no-ext-diff \
--src-prefix=a/src/ \
--dst-prefix=b/src/ \
>$current_dir/scripts/cli.patch || true
rm -rf $tmp_dir

View File

@@ -1,3 +0,0 @@
*.tgz
*.unopt.wasm
jsr.jsonc

View File

@@ -1,32 +0,0 @@
export function format(input: string, filename: string, config?: LayoutConfig): string;
interface LayoutConfig {
line_width?: number;
line_ending?: "lf" | "crlf";
language_version?: string;
}
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
export type InitOutput = unknown;
// export type SyncInitInput = BufferSource | WebAssembly.Module;
// /**
// * Instantiates the given `module`, which can either be bytes or
// * a precompiled `WebAssembly.Module`.
// *
// * @param {SyncInitInput} module
// *
// * @returns {InitOutput}
// */
// export function initSync(module: SyncInitInput): InitOutput;
/**
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
* for everything else, calls `WebAssembly.instantiate` directly.
*
* @param {InitInput | Promise<InitInput>} module_or_path
*
* @returns {Promise<InitOutput>}
*/
export default function init(module_or_path?: InitInput | Promise<InitInput>): Promise<InitOutput>;

View File

@@ -1,84 +0,0 @@
import { format as dart_fmt, instantiate, invoke } from "./dart_fmt.mjs";
let wasm;
function get_imports() {}
function init_memory() {}
function normalize(module) {
if (!(module instanceof WebAssembly.Module)) {
return new WebAssembly.Module(module);
}
return module;
}
export default async function (input) {
if (wasm !== undefined) return wasm;
if (typeof input === "undefined") {
input = new URL("dart_fmt.wasm", import.meta.url);
}
const imports = get_imports();
if (
typeof input === "string" ||
(typeof Request === "function" && input instanceof Request) ||
(typeof URL === "function" && input instanceof URL)
) {
input = fetch(input);
}
init_memory(imports);
wasm = await load(await input)
.then(normalize)
.then(instantiate);
invoke(wasm);
return wasm;
}
async function load(module) {
if (typeof Response === "function" && module instanceof Response) {
if ("compileStreaming" in WebAssembly) {
try {
return await WebAssembly.compileStreaming(module);
} catch (e) {
if (module.headers.get("Content-Type") != "application/wasm") {
console.warn(
"`WebAssembly.compileStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",
e,
);
} else {
throw e;
}
}
}
return module.arrayBuffer();
}
return module;
}
export function format(source, filename = "stdin.dart", config = {}) {
const options = { lineEnding: "\n" };
if (config.line_width) {
options.pageWidth = config.line_width;
}
if (options.line_ending === "crlf") {
options.lineEnding = "\r\n";
}
if(options.language_version) {
options.languageVersion = options.language_version;
}
const result = dart_fmt(source, filename, JSON.stringify(options));
const err = result[0] === "x";
const output = result.slice(1);
if (err) {
throw new Error(output);
}
return output;
}

View File

@@ -1,10 +0,0 @@
import fs from "node:fs/promises";
import initAsync from "./dart_fmt.js";
const wasm = new URL("./dart_fmt.wasm", import.meta.url);
export default function __wbg_init(init = fs.readFile(wasm)) {
return initAsync(init);
}
export * from "./dart_fmt.js";

View File

@@ -1,8 +0,0 @@
import initAsync from "./dart_fmt.js";
import wasm from "./dart_fmt.wasm?url";
export default function __wbg_init(input = wasm) {
return initAsync(input);
}
export * from "./dart_fmt.js";

View File

@@ -62,11 +62,10 @@ const dartPrinter: Printer<string> = {
} }
const text = (path as any).getValue ? (path as any).getValue() : path.node; const text = (path as any).getValue ? (path as any).getValue() : path.node;
const filename = getDartFilename(options.filepath);
const config = getDartConfig(options); const config = getDartConfig(options);
// Format using dart_fmt (synchronous call) // Format using dart_fmt (synchronous call)
const formatted = format(text, filename, config); const formatted = format(text, undefined, config);
return formatted.trim(); return formatted.trim();
} catch (error) { } catch (error) {
@@ -77,21 +76,6 @@ const dartPrinter: Printer<string> = {
}, },
}; };
// Helper function to get appropriate filename for dart_fmt
function getDartFilename(filepath?: string): string {
if (!filepath) {
return 'stdin.dart';
}
const filename = filepath.split(/[/\\]/).pop() || 'main.dart';
// Ensure .dart extension
if (!filename.endsWith('.dart')) {
return 'main.dart';
}
return filename;
}
// Helper function to create Dart config from Prettier options // Helper function to create Dart config from Prettier options
function getDartConfig(options: any): any { function getDartConfig(options: any): any {

View File

@@ -0,0 +1,5 @@
cd $(dirname $0)/..
dart compile wasm ./lib/binding.dart -o ./build/dart_fmt.wasm

View File

@@ -1,7 +0,0 @@
cd $(dirname $0)/..
dart compile wasm ./lib/binding.dart -o ./build/dart_fmt.wasm
cp -LR ./extra/. ./build/
./scripts/patch.mjs ./build/dart_fmt.mjs
./scripts/package.mjs ./package.json

View File

@@ -1,16 +0,0 @@
#!/usr/bin/env node
import process from "node:process";
import path from "node:path";
import fs from "node:fs";
const pkg_path = path.resolve(process.cwd(), process.argv[2]);
const pkg_text = fs.readFileSync(pkg_path, { encoding: "utf-8" });
const pkg_json = JSON.parse(pkg_text);
// JSR
const jsr_path = path.resolve(pkg_path, "..", "build", "jsr.jsonc");
pkg_json.name = "@fmt/dart-fmt";
pkg_json.exports = "./dart_fmt.js";
pkg_json.exclude = ["!../build", "*.tgz", ".npmignore"];
fs.writeFileSync(jsr_path, JSON.stringify(pkg_json, null, 4));

View File

@@ -1,13 +0,0 @@
#!/usr/bin/env node
import process from "node:process";
import path from "node:path";
import fs from "node:fs";
const file_path = path.resolve(process.cwd(), process.argv[2]);
let file_text = fs.readFileSync(file_path, { encoding: "utf-8" });
file_text = file_text.replace(`"length": (s) => s.length`, '"length": (s) => s?.length||0');
file_text = file_text.replace('globalThis.format', 'format');
file_text += "\nexport let format;";
fs.writeFileSync(file_path, file_text);

View File

@@ -1,2 +0,0 @@
*.tgz
jsr.jsonc

View File

@@ -1,10 +0,0 @@
import fs from "node:fs/promises";
import initAsync from "./lua_fmt.js";
const wasm = new URL("./lua_fmt_bg.wasm", import.meta.url);
export default function __wbg_init(init = { module_or_path: fs.readFile(wasm) }) {
return initAsync(init);
}
export * from "./lua_fmt.js";

View File

@@ -1,8 +0,0 @@
import initAsync from "./lua_fmt.js";
import wasm from "./lua_fmt_bg.wasm?url";
export default function __wbg_init(input = { module_or_path: wasm }) {
return initAsync(input);
}
export * from "./lua_fmt.js";

View File

@@ -1,39 +0,0 @@
#!/usr/bin/env node
import process from "node:process";
import path from "node:path";
import fs from "node:fs";
const pkg_path = path.resolve(process.cwd(), process.argv[2]);
const pkg_text = fs.readFileSync(pkg_path, { encoding: "utf-8" });
const pkg_json = JSON.parse(pkg_text);
delete pkg_json.files;
pkg_json.main = pkg_json.module;
pkg_json.type = "module";
pkg_json.publishConfig = {
access: "public",
};
pkg_json.exports = {
".": {
types: "./lua_fmt.d.ts",
node: "./lua_fmt_node.js",
default: "./lua_fmt.js",
},
"./vite": {
types: "./lua_fmt.d.ts",
default: "./lua_fmt_vite.js",
},
"./package.json": "./package.json",
"./*": "./*",
};
fs.writeFileSync(pkg_path, JSON.stringify(pkg_json, null, 4));
// JSR
const jsr_path = path.resolve(pkg_path, "..", "jsr.jsonc");
pkg_json.name = "@fmt/lua-fmt";
pkg_json.exports = "./lua_fmt.js";
pkg_json.exclude = ["!**", "*.tgz"];
fs.writeFileSync(jsr_path, JSON.stringify(pkg_json, null, 4));

View File

@@ -4,8 +4,3 @@ crates_dir=$(pwd)
cd ../.. cd ../..
wasm-pack build --target=web --scope=wasm-fmt crates/lua_fmt wasm-pack build --target=web --scope=wasm-fmt crates/lua_fmt
cd $crates_dir
cp -R ./extra/. ./pkg/
./scripts/package.mjs ./pkg/package.json

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,140 @@
/**
* Prettier Plugin for SQL formatting using SQL Format WebAssembly
*
* This plugin provides support for formatting SQL files using the SQL Format WASM implementation.
*/
import type { Plugin, Parser, Printer } from 'prettier';
// Import the SQL Format WASM module
import sqlFmtInit, { format, type Config } from './sql_fmt_vite.js';
const parserName = 'sql';
// Language configuration
const languages = [
{
name: 'SQL',
aliases: ['sql'],
parsers: [parserName],
extensions: ['.sql'],
aceMode: 'sql',
tmScope: 'source.sql',
linguistLanguageId: 316,
vscodeLanguageIds: ['sql']
}
];
// Parser configuration
const sqlParser: Parser<string> = {
astFormat: parserName,
parse: (text: string) => text,
locStart: () => 0,
locEnd: (node: string) => node.length,
};
// Initialize SQL Format WASM module
let initPromise: Promise<void> | null = null;
let isInitialized = false;
function initSqlFmt(): Promise<void> {
if (initPromise) {
return initPromise;
}
initPromise = (async () => {
if (!isInitialized) {
await sqlFmtInit();
isInitialized = true;
}
})();
return initPromise;
}
// Printer configuration
const sqlPrinter: Printer<string> = {
print: (path, options) => {
try {
if (!isInitialized) {
console.warn('SQL Format WASM module not initialized, returning original text');
return (path as any).getValue ? (path as any).getValue() : path.node;
}
const text = (path as any).getValue ? (path as any).getValue() : path.node;
const config = getSqlFmtConfig(options);
// Format using SQL Format (synchronous call)
const formatted = format(text, 'index.sql', config);
return formatted.trim();
} catch (error) {
console.warn('SQL formatting failed:', error);
// Return original text if formatting fails
return (path as any).getValue ? (path as any).getValue() : path.node;
}
},
};
// Helper function to create SQL Format config from Prettier options
function getSqlFmtConfig(options: any): Config {
const config: Config = {};
// Map Prettier options to SQL Format config
if (options.useTabs !== undefined) {
config.indent_style = options.useTabs ? 'tab' : 'space';
}
if (options.tabWidth !== undefined) {
config.indent_width = options.tabWidth;
}
if (options.sqlUppercase !== undefined) {
config.uppercase = options.sqlUppercase;
}
if (options.sqlLinesBetweenQueries !== undefined) {
config.lines_between_queries = options.sqlLinesBetweenQueries;
}
return config;
}
// Plugin options
const options = {
sqlUppercase: {
since: '0.0.1',
category: 'Format' as const,
type: 'boolean' as const,
default: false,
description: 'When set, changes reserved keywords to ALL CAPS'
},
sqlLinesBetweenQueries: {
since: '0.0.1',
category: 'Format' as const,
type: 'int' as const,
default: 1,
description: 'Controls the number of line breaks after a query'
}
};
// Plugin definition
const sqlPlugin: Plugin = {
languages,
parsers: {
[parserName]: sqlParser,
},
printers: {
[parserName]: sqlPrinter,
},
options,
};
// Initialize the WASM module
initSqlFmt().catch(error => {
console.error('Failed to initialize SQL Format WASM module:', error);
});
export default sqlPlugin;
export { languages };
export const parsers = sqlPlugin.parsers;
export const printers = sqlPlugin.printers;

View File

@@ -1,30 +0,0 @@
// SQL语言定义
export const languages = [
{
name: "SQL",
parsers: ["sql"],
extensions: [
".sql",
".ddl",
".dml",
".hql",
".psql",
".plsql",
".mysql",
".mssql",
".pgsql",
".sqlite",
".bigquery",
".snowflake",
".redshift",
".db2",
".n1ql",
".cql"
],
filenames: [
"*.sql",
"*.ddl",
"*.dml"
]
}
];

View File

@@ -1,40 +0,0 @@
import { AST, Option } from 'node-sql-parser';
import { Options, ParserOptions, Plugin } from 'prettier';
import {
FormatOptions,
FormatOptionsWithLanguage,
} from 'sql-formatter';
export type SqlBaseOptions = Option &
Partial<
| (FormatOptions & { dialect: string })
| (FormatOptionsWithLanguage & { dialect?: never })
> & {
formatter?: 'sql-formatter' | 'node-sql-parser' | 'sql-cst';
params?: string;
paramTypes?: string;
autoDetectDialect?: boolean;
};
export type SqlOptions = ParserOptions<AST> & SqlBaseOptions;
export type SqlFormatOptions = Options & SqlBaseOptions;
export declare const languages: Plugin["languages"];
export declare const parsers: {
sql: {
parse(text: string, options?: SqlOptions): AST | string;
astFormat: 'sql';
locStart(): number;
locEnd(): number;
};
};
export declare const printers: Plugin["printers"];
export declare const options: Plugin["options"];
export declare function detectDialect(sql: string): string;
declare const SqlPlugin: Plugin<AST | string>;
export default SqlPlugin;

View File

@@ -1,459 +0,0 @@
import { JSOX } from 'jsox';
import nodeSqlParser from 'node-sql-parser';
import {
format,
formatDialect,
} from 'sql-formatter';
import { detectDialect } from './detect.mjs';
import { languages } from './languages.js';
const parser = new nodeSqlParser.Parser();
const SQL_FORMATTER = 'sql-formatter';
const NODE_SQL_PARSER = 'node-sql-parser';
// Parsers
export const parsers = {
sql: {
parse(text, options = {}) {
const { formatter, type, database } = options;
return formatter === SQL_FORMATTER
? text
: parser.astify(text, { type, database });
},
astFormat: 'sql',
locStart: () => -1,
locEnd: () => -1,
},
};
// Printers
export const printers = {
sql: {
print(path, options = {}) {
const value = path.node;
const {
formatter = SQL_FORMATTER,
type,
database,
dialect,
language,
params,
paramTypes,
autoDetectDialect = true,
...formatOptions
} = options;
let formatted;
if (typeof value === 'string') {
// 准备sql-formatter选项
const sqlFormatterOptions = {
...formatOptions,
params:
params == null
? undefined
: JSOX.parse(params),
paramTypes:
paramTypes == null
? undefined
: JSOX.parse(paramTypes),
};
let finalLanguage = language;
let finalDialect = dialect;
if (autoDetectDialect && !language && !dialect) {
const detectedDialect = detectDialect(value);
finalLanguage = detectedDialect;
}
// 使用适当的格式化方法
if (finalDialect != null) {
// 使用formatDialect方法
formatted = formatDialect(value, {
...sqlFormatterOptions,
dialect: JSOX.parse(finalDialect),
});
} else {
// 使用format方法
formatted = format(value, {
...sqlFormatterOptions,
language: finalLanguage,
});
}
} else {
// 使用node-sql-parser进行格式化
formatted = parser.sqlify(value, { type, database });
}
return formatted + '\n';
},
},
};
// 插件选项
export const options = {
formatter: {
category: 'Config',
type: 'choice',
default: SQL_FORMATTER,
description: 'Choose which formatter to be used',
choices: [
{
value: SQL_FORMATTER,
description: 'use `sql-formatter` as formatter',
},
{
value: NODE_SQL_PARSER,
description: 'use `node-sql-parser` as formatter',
},
],
},
autoDetectDialect: {
category: 'Config',
type: 'boolean',
default: true,
description: 'Automatically detect SQL dialect if language/dialect is not specified',
},
dialect: {
category: 'Config',
type: 'string',
description: 'SQL dialect for `sql-formatter` formatDialect()',
},
language: {
category: 'Config',
type: 'choice',
default: 'sql',
description: 'SQL dialect for `sql-formatter` format()',
choices: [
{
value: 'sql',
description: 'Standard SQL: https://en.wikipedia.org/wiki/SQL:2011',
},
{
value: 'bigquery',
description:
'Google Standard SQL (Bigquery): https://cloud.google.com/bigquery',
},
{
value: 'db2',
description: 'IBM DB2: https://www.ibm.com/products/db2',
},
{
value: 'db2i',
description:
'IBM DB2i (experimental): https://www.ibm.com/docs/en/i/7.5?topic=overview-db2-i',
},
{
value: 'hive',
description: 'Apache Hive: https://hive.apache.org',
},
{
value: 'mariadb',
description: 'MariaDB: https://mariadb.com',
},
{
value: 'mysql',
description: 'MySQL: https://www.mysql.com',
},
{
value: 'n1ql',
description:
'Couchbase N1QL: https://www.couchbase.com/products/n1ql',
},
{
value: 'plsql',
description:
'Oracle PL/SQL: https://www.oracle.com/database/technologies/appdev/plsql.html',
},
{
value: 'postgresql',
description: 'PostgreSQL: https://www.postgresql.org',
},
{
value: 'redshift',
description:
'Amazon Redshift: https://docs.aws.amazon.com/redshift/latest/dg/cm_chap_SQLCommandRef.html',
},
{
value: 'singlestoredb',
description:
'SingleStoreDB: https://docs.singlestore.com/db/v7.8/en/introduction/singlestore-documentation.html',
},
{
value: 'snowflake',
description: 'Snowflake: https://docs.snowflake.com',
},
{
value: 'spark',
description: 'Spark: https://spark.apache.org',
},
{
value: 'sqlite',
description: 'SQLite: https://www.sqlite.org',
},
{
value: 'transactsql',
description:
'SQL Server Transact-SQL: https://docs.microsoft.com/en-us/sql/sql-server/',
},
{
value: 'tsql',
description:
'SQL Server Transact-SQL: https://docs.microsoft.com/en-us/sql/sql-server/',
},
{
value: 'trino',
description: 'Trino: https://trino.io',
},
],
},
keywordCase: {
category: 'Output',
type: 'choice',
default: 'preserve',
description:
'Converts reserved keywords to upper- or lowercase for `sql-formatter`',
choices: [
{
value: 'preserve',
description: 'preserves the original case of reserved keywords',
},
{
value: 'upper',
description: 'converts reserved keywords to uppercase',
},
{
value: 'lower',
description: 'converts reserved keywords to lowercase',
},
],
},
dataTypeCase: {
category: 'Output',
type: 'choice',
default: 'preserve',
description:
'Converts data types to upper- or lowercase for `sql-formatter`',
choices: [
{
value: 'preserve',
description: 'preserves the original case of data types',
},
{
value: 'upper',
description: 'converts data types to uppercase',
},
{
value: 'lower',
description: 'converts data types to lowercase',
},
],
},
functionCase: {
category: 'Output',
type: 'choice',
default: 'preserve',
description:
'Converts functions to upper- or lowercase for `sql-formatter`',
choices: [
{
value: 'preserve',
description: 'preserves the original case of functions',
},
{
value: 'upper',
description: 'converts functions to uppercase',
},
{
value: 'lower',
description: 'converts functions to lowercase',
},
],
},
identifierCase: {
category: 'Output',
type: 'choice',
default: 'preserve',
description:
'Converts identifiers to upper- or lowercase for `sql-formatter`. Only unquoted identifiers are converted. (experimental)',
choices: [
{
value: 'preserve',
description: 'preserves the original case of identifiers',
},
{
value: 'upper',
description: 'converts identifiers to uppercase',
},
{
value: 'lower',
description: 'converts identifiers to lowercase',
},
],
},
uppercase: {
category: 'Output',
type: 'boolean',
deprecated: '0.7.0',
description: 'Use `keywordCase` option instead',
},
indentStyle: {
category: 'Format',
type: 'choice',
default: 'standard',
description: `Switches between different indentation styles for \`sql-formatter\`.
Caveats of using \`"tabularLeft"\` and \`"tabularRight"\`:
- \`tabWidth\` option is ignored. Indentation will always be 10 spaces, regardless of what is specified by \`tabWidth\``,
choices: [
{
value: 'standard',
description:
'indents code by the amount specified by `tabWidth` option',
},
{
value: 'tabularLeft',
description:
'indents in tabular style with 10 spaces, aligning keywords to left',
},
{
value: 'tabularRight',
description:
'indents in tabular style with 10 spaces, aligning keywords to right',
},
],
},
logicalOperatorNewline: {
category: 'Format',
type: 'choice',
default: 'before',
description:
'Decides newline placement before or after logical operators (AND, OR, XOR)',
choices: [
{
value: 'before',
description: 'adds newline before the operator',
},
{
value: 'after',
description: 'adds newline after the operator',
},
],
},
expressionWidth: {
category: 'Format',
type: 'int',
default: 50,
description:
'Determines maximum length of parenthesized expressions for `sql-formatter`',
},
linesBetweenQueries: {
category: 'Format',
type: 'int',
default: 1,
description:
'Decides how many empty lines to leave between SQL statements for `sql-formatter`',
},
denseOperators: {
category: 'Format',
type: 'boolean',
default: false,
description:
'Decides whitespace around operators for `sql-formatter`. Does not apply to logical operators (AND, OR, XOR).',
},
newlineBeforeSemicolon: {
category: 'Format',
type: 'boolean',
default: false,
description:
'Whether to place query separator (`;`) on a separate line for `sql-formatter`',
},
params: {
category: 'Format',
type: 'string',
description:
'Specifies `JSOX` **stringified** parameter values to fill in for placeholders inside SQL for `sql-formatter`. This option is designed to be used through API (though nothing really prevents usage from command line).',
},
paramTypes: {
category: 'Config',
type: 'string',
description:
'Specifies `JSOX` **stringified** parameter types to support when parsing SQL prepared statements for `sql-formatter`.',
},
type: {
category: 'Config',
type: 'choice',
default: 'table',
description: 'Check the SQL with Authority List for `node-sql-parser`',
choices: [
{
value: 'table',
description: '`table` mode',
},
{
value: 'column',
description: '`column` mode',
},
],
},
database: {
category: 'Config',
type: 'choice',
default: 'mysql',
description: 'SQL dialect for `node-sql-parser`',
choices: [
{
value: 'bigquery',
description: 'BigQuery: https://cloud.google.com/bigquery',
},
{
value: 'db2',
description: 'IBM DB2: https://www.ibm.com/analytics/db2',
},
{
value: 'hive',
description: 'Hive: https://hive.apache.org',
},
{
value: 'mariadb',
description: 'MariaDB: https://mariadb.com',
},
{
value: 'mysql',
description: 'MySQL: https://www.mysql.com',
},
{
value: 'postgresql',
description: 'PostgreSQL: https://www.postgresql.org',
},
{
value: 'transactsql',
description:
'TransactSQL: https://docs.microsoft.com/en-us/sql/t-sql',
},
{
value: 'flinksql',
description:
'FlinkSQL: https://ci.apache.org/projects/flink/flink-docs-stable',
},
{
value: 'snowflake',
description: 'Snowflake (alpha): https://docs.snowflake.com',
},
],
},
};
const SqlPlugin = {
languages,
parsers,
printers,
options,
};
export { languages };
export default SqlPlugin;

View File

@@ -0,0 +1,58 @@
/* tslint:disable */
/* eslint-disable */
export function format(input: string, filename: string, config?: Config): string;
interface LayoutConfig {
indent_style?: "tab" | "space";
indent_width?: number;
}
export interface Config extends LayoutConfig {
/**
* When set, changes reserved keywords to ALL CAPS
*
* Default: false
*/
uppercase?: boolean;
/**
* Controls the number of line breaks after a query
*
* Default: 1
*/
lines_between_queries?: number;
}
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
export interface InitOutput {
readonly memory: WebAssembly.Memory;
readonly format: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
readonly __wbindgen_export_0: (a: number, b: number) => number;
readonly __wbindgen_export_1: (a: number, b: number, c: number, d: number) => number;
readonly __wbindgen_export_2: (a: number) => void;
readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
readonly __wbindgen_export_3: (a: number, b: number, c: number) => void;
}
export type SyncInitInput = BufferSource | WebAssembly.Module;
/**
* Instantiates the given `module`, which can either be bytes or
* a precompiled `WebAssembly.Module`.
*
* @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
*
* @returns {InitOutput}
*/
export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
/**
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
* for everything else, calls `WebAssembly.instantiate` directly.
*
* @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
*
* @returns {Promise<InitOutput>}
*/
export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;

View File

@@ -0,0 +1,524 @@
let wasm;
const heap = new Array(128).fill(undefined);
heap.push(undefined, null, true, false);
function getObject(idx) { return heap[idx]; }
let WASM_VECTOR_LEN = 0;
let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}
const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } );
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length, 1) >>> 0;
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len, 1) >>> 0;
const mem = getUint8ArrayMemory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
let cachedDataViewMemory0 = null;
function getDataViewMemory0() {
if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
}
return cachedDataViewMemory0;
}
let heap_next = heap.length;
function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next;
heap_next = heap[idx];
heap[idx] = obj;
return idx;
}
function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
wasm.__wbindgen_export_2(addHeapObject(e));
}
}
function isLikeNone(x) {
return x === undefined || x === null;
}
function debugString(val) {
// primitive types
const type = typeof val;
if (type == 'number' || type == 'boolean' || val == null) {
return `${val}`;
}
if (type == 'string') {
return `"${val}"`;
}
if (type == 'symbol') {
const description = val.description;
if (description == null) {
return 'Symbol';
} else {
return `Symbol(${description})`;
}
}
if (type == 'function') {
const name = val.name;
if (typeof name == 'string' && name.length > 0) {
return `Function(${name})`;
} else {
return 'Function';
}
}
// objects
if (Array.isArray(val)) {
const length = val.length;
let debug = '[';
if (length > 0) {
debug += debugString(val[0]);
}
for(let i = 1; i < length; i++) {
debug += ', ' + debugString(val[i]);
}
debug += ']';
return debug;
}
// Test for built-in
const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
let className;
if (builtInMatches && builtInMatches.length > 1) {
className = builtInMatches[1];
} else {
// Failed to match the standard '[object ClassName]'
return toString.call(val);
}
if (className == 'Object') {
// we're a user defined class or Object
// JSON.stringify avoids problems with cycles, and is generally much
// easier than looping through ownProperties of `val`.
try {
return 'Object(' + JSON.stringify(val) + ')';
} catch (_) {
return 'Object';
}
}
// errors
if (val instanceof Error) {
return `${val.name}: ${val.message}\n${val.stack}`;
}
// TODO we could test for more things here, like `Set`s and `Map`s.
return className;
}
const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );
if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
function dropObject(idx) {
if (idx < 132) return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
/**
* @param {string} input
* @param {string} filename
* @param {Config | undefined} [config]
* @returns {string}
*/
export function format(input, filename, config) {
let deferred4_0;
let deferred4_1;
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passStringToWasm0(input, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
const len0 = WASM_VECTOR_LEN;
const ptr1 = passStringToWasm0(filename, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
const len1 = WASM_VECTOR_LEN;
wasm.format(retptr, ptr0, len0, ptr1, len1, isLikeNone(config) ? 0 : addHeapObject(config));
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
var ptr3 = r0;
var len3 = r1;
if (r3) {
ptr3 = 0; len3 = 0;
throw takeObject(r2);
}
deferred4_0 = ptr3;
deferred4_1 = len3;
return getStringFromWasm0(ptr3, len3);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
wasm.__wbindgen_export_3(deferred4_0, deferred4_1, 1);
}
}
async function __wbg_load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
if (module.headers.get('Content-Type') != 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
} else {
throw e;
}
}
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
}
}
}
function __wbg_get_imports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_String_8f0eb39a4a4c2f66 = function(arg0, arg1) {
const ret = String(getObject(arg1));
const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
const len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
};
imports.wbg.__wbg_buffer_61b7ce01341d7f88 = function(arg0) {
const ret = getObject(arg0).buffer;
return addHeapObject(ret);
};
imports.wbg.__wbg_call_b0d8e36992d9900d = function() { return handleError(function (arg0, arg1) {
const ret = getObject(arg0).call(getObject(arg1));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_done_f22c1561fa919baa = function(arg0) {
const ret = getObject(arg0).done;
return ret;
};
imports.wbg.__wbg_entries_4f2bb9b0d701c0f6 = function(arg0) {
const ret = Object.entries(getObject(arg0));
return addHeapObject(ret);
};
imports.wbg.__wbg_get_9aa3dff3f0266054 = function(arg0, arg1) {
const ret = getObject(arg0)[arg1 >>> 0];
return addHeapObject(ret);
};
imports.wbg.__wbg_get_bbccf8970793c087 = function() { return handleError(function (arg0, arg1) {
const ret = Reflect.get(getObject(arg0), getObject(arg1));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_instanceof_ArrayBuffer_670ddde44cdb2602 = function(arg0) {
let result;
try {
result = getObject(arg0) instanceof ArrayBuffer;
} catch (_) {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_instanceof_Map_98ecb30afec5acdb = function(arg0) {
let result;
try {
result = getObject(arg0) instanceof Map;
} catch (_) {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_instanceof_Uint8Array_28af5bc19d6acad8 = function(arg0) {
let result;
try {
result = getObject(arg0) instanceof Uint8Array;
} catch (_) {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_isArray_1ba11a930108ec51 = function(arg0) {
const ret = Array.isArray(getObject(arg0));
return ret;
};
imports.wbg.__wbg_isSafeInteger_12f5549b2fca23f4 = function(arg0) {
const ret = Number.isSafeInteger(getObject(arg0));
return ret;
};
imports.wbg.__wbg_iterator_23604bb983791576 = function() {
const ret = Symbol.iterator;
return addHeapObject(ret);
};
imports.wbg.__wbg_length_65d1cd11729ced11 = function(arg0) {
const ret = getObject(arg0).length;
return ret;
};
imports.wbg.__wbg_length_d65cf0786bfc5739 = function(arg0) {
const ret = getObject(arg0).length;
return ret;
};
imports.wbg.__wbg_new_3ff5b33b1ce712df = function(arg0) {
const ret = new Uint8Array(getObject(arg0));
return addHeapObject(ret);
};
imports.wbg.__wbg_next_01dd9234a5bf6d05 = function() { return handleError(function (arg0) {
const ret = getObject(arg0).next();
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_next_137428deb98342b0 = function(arg0) {
const ret = getObject(arg0).next;
return addHeapObject(ret);
};
imports.wbg.__wbg_set_23d69db4e5c66a6e = function(arg0, arg1, arg2) {
getObject(arg0).set(getObject(arg1), arg2 >>> 0);
};
imports.wbg.__wbg_value_4c32fd138a88eee2 = function(arg0) {
const ret = getObject(arg0).value;
return addHeapObject(ret);
};
imports.wbg.__wbindgen_as_number = function(arg0) {
const ret = +getObject(arg0);
return ret;
};
imports.wbg.__wbindgen_bigint_from_i64 = function(arg0) {
const ret = arg0;
return addHeapObject(ret);
};
imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) {
const ret = BigInt.asUintN(64, arg0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_bigint_get_as_i64 = function(arg0, arg1) {
const v = getObject(arg1);
const ret = typeof(v) === 'bigint' ? v : undefined;
getDataViewMemory0().setBigInt64(arg0 + 8 * 1, isLikeNone(ret) ? BigInt(0) : ret, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
};
imports.wbg.__wbindgen_boolean_get = function(arg0) {
const v = getObject(arg0);
const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2;
return ret;
};
imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {
const ret = debugString(getObject(arg1));
const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
const len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
};
imports.wbg.__wbindgen_error_new = function(arg0, arg1) {
const ret = new Error(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
imports.wbg.__wbindgen_in = function(arg0, arg1) {
const ret = getObject(arg0) in getObject(arg1);
return ret;
};
imports.wbg.__wbindgen_is_bigint = function(arg0) {
const ret = typeof(getObject(arg0)) === 'bigint';
return ret;
};
imports.wbg.__wbindgen_is_function = function(arg0) {
const ret = typeof(getObject(arg0)) === 'function';
return ret;
};
imports.wbg.__wbindgen_is_object = function(arg0) {
const val = getObject(arg0);
const ret = typeof(val) === 'object' && val !== null;
return ret;
};
imports.wbg.__wbindgen_jsval_eq = function(arg0, arg1) {
const ret = getObject(arg0) === getObject(arg1);
return ret;
};
imports.wbg.__wbindgen_jsval_loose_eq = function(arg0, arg1) {
const ret = getObject(arg0) == getObject(arg1);
return ret;
};
imports.wbg.__wbindgen_memory = function() {
const ret = wasm.memory;
return addHeapObject(ret);
};
imports.wbg.__wbindgen_number_get = function(arg0, arg1) {
const obj = getObject(arg1);
const ret = typeof(obj) === 'number' ? obj : undefined;
getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
};
imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
const ret = getObject(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
takeObject(arg0);
};
imports.wbg.__wbindgen_string_get = function(arg0, arg1) {
const obj = getObject(arg1);
const ret = typeof(obj) === 'string' ? obj : undefined;
var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
var len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
};
imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
const ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
return imports;
}
function __wbg_init_memory(imports, memory) {
}
function __wbg_finalize_init(instance, module) {
wasm = instance.exports;
__wbg_init.__wbindgen_wasm_module = module;
cachedDataViewMemory0 = null;
cachedUint8ArrayMemory0 = null;
return wasm;
}
function initSync(module) {
if (wasm !== undefined) return wasm;
if (typeof module !== 'undefined') {
if (Object.getPrototypeOf(module) === Object.prototype) {
({module} = module)
} else {
console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
}
}
const imports = __wbg_get_imports();
__wbg_init_memory(imports);
if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}
const instance = new WebAssembly.Instance(module, imports);
return __wbg_finalize_init(instance, module);
}
async function __wbg_init(module_or_path) {
if (wasm !== undefined) return wasm;
if (typeof module_or_path !== 'undefined') {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
({module_or_path} = module_or_path)
} else {
console.warn('using deprecated parameters for the initialization function; pass a single object instead')
}
}
if (typeof module_or_path === 'undefined') {
module_or_path = new URL('sql_fmt_bg.wasm', import.meta.url);
}
const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
module_or_path = fetch(module_or_path);
}
__wbg_init_memory(imports);
const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module);
}
export { initSync };
export default __wbg_init;

View File

@@ -0,0 +1,9 @@
/* tslint:disable */
/* eslint-disable */
export const memory: WebAssembly.Memory;
export const format: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
export const __wbindgen_export_0: (a: number, b: number) => number;
export const __wbindgen_export_1: (a: number, b: number, c: number, d: number) => number;
export const __wbindgen_export_2: (a: number) => void;
export const __wbindgen_add_to_stack_pointer: (a: number) => number;
export const __wbindgen_export_3: (a: number, b: number, c: number) => void;

View File

@@ -1,10 +1,10 @@
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import initAsync from "./web_fmt.js"; import initAsync from "./sql_fmt.js";
const wasm = new URL("./web_fmt_bg.wasm", import.meta.url); const wasm = new URL("./sql_fmt_bg.wasm", import.meta.url);
export default function __wbg_init(init = { module_or_path: fs.readFile(wasm) }) { export default function __wbg_init(init = { module_or_path: fs.readFile(wasm) }) {
return initAsync(init); return initAsync(init);
} }
export * from "./web_fmt.js"; export * from "./sql_fmt.js";

View File

@@ -0,0 +1,8 @@
import initAsync from "./sql_fmt.js";
import wasm from "./sql_fmt_bg.wasm?url";
export default function __wbg_init(input = { module_or_path: wasm }) {
return initAsync(input);
}
export * from "./sql_fmt.js";

View File

@@ -0,0 +1,3 @@
cd $(dirname $0)/..
wasm-pack build --target=web --scope=wasm-fmt

View File

@@ -0,0 +1,97 @@
use serde::Deserialize;
use sqlformat::{FormatOptions, QueryParams};
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
pub fn format(input: &str, filename: &str, config: Option<Config>) -> Result<String, String> {
let _ = filename;
let config = config
.map(|x| serde_wasm_bindgen::from_value::<SQLConfig>(x.clone()))
.transpose()
.map_err(|op| op.to_string())?
.unwrap_or_default();
Ok(sqlformat::format(input, &QueryParams::None, &config.into()))
}
#[wasm_bindgen(typescript_custom_section)]
const TS_Config: &'static str = r#"
interface LayoutConfig {
indent_style?: "tab" | "space";
indent_width?: number;
}"#;
#[wasm_bindgen(typescript_custom_section)]
const TS_Config: &'static str = r#"
export interface Config extends LayoutConfig {
/**
* When set, changes reserved keywords to ALL CAPS
*
* Default: false
*/
uppercase?: boolean;
/**
* Controls the number of line breaks after a query
*
* Default: 1
*/
lines_between_queries?: number;
}"#;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "Config")]
pub type Config;
}
#[derive(Deserialize, Clone, Copy)]
enum IndentStyle {
#[serde(rename = "tab")]
Tab,
#[serde(rename = "space")]
Space,
}
#[derive(Deserialize, Clone, Default)]
struct LayoutConfig {
#[serde(alias = "indentStyle")]
indent_style: Option<IndentStyle>,
#[serde(alias = "indentWidth")]
indent_width: Option<u8>,
}
#[derive(Deserialize, Clone, Default)]
struct SQLConfig {
#[serde(flatten)]
layout: LayoutConfig,
pub uppercase: Option<bool>,
#[serde(alias = "linesBetweenQueries")]
pub lines_between_queries: Option<u8>,
}
impl<'a> From<SQLConfig> for FormatOptions<'a> {
fn from(val: SQLConfig) -> Self {
let mut config = FormatOptions::default();
let indent_width = val.layout.indent_width.unwrap_or(2);
if let Some(indent_style) = val.layout.indent_style {
config.indent = match indent_style {
IndentStyle::Tab => sqlformat::Indent::Tabs,
IndentStyle::Space => sqlformat::Indent::Spaces(indent_width),
};
}
config.uppercase = val.uppercase;
if let Some(lines_between_queries) = val.lines_between_queries {
config.lines_between_queries = lines_between_queries;
}
config
}
}

View File

@@ -1,2 +0,0 @@
*.tgz
jsr.jsonc

View File

@@ -1,10 +0,0 @@
import fs from "node:fs/promises";
import initAsync from "./json_fmt.js";
const wasm = new URL("./json_fmt_bg.wasm", import.meta.url);
export default function __wbg_init(init = { module_or_path: fs.readFile(wasm) }) {
return initAsync(init);
}
export * from "./json_fmt.js";

View File

@@ -1,8 +0,0 @@
import initAsync from "./json_fmt.js";
import wasm from "./json_fmt_bg.wasm?url";
export default function __wbg_init(input = { module_or_path: wasm }) {
return initAsync(input);
}
export * from "./json_fmt.js";

View File

@@ -1,39 +0,0 @@
#!/usr/bin/env node
import process from "node:process";
import path from "node:path";
import fs from "node:fs";
const pkg_path = path.resolve(process.cwd(), process.argv[2]);
const pkg_text = fs.readFileSync(pkg_path, { encoding: "utf-8" });
const pkg_json = JSON.parse(pkg_text);
delete pkg_json.files;
pkg_json.main = pkg_json.module;
pkg_json.type = "module";
pkg_json.publishConfig = {
access: "public",
};
pkg_json.exports = {
".": {
types: "./json_fmt.d.ts",
node: "./json_fmt_node.js",
default: "./json_fmt.js",
},
"./vite": {
types: "./json_fmt.d.ts",
default: "./json_fmt_vite.js",
},
"./package.json": "./package.json",
"./*": "./*",
};
fs.writeFileSync(pkg_path, JSON.stringify(pkg_json, null, 4));
// JSR
const jsr_path = path.resolve(pkg_path, "..", "jsr.jsonc");
pkg_json.name = "@fmt/json-fmt";
pkg_json.exports = "./json_fmt.js";
pkg_json.exclude = ["!**", "*.tgz"];
fs.writeFileSync(jsr_path, JSON.stringify(pkg_json, null, 4));

View File

@@ -4,8 +4,3 @@ crates_dir=$(pwd)
cd ../.. cd ../..
wasm-pack build --target=web --scope=wasm-fmt crates/json_fmt wasm-pack build --target=web --scope=wasm-fmt crates/json_fmt
cd $crates_dir
cp -R ./extra/. ./pkg/
./scripts/package.mjs ./pkg/package.json

View File

@@ -1,2 +0,0 @@
*.tgz
jsr.jsonc

View File

@@ -1,8 +0,0 @@
import initAsync from "./web_fmt.js";
import wasm from "./web_fmt_bg.wasm?url";
export default function __wbg_init(input = { module_or_path: wasm }) {
return initAsync(input);
}
export * from "./web_fmt.js";

View File

@@ -1,39 +0,0 @@
#!/usr/bin/env node
import process from "node:process";
import path from "node:path";
import fs from "node:fs";
const pkg_path = path.resolve(process.cwd(), process.argv[2]);
const pkg_text = fs.readFileSync(pkg_path, { encoding: "utf-8" });
const pkg_json = JSON.parse(pkg_text);
delete pkg_json.files;
pkg_json.main = pkg_json.module;
pkg_json.type = "module";
pkg_json.publishConfig = {
access: "public",
};
pkg_json.exports = {
".": {
types: "./web_fmt.d.ts",
node: "./web_fmt_node.js",
default: "./web_fmt.js",
},
"./vite": {
types: "./web_fmt.d.ts",
default: "./web_fmt_vite.js",
},
"./package.json": "./package.json",
"./*": "./*",
};
fs.writeFileSync(pkg_path, JSON.stringify(pkg_json, null, 4));
// JSR
const jsr_path = path.resolve(pkg_path, "..", "jsr.jsonc");
pkg_json.name = "@fmt/web-fmt";
pkg_json.exports = "./web_fmt.js";
pkg_json.exclude = ["!**", "*.tgz"];
fs.writeFileSync(jsr_path, JSON.stringify(pkg_json, null, 4));

View File

@@ -4,8 +4,3 @@ crates_dir=$(pwd)
cd ../.. cd ../..
wasm-pack build --target=web --scope=wasm-fmt crates/web_fmt wasm-pack build --target=web --scope=wasm-fmt crates/web_fmt
cd $crates_dir
cp -R ./extra/. ./pkg/
./scripts/package.mjs ./pkg/package.json

View File

@@ -39,7 +39,7 @@ import cssPrettierPlugin from "prettier/plugins/postcss"
import markdownPrettierPlugin from "prettier/plugins/markdown" import markdownPrettierPlugin from "prettier/plugins/markdown"
import yamlPrettierPlugin from "prettier/plugins/yaml" import yamlPrettierPlugin from "prettier/plugins/yaml"
import goPrettierPlugin from "@/common/prettier/plugins/go/go.mjs" import goPrettierPlugin from "@/common/prettier/plugins/go/go.mjs"
import sqlPrettierPlugin from "@/common/prettier/plugins/sql/sql" import sqlPrettierPlugin from "@/common/prettier/plugins/sql"
import phpPrettierPlugin from "@/common/prettier/plugins/php" import phpPrettierPlugin from "@/common/prettier/plugins/php"
import javaPrettierPlugin from "@/common/prettier/plugins/java" import javaPrettierPlugin from "@/common/prettier/plugins/java"
import xmlPrettierPlugin from "@prettier/plugin-xml" import xmlPrettierPlugin from "@prettier/plugin-xml"
@@ -115,14 +115,23 @@ export const LANGUAGES: LanguageInfo[] = [
plugins: [xmlPrettierPlugin] plugins: [xmlPrettierPlugin]
}), }),
new LanguageInfo("cpp", "C++", cppLanguage.parser, ["cpp", "c"], { new LanguageInfo("cpp", "C++", cppLanguage.parser, ["cpp", "c"], {
parser: "clang", parser: "clang-format",
plugins: [clangPrettierPlugin] plugins: [clangPrettierPlugin],
options: {
filename: "index.cpp"
}
}), }),
new LanguageInfo("rs", "Rust", rustLanguage.parser, ["rs"], { new LanguageInfo("rs", "Rust", rustLanguage.parser, ["rs"], {
parser: "jinx-rust", parser: "jinx-rust",
plugins: [rustPrettierPlugin] plugins: [rustPrettierPlugin]
}), }),
new LanguageInfo("cs", "C#", StreamLanguage.define(csharp).parser, ["cs"]), new LanguageInfo("cs", "C#", StreamLanguage.define(csharp).parser, ["cs"],{
parser: "clang-format",
plugins: [clangPrettierPlugin],
options: {
filename: "index.cs"
}
}),
new LanguageInfo("rb", "Ruby", StreamLanguage.define(ruby).parser, ["rb"]), new LanguageInfo("rb", "Ruby", StreamLanguage.define(ruby).parser, ["rb"]),
new LanguageInfo("sh", "Shell", StreamLanguage.define(shell).parser, ["sh", "bat"], { new LanguageInfo("sh", "Shell", StreamLanguage.define(shell).parser, ["sh", "bat"], {
parser: "sh", parser: "sh",