@wasm-fmt/dart_fmt 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## 0.0.0
2
+
3
+ - Initial version.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 wasm-fmt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ [![Test](https://github.com/wasm-fmt/dart_fmt/actions/workflows/test.yml/badge.svg)](https://github.com/wasm-fmt/dart_fmt/actions/workflows/test.yml)
2
+
3
+ # Install
4
+
5
+ [![npm](https://img.shields.io/npm/v/@wasm-fmt/dart_fmt)](https://www.npmjs.com/package/@wasm-fmt/dart_fmt)
6
+
7
+ ```bash
8
+ npm install @wasm-fmt/dart_fmt
9
+ ```
10
+
11
+ [![jsr.io](https://jsr.io/badges/@fmt/dart-fmt)](https://jsr.io/@fmt/dart-fmt)
12
+
13
+ ```bash
14
+ npx jsr add @fmt/dart-fmt
15
+ ```
16
+
17
+ # Usage
18
+
19
+ ```javascript
20
+ import init, { format } from "@wasm-fmt/dart_fmt";
21
+
22
+ await init();
23
+
24
+ const input = `void main() { print('Hello, World!'); }`;
25
+
26
+ const formatted = format(input, "main.dart");
27
+ console.log(formatted);
28
+ ```
29
+
30
+ For Vite users:
31
+
32
+ ```JavaScript
33
+ import init, { format } from "@wasm-fmt/dart_fmt/vite";
34
+
35
+ // ...
36
+ ```
package/dart_fmt.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ export function format(input: string, filename: string, config?: LayoutConfig): string;
2
+
3
+ interface LayoutConfig {
4
+ line_width?: number;
5
+ line_ending?: "lf" | "crlf";
6
+ }
7
+
8
+ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
9
+
10
+ export type InitOutput = unknown;
11
+
12
+ export type SyncInitInput = BufferSource | WebAssembly.Module;
13
+ /**
14
+ * Instantiates the given `module`, which can either be bytes or
15
+ * a precompiled `WebAssembly.Module`.
16
+ *
17
+ * @param {SyncInitInput} module
18
+ *
19
+ * @returns {InitOutput}
20
+ */
21
+ export function initSync(module: SyncInitInput): InitOutput;
22
+
23
+ /**
24
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
25
+ * for everything else, calls `WebAssembly.instantiate` directly.
26
+ *
27
+ * @param {InitInput | Promise<InitInput>} module_or_path
28
+ *
29
+ * @returns {Promise<InitOutput>}
30
+ */
31
+ export default function init(module_or_path?: InitInput | Promise<InitInput>): Promise<InitOutput>;
package/dart_fmt.js ADDED
@@ -0,0 +1,120 @@
1
+ import { instantiate } from "./dart_fmt.mjs";
2
+
3
+ let wasm;
4
+
5
+ function get_imports() {}
6
+ function init_memory() {}
7
+
8
+ export function initSync(module) {
9
+ if (wasm !== undefined) return wasm;
10
+
11
+ const imports = get_imports();
12
+
13
+ init_memory(imports);
14
+
15
+ if (!(module instanceof WebAssembly.Module)) {
16
+ module = new WebAssembly.Module(module);
17
+ }
18
+
19
+ return (wasm = instantiate(module));
20
+ }
21
+
22
+ export default async function (input) {
23
+ if (wasm !== undefined) return wasm;
24
+
25
+ if (typeof input === "undefined") {
26
+ input = new URL("dart_fmt.wasm", import.meta.url);
27
+ }
28
+ const imports = get_imports();
29
+
30
+ if (
31
+ typeof input === "string" ||
32
+ (typeof Request === "function" && input instanceof Request) ||
33
+ (typeof URL === "function" && input instanceof URL)
34
+ ) {
35
+ input = fetch(input);
36
+ }
37
+
38
+ init_memory(imports);
39
+
40
+ return (wasm = await load(await input).then(instantiate));
41
+ }
42
+
43
+ async function load(module) {
44
+ if (typeof Response === "function" && module instanceof Response) {
45
+ if ("compileStreaming" in WebAssembly) {
46
+ try {
47
+ return await WebAssembly.compileStreaming(module);
48
+ } catch (e) {
49
+ if (module.headers.get("Content-Type") != "application/wasm") {
50
+ console.warn(
51
+ "`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",
52
+ e,
53
+ );
54
+ } else {
55
+ throw e;
56
+ }
57
+ }
58
+ }
59
+
60
+ return module.arrayBuffer();
61
+ }
62
+
63
+ return module;
64
+ }
65
+
66
+ function stringFromDartString(string) {
67
+ const totalLength = wasm.exports.$stringLength(string);
68
+ let result = "";
69
+ let index = 0;
70
+ while (index < totalLength) {
71
+ let chunkLength = Math.min(totalLength - index, 0xffff);
72
+ const array = new Array(chunkLength);
73
+ for (let i = 0; i < chunkLength; i++) {
74
+ array[i] = wasm.exports.$stringRead(string, index++);
75
+ }
76
+ result += String.fromCharCode(...array);
77
+ }
78
+ return result;
79
+ }
80
+
81
+ function stringToDartString(string) {
82
+ const length = string.length;
83
+ let range = 0;
84
+ for (let i = 0; i < length; i++) {
85
+ range |= string.codePointAt(i);
86
+ }
87
+ if (range < 256) {
88
+ const dartString = wasm.exports.$stringAllocate1(length);
89
+ for (let i = 0; i < length; i++) {
90
+ wasm.exports.$stringWrite1(dartString, i, string.codePointAt(i));
91
+ }
92
+ return dartString;
93
+ } else {
94
+ const dartString = wasm.exports.$stringAllocate2(length);
95
+ for (let i = 0; i < length; i++) {
96
+ wasm.exports.$stringWrite2(dartString, i, string.charCodeAt(i));
97
+ }
98
+ return dartString;
99
+ }
100
+ }
101
+
102
+ export function format(source, filename, config = {}) {
103
+ const options = { lineEnding: "\n" };
104
+ if (config.line_width) {
105
+ options.pageWidth = config.line_width;
106
+ }
107
+ if (options.line_ending === "crlf") {
108
+ options.lineEnding = "\r\n";
109
+ }
110
+
111
+ const sourceString = stringToDartString(source);
112
+ const filenameString = stringToDartString(filename);
113
+ const configString = stringToDartString(JSON.stringify(options));
114
+ const result = wasm.exports.format(
115
+ sourceString,
116
+ filenameString,
117
+ configString,
118
+ );
119
+ return stringFromDartString(result);
120
+ }
package/dart_fmt.mjs ADDED
@@ -0,0 +1,279 @@
1
+ let buildArgsList;
2
+
3
+ // `modulePromise` is a promise to the `WebAssembly.module` object to be
4
+ // instantiated.
5
+ // `importObjectPromise` is a promise to an object that contains any additional
6
+ // imports needed by the module that aren't provided by the standard runtime.
7
+ // The fields on this object will be merged into the importObject with which
8
+ // the module will be instantiated.
9
+ // This function returns a promise to the instantiated module.
10
+ export const instantiate = async (modulePromise, importObjectPromise) => {
11
+ let dartInstance;
12
+
13
+ function stringFromDartString(string) {
14
+ const totalLength = dartInstance.exports.$stringLength(string);
15
+ let result = '';
16
+ let index = 0;
17
+ while (index < totalLength) {
18
+ let chunkLength = Math.min(totalLength - index, 0xFFFF);
19
+ const array = new Array(chunkLength);
20
+ for (let i = 0; i < chunkLength; i++) {
21
+ array[i] = dartInstance.exports.$stringRead(string, index++);
22
+ }
23
+ result += String.fromCharCode(...array);
24
+ }
25
+ return result;
26
+ }
27
+
28
+ function stringToDartString(string) {
29
+ const length = string.length;
30
+ let range = 0;
31
+ for (let i = 0; i < length; i++) {
32
+ range |= string.codePointAt(i);
33
+ }
34
+ if (range < 256) {
35
+ const dartString = dartInstance.exports.$stringAllocate1(length);
36
+ for (let i = 0; i < length; i++) {
37
+ dartInstance.exports.$stringWrite1(dartString, i, string.codePointAt(i));
38
+ }
39
+ return dartString;
40
+ } else {
41
+ const dartString = dartInstance.exports.$stringAllocate2(length);
42
+ for (let i = 0; i < length; i++) {
43
+ dartInstance.exports.$stringWrite2(dartString, i, string.charCodeAt(i));
44
+ }
45
+ return dartString;
46
+ }
47
+ }
48
+
49
+ // Converts a Dart List to a JS array. Any Dart objects will be converted, but
50
+ // this will be cheap for JSValues.
51
+ function arrayFromDartList(constructor, list) {
52
+ const length = dartInstance.exports.$listLength(list);
53
+ const array = new constructor(length);
54
+ for (let i = 0; i < length; i++) {
55
+ array[i] = dartInstance.exports.$listRead(list, i);
56
+ }
57
+ return array;
58
+ }
59
+
60
+ buildArgsList = function(list) {
61
+ const dartList = dartInstance.exports.$makeStringList();
62
+ for (let i = 0; i < list.length; i++) {
63
+ dartInstance.exports.$listAdd(dartList, stringToDartString(list[i]));
64
+ }
65
+ return dartList;
66
+ }
67
+
68
+ // A special symbol attached to functions that wrap Dart functions.
69
+ const jsWrappedDartFunctionSymbol = Symbol("JSWrappedDartFunction");
70
+
71
+ function finalizeWrapper(dartFunction, wrapped) {
72
+ wrapped.dartFunction = dartFunction;
73
+ wrapped[jsWrappedDartFunctionSymbol] = true;
74
+ return wrapped;
75
+ }
76
+
77
+ if (WebAssembly.String === undefined) {
78
+ console.log("WebAssembly.String is undefined, adding polyfill");
79
+ WebAssembly.String = {
80
+ "charCodeAt": (s, i) => s.charCodeAt(i),
81
+ "compare": (s1, s2) => {
82
+ if (s1 < s2) return -1;
83
+ if (s1 > s2) return 1;
84
+ return 0;
85
+ },
86
+ "concat": (s1, s2) => s1 + s2,
87
+ "equals": (s1, s2) => s1 === s2,
88
+ "fromCharCode": (i) => String.fromCharCode(i),
89
+ "length": (s) => s.length,
90
+ "substring": (s, a, b) => s.substring(a, b),
91
+ };
92
+ }
93
+
94
+ // Imports
95
+ const dart2wasm = {
96
+
97
+ _69: s => stringToDartString(JSON.stringify(stringFromDartString(s))),
98
+ _70: s => console.log(stringFromDartString(s)),
99
+ _173: o => o === undefined,
100
+ _174: o => typeof o === 'boolean',
101
+ _175: o => typeof o === 'number',
102
+ _177: o => typeof o === 'string',
103
+ _180: o => o instanceof Int8Array,
104
+ _181: o => o instanceof Uint8Array,
105
+ _182: o => o instanceof Uint8ClampedArray,
106
+ _183: o => o instanceof Int16Array,
107
+ _184: o => o instanceof Uint16Array,
108
+ _185: o => o instanceof Int32Array,
109
+ _186: o => o instanceof Uint32Array,
110
+ _187: o => o instanceof Float32Array,
111
+ _188: o => o instanceof Float64Array,
112
+ _189: o => o instanceof ArrayBuffer,
113
+ _190: o => o instanceof DataView,
114
+ _191: o => o instanceof Array,
115
+ _192: o => typeof o === 'function' && o[jsWrappedDartFunctionSymbol] === true,
116
+ _195: o => o instanceof RegExp,
117
+ _196: (l, r) => l === r,
118
+ _197: o => o,
119
+ _198: o => o,
120
+ _199: o => o,
121
+ _200: b => !!b,
122
+ _201: o => o.length,
123
+ _204: (o, i) => o[i],
124
+ _205: f => f.dartFunction,
125
+ _206: l => arrayFromDartList(Int8Array, l),
126
+ _207: l => arrayFromDartList(Uint8Array, l),
127
+ _208: l => arrayFromDartList(Uint8ClampedArray, l),
128
+ _209: l => arrayFromDartList(Int16Array, l),
129
+ _210: l => arrayFromDartList(Uint16Array, l),
130
+ _211: l => arrayFromDartList(Int32Array, l),
131
+ _212: l => arrayFromDartList(Uint32Array, l),
132
+ _213: l => arrayFromDartList(Float32Array, l),
133
+ _214: l => arrayFromDartList(Float64Array, l),
134
+ _215: (data, length) => {
135
+ const view = new DataView(new ArrayBuffer(length));
136
+ for (let i = 0; i < length; i++) {
137
+ view.setUint8(i, dartInstance.exports.$byteDataGetUint8(data, i));
138
+ }
139
+ return view;
140
+ },
141
+ _216: l => arrayFromDartList(Array, l),
142
+ _217: stringFromDartString,
143
+ _218: stringToDartString,
144
+ _225: (o, p) => o[p],
145
+ _162: (s, m) => {
146
+ try {
147
+ return new RegExp(s, m);
148
+ } catch (e) {
149
+ return String(e);
150
+ }
151
+ },
152
+ _163: (x0,x1) => x0.exec(x1),
153
+ _164: (x0,x1) => x0.test(x1),
154
+ _165: (x0,x1) => x0.exec(x1),
155
+ _166: (x0,x1) => x0.exec(x1),
156
+ _167: x0 => x0.pop(),
157
+ _221: l => new Array(l),
158
+ _229: o => String(o),
159
+ _234: x0 => x0.index,
160
+ _236: x0 => x0.length,
161
+ _238: (x0,x1) => x0[x1],
162
+ _240: (x0,x1) => x0.exec(x1),
163
+ _242: x0 => x0.flags,
164
+ _243: x0 => x0.multiline,
165
+ _244: x0 => x0.ignoreCase,
166
+ _245: x0 => x0.unicode,
167
+ _246: x0 => x0.dotAll,
168
+ _247: (x0,x1) => x0.lastIndex = x1,
169
+ _122: Object.is,
170
+ _124: WebAssembly.String.concat,
171
+ _132: (o) => new DataView(o.buffer, o.byteOffset, o.byteLength),
172
+ _82: (a, i) => a.push(i),
173
+ _92: (a, b) => a == b ? 0 : (a > b ? 1 : -1),
174
+ _93: a => a.length,
175
+ _95: (a, i) => a[i],
176
+ _96: (a, i, v) => a[i] = v,
177
+ _98: a => a.join(''),
178
+ _101: (s, t) => s.split(t),
179
+ _102: s => s.toLowerCase(),
180
+ _103: s => s.toUpperCase(),
181
+ _104: s => s.trim(),
182
+ _106: s => s.trimRight(),
183
+ _108: (s, p, i) => s.indexOf(p, i),
184
+ _109: (s, p, i) => s.lastIndexOf(p, i),
185
+ _111: (o, start, length) => new Uint8Array(o.buffer, o.byteOffset + start, length),
186
+ _112: (o, start, length) => new Int8Array(o.buffer, o.byteOffset + start, length),
187
+ _113: (o, start, length) => new Uint8ClampedArray(o.buffer, o.byteOffset + start, length),
188
+ _114: (o, start, length) => new Uint16Array(o.buffer, o.byteOffset + start, length),
189
+ _115: (o, start, length) => new Int16Array(o.buffer, o.byteOffset + start, length),
190
+ _116: (o, start, length) => new Uint32Array(o.buffer, o.byteOffset + start, length),
191
+ _117: (o, start, length) => new Int32Array(o.buffer, o.byteOffset + start, length),
192
+ _120: (o, start, length) => new Float32Array(o.buffer, o.byteOffset + start, length),
193
+ _121: (o, start, length) => new Float64Array(o.buffer, o.byteOffset + start, length),
194
+ _123: WebAssembly.String.charCodeAt,
195
+ _125: WebAssembly.String.substring,
196
+ _126: WebAssembly.String.length,
197
+ _127: WebAssembly.String.equals,
198
+ _128: WebAssembly.String.compare,
199
+ _129: WebAssembly.String.fromCharCode,
200
+ _136: Function.prototype.call.bind(Object.getOwnPropertyDescriptor(DataView.prototype, 'byteLength').get),
201
+ _137: (b, o) => new DataView(b, o),
202
+ _139: Function.prototype.call.bind(DataView.prototype.getUint8),
203
+ _140: Function.prototype.call.bind(DataView.prototype.setUint8),
204
+ _141: Function.prototype.call.bind(DataView.prototype.getInt8),
205
+ _142: Function.prototype.call.bind(DataView.prototype.setInt8),
206
+ _143: Function.prototype.call.bind(DataView.prototype.getUint16),
207
+ _144: Function.prototype.call.bind(DataView.prototype.setUint16),
208
+ _145: Function.prototype.call.bind(DataView.prototype.getInt16),
209
+ _146: Function.prototype.call.bind(DataView.prototype.setInt16),
210
+ _147: Function.prototype.call.bind(DataView.prototype.getUint32),
211
+ _148: Function.prototype.call.bind(DataView.prototype.setUint32),
212
+ _149: Function.prototype.call.bind(DataView.prototype.getInt32),
213
+ _150: Function.prototype.call.bind(DataView.prototype.setInt32),
214
+ _155: Function.prototype.call.bind(DataView.prototype.getFloat32),
215
+ _156: Function.prototype.call.bind(DataView.prototype.setFloat32),
216
+ _157: Function.prototype.call.bind(DataView.prototype.getFloat64),
217
+ _158: Function.prototype.call.bind(DataView.prototype.setFloat64),
218
+ _80: (c) =>
219
+ queueMicrotask(() => dartInstance.exports.$invokeCallback(c)),
220
+ _159: s => stringToDartString(stringFromDartString(s).toUpperCase()),
221
+ _160: s => stringToDartString(stringFromDartString(s).toLowerCase()),
222
+ _45: v => stringToDartString(v.toString()),
223
+ _59: s => {
224
+ const jsSource = stringFromDartString(s);
225
+ if (!/^\s*[+-]?(?:Infinity|NaN|(?:\.\d+|\d+(?:\.\d*)?)(?:[eE][+-]?\d+)?)\s*$/.test(jsSource)) {
226
+ return NaN;
227
+ }
228
+ return parseFloat(jsSource);
229
+ },
230
+ _60: () => {
231
+ let stackString = new Error().stack.toString();
232
+ let frames = stackString.split('\n');
233
+ let drop = 2;
234
+ if (frames[0] === 'Error') {
235
+ drop += 1;
236
+ }
237
+ return frames.slice(drop).join('\n');
238
+ },
239
+ _64: () => {
240
+ // On browsers return `globalThis.location.href`
241
+ if (globalThis.location != null) {
242
+ return stringToDartString(globalThis.location.href);
243
+ }
244
+ return null;
245
+ },
246
+ _65: () => {
247
+ return typeof process != undefined &&
248
+ Object.prototype.toString.call(process) == "[object process]" &&
249
+ process.platform == "win32"
250
+ }
251
+ };
252
+
253
+ const baseImports = {
254
+ dart2wasm: dart2wasm,
255
+
256
+
257
+ Math: Math,
258
+ Date: Date,
259
+ Object: Object,
260
+ Array: Array,
261
+ Reflect: Reflect,
262
+ };
263
+ dartInstance = await WebAssembly.instantiate(await modulePromise, {
264
+ ...baseImports,
265
+ ...(await importObjectPromise),
266
+ });
267
+
268
+ return dartInstance;
269
+ }
270
+
271
+ // Call the main function for the instantiated module
272
+ // `moduleInstance` is the instantiated dart2wasm module
273
+ // `args` are any arguments that should be passed into the main function.
274
+ export const invoke = (moduleInstance, ...args) => {
275
+ const dartMain = moduleInstance.exports.$getMain();
276
+ const dartArgs = buildArgsList(args);
277
+ moduleInstance.exports.$invokeMain(dartMain, dartArgs);
278
+ }
279
+
package/dart_fmt.wasm ADDED
Binary file
@@ -0,0 +1,10 @@
1
+ import fs from "node:fs/promises";
2
+ import initAsync from "./dart_fmt.js";
3
+
4
+ const wasm = new URL("./dart_fmt.wasm", import.meta.url);
5
+
6
+ export default function __wbg_init(init = fs.readFile(wasm)) {
7
+ return initAsync(init);
8
+ }
9
+
10
+ export * from "./dart_fmt.js";
@@ -0,0 +1,8 @@
1
+ import initAsync from "./dart_fmt.js";
2
+ import wasm from "./dart_fmt.wasm?url";
3
+
4
+ export default function __wbg_init(input = wasm) {
5
+ return initAsync(input);
6
+ }
7
+
8
+ export * from "./dart_fmt.js";
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@wasm-fmt/dart_fmt",
3
+ "description": "Dart Formatter powered by WASM ported from dart_style",
4
+ "author": "magic-akari <akari.ccino@gmail.com>",
5
+ "version": "0.0.1",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/wasm-fmt/dart_fmt"
10
+ },
11
+ "module": "dart_fmt.js",
12
+ "homepage": "https://github.com/wasm-fmt/dart_fmt",
13
+ "types": "dart_fmt.d.ts",
14
+ "keywords": [
15
+ "wasm",
16
+ "formatter",
17
+ "dart"
18
+ ],
19
+ "main": "dart_fmt.js",
20
+ "type": "module",
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dart_fmt.d.ts",
27
+ "node": "./dart_fmt_node.js",
28
+ "default": "./dart_fmt.js"
29
+ },
30
+ "./vite": {
31
+ "types": "./dart_fmt.d.ts",
32
+ "default": "./dart_fmt_vite.js"
33
+ },
34
+ "./package.json": "./package.json",
35
+ "./*": "./*"
36
+ }
37
+ }