@meritt/microtypo-wasm 0.1.0 → 0.2.0

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/microtypo.js CHANGED
@@ -1,842 +1,379 @@
1
- export const load = (() => {
2
- const VERSION = '0.1.0';
3
- const MAX_ENTRIES = 100_000;
1
+ import { Engine, defaultMaxInputLength, initSync, version } from './glue.js';
4
2
 
5
- class MicroTypoError extends Error {
6
- static code = 'ERR_MICROTYPO';
3
+ const VERSION = '0.2.0';
4
+ const MAX_ENTRIES = 100_000;
7
5
 
8
- constructor(message, options = {}) {
9
- super(message, options.cause ? { cause: options.cause } : undefined);
6
+ class MicroTypoError extends Error {
7
+ static code = 'ERR_MICROTYPO';
10
8
 
11
- this.name = new.target.name;
12
- this.code = new.target.code;
9
+ constructor(message, options = {}) {
10
+ super(message, options.cause ? { cause: options.cause } : undefined);
13
11
 
14
- if (options.details !== undefined) {
15
- this.details = options.details;
16
- }
17
- }
18
- }
12
+ this.name = new.target.name;
13
+ this.code = new.target.code;
19
14
 
20
- class MicroTypoConfigError extends MicroTypoError {
21
- static code = 'ERR_MICROTYPO_CONFIG';
15
+ if (options.details !== undefined) {
16
+ this.details = options.details;
17
+ }
22
18
  }
19
+ }
23
20
 
24
- class MicroTypoInputError extends MicroTypoError {
25
- static code = 'ERR_MICROTYPO_INPUT';
26
- }
21
+ class MicroTypoConfigError extends MicroTypoError {
22
+ static code = 'ERR_MICROTYPO_CONFIG';
23
+ }
27
24
 
28
- class MicroTypoBudgetError extends MicroTypoError {
29
- static code = 'ERR_MICROTYPO_BUDGET';
30
- }
25
+ class MicroTypoInputError extends MicroTypoError {
26
+ static code = 'ERR_MICROTYPO_INPUT';
27
+ }
31
28
 
32
- class MicroTypoVersionError extends MicroTypoError {
33
- static code = 'ERR_MICROTYPO_VERSION';
34
- }
29
+ class MicroTypoBudgetError extends MicroTypoError {
30
+ static code = 'ERR_MICROTYPO_BUDGET';
31
+ }
35
32
 
36
- function capacityError(message, details) {
37
- return new MicroTypoInputError(message, { details: { reason: 'capacity', ...details } });
38
- }
33
+ class MicroTypoVersionError extends MicroTypoError {
34
+ static code = 'ERR_MICROTYPO_VERSION';
35
+ }
39
36
 
40
- const ERRORS = { MicroTypoError, MicroTypoConfigError, MicroTypoInputError, MicroTypoBudgetError };
41
- const UNSAFE_PREFIX_RE = /["<>&\s]/;
37
+ function capacityError(message, details) {
38
+ return new MicroTypoInputError(message, { details: { reason: 'capacity', ...details } });
39
+ }
42
40
 
43
- function lift(error) {
44
- if (error === null || typeof error !== 'object' || error.engine !== true) {
45
- return error;
46
- }
41
+ const ERRORS = { MicroTypoError, MicroTypoConfigError, MicroTypoInputError, MicroTypoBudgetError };
42
+ const UNSAFE_PREFIX_RE = /["<>&\s]/;
47
43
 
48
- const Class = ERRORS[error.name];
44
+ function lift(error) {
45
+ if (error === null || typeof error !== 'object' || error.engine !== true) {
46
+ return error;
47
+ }
49
48
 
50
- if (Class) {
51
- return new Class(error.message, 'details' in error ? { details: error.details } : {});
52
- }
49
+ const Class = ERRORS[error.name];
53
50
 
54
- return error.name === 'TypeError' ? new TypeError(error.message) : new Error(error.message);
51
+ if (Class) {
52
+ return new Class(error.message, 'details' in error ? { details: error.details } : {});
55
53
  }
56
54
 
57
- function toUnits(text) {
58
- const units = new Uint16Array(text.length);
55
+ return error.name === 'TypeError' ? new TypeError(error.message) : new Error(error.message);
56
+ }
59
57
 
60
- for (let i = 0; i < text.length; i++) {
61
- units[i] = text.charCodeAt(i);
62
- }
58
+ function toUnits(text) {
59
+ const units = new Uint16Array(text.length);
63
60
 
64
- return units;
61
+ for (let i = 0; i < text.length; i++) {
62
+ units[i] = text.charCodeAt(i);
65
63
  }
66
64
 
67
- function fromUnits(units) {
68
- let text = '';
65
+ return units;
66
+ }
69
67
 
70
- for (let i = 0; i < units.length; i += 0x2000) {
71
- text += String.fromCharCode.apply(null, units.subarray(i, i + 0x2000));
72
- }
68
+ function fromUnits(units) {
69
+ let text = '';
73
70
 
74
- return text;
71
+ for (let i = 0; i < units.length; i += 0x2000) {
72
+ text += String.fromCharCode.apply(null, units.subarray(i, i + 0x2000));
75
73
  }
76
74
 
77
- const notJson = (value) =>
78
- typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint';
79
-
80
- function toJson(value) {
81
- return JSON.stringify(value, (_, v) =>
82
- typeof v === 'string' ? v.toWellFormed() : notJson(v) ? null : v
75
+ return text;
76
+ }
77
+
78
+ const notJson = (value) =>
79
+ typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint';
80
+
81
+ function toJson(value) {
82
+ return JSON.stringify(value, (_, v) => notJson(v) ? null : v);
83
+ }
84
+
85
+ function checkConfig(config) {
86
+ if (
87
+ config !== undefined &&
88
+ config !== null &&
89
+ (typeof config !== 'object' || Array.isArray(config))
90
+ ) {
91
+ throw new MicroTypoConfigError(
92
+ `invalid config: expected an object, got ${Array.isArray(config) ? 'an array' : typeof config}`,
93
+ { details: { issues: ['config: expected an object'] } }
83
94
  );
84
95
  }
85
-
86
- function checkConfig(config) {
87
- if (
88
- config !== undefined &&
89
- config !== null &&
90
- (typeof config !== 'object' || Array.isArray(config))
91
- ) {
92
- throw new MicroTypoConfigError(
93
- `invalid config: expected an object, got ${Array.isArray(config) ? 'an array' : typeof config}`,
94
- { details: { issues: ['config: expected an object'] } }
95
- );
96
+ }
97
+
98
+ function readProcessOptions(options) {
99
+ const result = {};
100
+ for (const option of ['changes', 'edits', 'trace']) {
101
+ const value = options !== null && typeof options === 'object' && Object.hasOwn(options, option)
102
+ ? options[option] : undefined;
103
+ if (value !== undefined && typeof value !== 'boolean') {
104
+ throw new MicroTypoConfigError(`process() option "${option}" must be a boolean`, {
105
+ details: { option, receivedType: typeof value }
106
+ });
96
107
  }
108
+ result[option] = value === true;
97
109
  }
110
+ return result;
111
+ }
98
112
 
99
- function readProcessOptions(options) {
100
- const changes =
101
- options !== null && typeof options === 'object' && Object.hasOwn(options, 'changes')
102
- ? options.changes
103
- : undefined;
113
+ function freezeGroup(group) {
114
+ return Object.freeze({ ...group, rules: Object.freeze(group.rules.map(Object.freeze)) });
115
+ }
104
116
 
105
- if (changes === undefined) {
106
- return false;
107
- }
117
+ class MicroTypo {
118
+ #engine;
119
+ #processing = false;
108
120
 
109
- if (typeof changes !== 'boolean') {
110
- throw new MicroTypoConfigError('process() option "changes" must be a boolean', {
111
- details: { option: 'changes', receivedType: typeof changes }
112
- });
113
- }
121
+ onCycleLimit = null;
114
122
 
115
- return changes;
116
- }
123
+ constructor(config) {
124
+ checkConfig(config);
117
125
 
118
- function freezeGroup(group) {
119
- return Object.freeze({ ...group, rules: Object.freeze(group.rules.map(Object.freeze)) });
126
+ try {
127
+ this.#engine = new Engine(config == null ? undefined : toJson(config));
128
+ } catch (error) {
129
+ throw lift(error);
130
+ }
120
131
  }
121
132
 
122
- function bind(wasm) {
123
- class MicroTypo {
124
- #engine;
125
- #processing = false;
126
-
127
- onCycleLimit = null;
128
-
129
- constructor(config) {
130
- checkConfig(config);
131
-
132
- try {
133
- this.#engine = new wasm.Engine(config == null ? undefined : toJson(config));
134
- } catch (error) {
135
- throw lift(error);
136
- }
137
- }
133
+ #call(method, args) {
134
+ try {
135
+ this.#engine.call(method, toJson(args));
136
+ } catch (error) {
137
+ throw lift(error);
138
+ }
138
139
 
139
- #call(method, args) {
140
- try {
141
- this.#engine.call(method, toJson(args));
142
- } catch (error) {
143
- throw lift(error);
144
- }
140
+ return this;
141
+ }
145
142
 
146
- return this;
147
- }
143
+ registerRuleGroup(group, options) {
144
+ if (typeof group?.preParse === 'function' || (Array.isArray(group?.rules) && group.rules.some((rule) =>
145
+ typeof rule?.handler === 'function' ||
146
+ typeof rule?.replacement === 'function' ||
147
+ (Array.isArray(rule?.replacement) && rule.replacement.some((value) => typeof value === 'function')) ||
148
+ (Array.isArray(rule?.pattern) ? rule.pattern : [rule?.pattern]).some((pattern) => pattern instanceof RegExp)
149
+ ))) {
150
+ throw new TypeError(
151
+ 'registerRuleGroup: a rule group is JavaScript code, which the wasm engine cannot run'
152
+ );
153
+ }
154
+ return this.#call('registerRuleGroup', options === undefined ? [group] : [group, options]);
155
+ }
148
156
 
149
- registerRuleGroup() {
150
- throw new TypeError(
151
- 'registerRuleGroup: a rule group is JavaScript code, which the wasm engine cannot run'
152
- );
153
- }
157
+ getRuleGroup(name) {
158
+ const json = name ? this.#engine.ruleGroup(toUnits(String(name))) : undefined;
154
159
 
155
- getRuleGroup(name) {
156
- const json = name ? this.#engine.ruleGroup(String(name)) : undefined;
160
+ return json === undefined ? undefined : freezeGroup(JSON.parse(json));
161
+ }
157
162
 
158
- return json === undefined ? undefined : freezeGroup(JSON.parse(json));
159
- }
163
+ listRuleGroups() {
164
+ return Object.freeze(JSON.parse(this.#engine.ruleGroups()).map(freezeGroup));
165
+ }
160
166
 
161
- listRuleGroups() {
162
- return Object.freeze(JSON.parse(this.#engine.ruleGroups()).map(freezeGroup));
163
- }
167
+ addSafeTag(tag) {
168
+ if (typeof tag === 'bigint') {
169
+ JSON.stringify(tag);
170
+ }
164
171
 
165
- addSafeTag(tag) {
166
- if (typeof tag === 'bigint') {
167
- JSON.stringify(tag);
168
- }
172
+ const absent = tag === undefined || typeof tag === 'function' || typeof tag === 'symbol';
169
173
 
170
- const absent = tag === undefined || typeof tag === 'function' || typeof tag === 'symbol';
174
+ return this.#call('addSafeTag', absent ? [] : [tag]);
175
+ }
171
176
 
172
- return this.#call('addSafeTag', absent ? [] : [tag]);
173
- }
177
+ addSafeBlock(spec) {
178
+ let args = spec === undefined ? [] : [notJson(spec) ? 0 : spec];
179
+ let spellError;
174
180
 
175
- addSafeBlock(spec) {
176
- let args = spec === undefined ? [] : [notJson(spec) ? 0 : spec];
177
- let spellError;
178
-
179
- if (spec !== null && typeof spec === 'object') {
180
- const { id, open, close, unsafeRegex } = spec;
181
- const plain =
182
- id == null ||
183
- typeof id === 'string' ||
184
- typeof id === 'boolean' ||
185
- (typeof id === 'number' && Number.isFinite(id));
186
- let spelled = id;
187
-
188
- if (!plain) {
189
- try {
190
- spelled = `${id}`;
191
- } catch (error) {
192
- spelled = undefined;
193
- spellError = { error };
194
- }
195
- }
196
-
197
- args = [{ id: spelled, open, close, unsafeRegex }];
198
- }
181
+ if (spec !== null && typeof spec === 'object') {
182
+ const { id, open, close, unsafeRegex } = spec;
183
+ const plain =
184
+ id == null ||
185
+ typeof id === 'string' ||
186
+ typeof id === 'boolean' ||
187
+ (typeof id === 'number' && Number.isFinite(id));
188
+ let spelled = id;
199
189
 
190
+ if (!plain) {
200
191
  try {
201
- return this.#call('addSafeBlock', args);
192
+ spelled = `${id}`;
202
193
  } catch (error) {
203
- if (
204
- error instanceof MicroTypoConfigError &&
205
- error.message.startsWith("safe block '") &&
206
- error.details &&
207
- spec != null
208
- ) {
209
- if (spellError) {
210
- throw spellError.error;
211
- }
212
-
213
- const { id, open, close } = spec;
214
-
215
- Object.assign(error.details, 'open' in error.details ? { id, open, close } : { id });
216
- }
217
-
218
- throw error;
219
- }
220
- }
221
-
222
- setLayout(layout) {
223
- if (layout !== 'style' && layout !== 'class' && layout !== 'both') {
224
- throw new MicroTypoConfigError(
225
- `layout must be "style", "class", or "both": ${JSON.stringify(layout)}`,
226
- { details: { layout } }
227
- );
194
+ spelled = undefined;
195
+ spellError = { error };
228
196
  }
229
-
230
- return this.#call('setLayout', [layout]);
231
- }
232
-
233
- setPrefix(p) {
234
- const prefix = p === true ? 'mt_' : p || '';
235
- const spelled = `${prefix}`;
236
-
237
- if (UNSAFE_PREFIX_RE.test(spelled)) {
238
- throw new MicroTypoConfigError(
239
- `prefix must not contain a quote, angle bracket, "&", or whitespace: ${JSON.stringify(prefix)}`,
240
- { details: { prefix } }
241
- );
242
- }
243
-
244
- return this.#call('setPrefix', [spelled]);
245
197
  }
246
198
 
247
- applyOptions(options) {
248
- checkConfig(options);
249
-
250
- return this.#call('applyOptions', options === undefined ? [] : [options]);
251
- }
252
-
253
- process(text, options) {
254
- if (typeof text !== 'string') {
255
- throw new MicroTypoInputError(`process() expects string, got ${typeof text}`, {
256
- details: { receivedType: typeof text }
257
- });
258
- }
259
-
260
- const withChanges = readProcessOptions(options);
261
-
262
- if (this.#processing) {
263
- throw new MicroTypoInputError(
264
- 'process() called reentrantly on the same MicroTypo instance; recursive process() calls are not supported',
265
- { details: {} }
266
- );
267
- }
268
-
269
- const hook = typeof this.onCycleLimit === 'function' ? this.onCycleLimit : undefined;
270
- let units;
271
- let failure;
272
-
273
- this.#processing = true;
274
-
275
- try {
276
- try {
277
- units = this.#engine.process(toUnits(text), withChanges);
278
- } catch (error) {
279
- failure = { error: lift(error) };
280
- }
281
-
282
- if (hook) {
283
- for (const [id, n] of this.#engine.takeCycleLimits()) {
284
- hook.call(undefined, id, n);
285
- }
286
- }
287
- } finally {
288
- this.#processing = false;
289
- }
290
-
291
- if (failure) {
292
- throw failure.error;
293
- }
294
-
295
- const result = fromUnits(units);
296
-
297
- if (!withChanges) {
298
- return result;
299
- }
300
-
301
- const flat = this.#engine.takeChanges();
302
- const changes = [];
199
+ args = [{ id: spelled, open, close, unsafeRegex }];
200
+ }
303
201
 
304
- for (let i = 0; i < flat.length; i += 2) {
305
- changes.push([flat[i], flat[i + 1]]);
202
+ try {
203
+ return this.#call('addSafeBlock', args);
204
+ } catch (error) {
205
+ if (
206
+ error instanceof MicroTypoConfigError &&
207
+ error.message.startsWith("safe block '") &&
208
+ error.details &&
209
+ spec != null
210
+ ) {
211
+ if (spellError) {
212
+ throw spellError.error;
306
213
  }
307
214
 
308
- return { text: result, changes };
309
- }
215
+ const { id, open, close } = spec;
310
216
 
311
- free() {
312
- this.#engine.free();
217
+ Object.assign(error.details, 'open' in error.details ? { id, open, close } : { id });
313
218
  }
314
- }
315
219
 
316
- function microtypo(text, options) {
317
- return new MicroTypo(options).process(text);
220
+ throw error;
318
221
  }
319
-
320
- return { MicroTypo, microtypo };
321
222
  }
322
223
 
323
- function glue() {
324
- let wasm_bindgen = (function(exports) {
325
- let script_src;
326
- if (typeof document !== 'undefined' && document.currentScript !== null) {
327
- script_src = new URL(document.currentScript.src, location.href).toString();
328
- }
329
-
330
- class Engine {
331
- __destroy_into_raw() {
332
- const ptr = this.__wbg_ptr;
333
- this.__wbg_ptr = 0;
334
- EngineFinalization.unregister(this);
335
- return ptr;
336
- }
337
- free() {
338
- const ptr = this.__destroy_into_raw();
339
- wasm.__wbg_engine_free(ptr, 0);
340
- }
341
- /**
342
- * @param {string} method
343
- * @param {string} args
344
- */
345
- call(method, args) {
346
- let ptr0, len0, ptr1, len1;
347
- try {
348
- ptr0 = passStringToWasm0(method, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
349
- len0 = WASM_VECTOR_LEN;
350
- ptr1 = passStringToWasm0(args, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
351
- len1 = WASM_VECTOR_LEN;
352
- } catch (e) {
353
- if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); }
354
- if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); }
355
- throw e;
356
- }
357
- const ret = wasm.engine_call(this.__wbg_ptr, ptr0, len0, ptr1, len1);
358
- if (ret[1]) {
359
- throw takeFromExternrefTable0(ret[0]);
360
- }
361
- }
362
- /**
363
- * @param {string | null} [config]
364
- */
365
- constructor(config) {
366
- var ptr0 = isLikeNone(config) ? 0 : passStringToWasm0(config, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
367
- var len0 = WASM_VECTOR_LEN;
368
- const ret = wasm.engine_new(ptr0, len0);
369
- if (ret[2]) {
370
- throw takeFromExternrefTable0(ret[1]);
371
- }
372
- this.__wbg_ptr = ret[0];
373
- EngineFinalization.register(this, this.__wbg_ptr, this);
374
- return this;
375
- }
376
- /**
377
- * @param {Uint16Array | number[]} text
378
- * @param {boolean} with_changes
379
- * @returns {Uint16Array}
380
- */
381
- process(text, with_changes) {
382
- const val2 = +with_changes;
383
- const ptr0 = passArray16ToWasm0(text, wasm.__wbindgen_malloc);
384
- const len0 = WASM_VECTOR_LEN;
385
- const ret = wasm.engine_process(this.__wbg_ptr, ptr0, len0, val2);
386
- if (ret[3]) {
387
- throw takeFromExternrefTable0(ret[2]);
388
- }
389
- var v3 = getArrayU16FromWasm0(ret[0], ret[1]).slice();
390
- wasm.__wbindgen_free(ret[0], ret[1] * 2, 2);
391
- return v3;
392
- }
393
- /**
394
- * @param {string} name
395
- * @returns {string | undefined}
396
- */
397
- ruleGroup(name) {
398
- const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
399
- const len0 = WASM_VECTOR_LEN;
400
- const ret = wasm.engine_ruleGroup(this.__wbg_ptr, ptr0, len0);
401
- let v2;
402
- if (ret[0] !== 0) {
403
- v2 = getStringFromWasm0(ret[0], ret[1]);
404
- wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
405
- }
406
- return v2;
407
- }
408
- /**
409
- * @returns {string}
410
- */
411
- ruleGroups() {
412
- let deferred1_0;
413
- let deferred1_1;
414
- try {
415
- const ret = wasm.engine_ruleGroups(this.__wbg_ptr);
416
- deferred1_0 = ret[0];
417
- deferred1_1 = ret[1];
418
- return getStringFromWasm0(ret[0], ret[1]);
419
- } finally {
420
- wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
421
- }
422
- }
423
- /**
424
- * @returns {Uint32Array}
425
- */
426
- takeChanges() {
427
- const ret = wasm.engine_takeChanges(this.__wbg_ptr);
428
- var v1 = getArrayU32FromWasm0(ret[0], ret[1]).slice();
429
- wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
430
- return v1;
431
- }
432
- /**
433
- * @returns {Array<any>}
434
- */
435
- takeCycleLimits() {
436
- const ret = wasm.engine_takeCycleLimits(this.__wbg_ptr);
437
- return ret;
438
- }
439
- }
440
- if (Symbol.dispose) Engine.prototype[Symbol.dispose] = Engine.prototype.free;
441
- exports.Engine = Engine;
442
-
443
- /**
444
- * @returns {number}
445
- */
446
- function defaultMaxInputLength() {
447
- const ret = wasm.defaultMaxInputLength();
448
- return ret;
449
- }
450
- exports.defaultMaxInputLength = defaultMaxInputLength;
451
-
452
- function start() {
453
- wasm.start();
454
- }
455
- exports.start = start;
456
-
457
- /**
458
- * @returns {string}
459
- */
460
- function version() {
461
- let deferred1_0;
462
- let deferred1_1;
463
- try {
464
- const ret = wasm.version();
465
- deferred1_0 = ret[0];
466
- deferred1_1 = ret[1];
467
- return getStringFromWasm0(ret[0], ret[1]);
468
- } finally {
469
- wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
470
- }
471
- }
472
- exports.version = version;
473
- function __wbg_get_imports() {
474
- const import0 = {
475
- __proto__: null,
476
- __wbg___wbindgen_throw_4c88d8bf264fd984: function(arg0, arg1) {
477
- throw new Error(getStringFromWasm0(arg0, arg1));
478
- },
479
- __wbg_error_3057c4a180e4cd8c: function(arg0, arg1) {
480
- console.error(getStringFromWasm0(arg0, arg1));
481
- },
482
- __wbg_getRandomValues_8b6f1f663e6f188d: function() { return handleError(function (arg0, arg1) {
483
- globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));
484
- }, arguments); },
485
- __wbg_new_37eb45aaf5eeb820: function() {
486
- const ret = new Array();
487
- return ret;
488
- },
489
- __wbg_new_cd4348290afae586: function() {
490
- const ret = new Object();
491
- return ret;
492
- },
493
- __wbg_now_463ac581d2fc7ea3: function() {
494
- const ret = Date.now();
495
- return ret;
496
- },
497
- __wbg_of_e7ea0fcd535c1444: function(arg0, arg1) {
498
- const ret = Array.of(arg0, arg1);
499
- return ret;
500
- },
501
- __wbg_parse_c3f72b5a24f83c01: function() { return handleError(function (arg0, arg1) {
502
- const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
503
- return ret;
504
- }, arguments); },
505
- __wbg_push_c9f4893fc209f768: function(arg0, arg1) {
506
- const ret = arg0.push(arg1);
507
- return ret;
508
- },
509
- __wbg_set_2793479888329cb6: function() { return handleError(function (arg0, arg1, arg2) {
510
- const ret = Reflect.set(arg0, arg1, arg2);
511
- return ret;
512
- }, arguments); },
513
- __wbindgen_generic_0000000000000001: function(arg0) {
514
- // Cast intrinsic for `F64 -> Externref`.
515
- const ret = arg0;
516
- return ret;
517
- },
518
- __wbindgen_generic_0000000000000002: function(arg0, arg1) {
519
- // Cast intrinsic for `Ref(String) -> Externref`.
520
- const ret = getStringFromWasm0(arg0, arg1);
521
- return ret;
522
- },
523
- __wbindgen_init_externref_table: function() {
524
- const table = wasm.__wbindgen_externrefs;
525
- table.set(0, undefined);
526
- table.set(1024, undefined);
527
- table.set(1025, null);
528
- table.set(1026, true);
529
- table.set(1027, false);
530
- },
531
- };
532
- return {
533
- __proto__: null,
534
- "./microtypo_wasm_bg.js": import0,
535
- };
536
- }
537
-
538
- const EngineFinalization = (typeof FinalizationRegistry === 'undefined')
539
- ? { register: () => {}, unregister: () => {} }
540
- : new FinalizationRegistry(ptr => wasm.__wbg_engine_free(ptr, 1));
541
-
542
- function addToExternrefTable0(obj) {
543
- const idx = wasm.__externref_table_alloc();
544
- wasm.__wbindgen_externrefs.set(idx, obj);
545
- return idx;
546
- }
547
-
548
- function getArrayU16FromWasm0(ptr, len) {
549
- ptr = ptr >>> 0;
550
- return getUint16ArrayMemory0().subarray(ptr / 2, ptr / 2 + len);
551
- }
552
-
553
- function getArrayU32FromWasm0(ptr, len) {
554
- ptr = ptr >>> 0;
555
- return getUint32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len);
556
- }
557
-
558
- function getArrayU8FromWasm0(ptr, len) {
559
- ptr = ptr >>> 0;
560
- return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
561
- }
562
-
563
- function getStringFromWasm0(ptr, len) {
564
- ptr = ptr >>> 0;
565
- return decodeText(getUint8ArrayMemory0().subarray(ptr, ptr + len));
566
- }
567
-
568
- let cachedUint16ArrayMemory0 = null;
569
- function getUint16ArrayMemory0() {
570
- if (cachedUint16ArrayMemory0 === null || cachedUint16ArrayMemory0.byteLength === 0) {
571
- cachedUint16ArrayMemory0 = new Uint16Array(wasm.memory.buffer);
572
- }
573
- return cachedUint16ArrayMemory0;
574
- }
575
-
576
- let cachedUint32ArrayMemory0 = null;
577
- function getUint32ArrayMemory0() {
578
- if (cachedUint32ArrayMemory0 === null || cachedUint32ArrayMemory0.byteLength === 0) {
579
- cachedUint32ArrayMemory0 = new Uint32Array(wasm.memory.buffer);
580
- }
581
- return cachedUint32ArrayMemory0;
582
- }
583
-
584
- let cachedUint8ArrayMemory0 = null;
585
- function getUint8ArrayMemory0() {
586
- if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
587
- cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
588
- }
589
- return cachedUint8ArrayMemory0;
224
+ setLayout(layout) {
225
+ if (layout !== 'style' && layout !== 'class' && layout !== 'both') {
226
+ throw new MicroTypoConfigError(
227
+ `layout must be "style", "class", or "both": ${JSON.stringify(layout)}`,
228
+ { details: { layout } }
229
+ );
590
230
  }
591
231
 
592
- function handleError(f, args) {
593
- try {
594
- return f.apply(this, args);
595
- } catch (e) {
596
- const idx = addToExternrefTable0(e);
597
- wasm.__wbindgen_exn_store(idx);
598
- }
599
- }
232
+ return this.#call('setLayout', [layout]);
233
+ }
600
234
 
601
- function isLikeNone(x) {
602
- return x === undefined || x === null;
603
- }
235
+ setPrefix(p) {
236
+ const prefix = p === true ? 'mt_' : p || '';
237
+ const spelled = `${prefix}`;
604
238
 
605
- function passArray16ToWasm0(arg, malloc) {
606
- const ptr = malloc(arg.length * 2, 2) >>> 0;
607
- getUint16ArrayMemory0().set(arg, ptr / 2);
608
- WASM_VECTOR_LEN = arg.length;
609
- return ptr;
239
+ if (UNSAFE_PREFIX_RE.test(spelled)) {
240
+ throw new MicroTypoConfigError(
241
+ `prefix must not contain a quote, angle bracket, "&", or whitespace: ${JSON.stringify(prefix)}`,
242
+ { details: { prefix } }
243
+ );
610
244
  }
611
245
 
612
- function passStringToWasm0(arg, malloc, realloc) {
613
- if (realloc === undefined) {
614
- const buf = cachedTextEncoder.encode(arg);
615
- const ptr = malloc(buf.length, 1) >>> 0;
616
- getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
617
- WASM_VECTOR_LEN = buf.length;
618
- return ptr;
619
- }
620
-
621
- let len = arg.length;
622
- let ptr = malloc(len, 1) >>> 0;
623
-
624
- const mem = getUint8ArrayMemory0();
246
+ return this.#call('setPrefix', [spelled]);
247
+ }
625
248
 
626
- let offset = 0;
249
+ applyOptions(options) {
250
+ checkConfig(options);
627
251
 
628
- for (; offset < len; offset++) {
629
- const code = arg.charCodeAt(offset);
630
- if (code > 0x7F) break;
631
- mem[ptr + offset] = code;
632
- }
633
- if (offset !== len) {
634
- if (offset !== 0) {
635
- arg = arg.slice(offset);
636
- }
637
- ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
638
- const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
639
- const ret = cachedTextEncoder.encodeInto(arg, view);
640
-
641
- offset += ret.written;
642
- ptr = realloc(ptr, len, offset, 1) >>> 0;
643
- }
252
+ return this.#call('applyOptions', options === undefined ? [] : [options]);
253
+ }
644
254
 
645
- WASM_VECTOR_LEN = offset;
646
- return ptr;
255
+ process(text, options) {
256
+ if (typeof text !== 'string') {
257
+ throw new MicroTypoInputError(`process() expects string, got ${typeof text}`, {
258
+ details: { receivedType: typeof text }
259
+ });
647
260
  }
648
261
 
649
- function takeFromExternrefTable0(idx) {
650
- const value = wasm.__wbindgen_externrefs.get(idx);
651
- wasm.__externref_table_dealloc(idx);
652
- return value;
653
- }
262
+ const diagnostics = readProcessOptions(options);
654
263
 
655
- let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
656
- cachedTextDecoder.decode();
657
- function decodeText(bytes) {
658
- return cachedTextDecoder.decode(bytes);
264
+ if (this.#processing) {
265
+ throw new MicroTypoInputError(
266
+ 'process() called reentrantly on the same MicroTypo instance; recursive process() calls are not supported',
267
+ { details: {} }
268
+ );
659
269
  }
660
270
 
661
- const cachedTextEncoder = new TextEncoder();
662
-
663
- if (!('encodeInto' in cachedTextEncoder)) {
664
- cachedTextEncoder.encodeInto = function (arg, view) {
665
- const buf = cachedTextEncoder.encode(arg);
666
- view.set(buf);
667
- return {
668
- read: arg.length,
669
- written: buf.length
670
- };
671
- };
672
- }
271
+ const hook = typeof this.onCycleLimit === 'function' ? this.onCycleLimit : undefined;
272
+ let units;
273
+ let failure;
673
274
 
674
- let WASM_VECTOR_LEN = 0;
675
-
676
- let wasmModule, wasmInstance, wasm;
677
- function __wbg_finalize_init(instance, module) {
678
- wasmInstance = instance;
679
- wasm = instance.exports;
680
- wasmModule = module;
681
- cachedUint16ArrayMemory0 = null;
682
- cachedUint32ArrayMemory0 = null;
683
- cachedUint8ArrayMemory0 = null;
684
- wasm.__wbindgen_start();
685
- return wasm;
686
- }
275
+ this.#processing = true;
687
276
 
688
- async function __wbg_load(module, imports) {
689
- if (typeof Response === 'function' && module instanceof Response) {
690
- if (!module.ok) {
691
- throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
692
- }
693
-
694
- if (typeof WebAssembly.instantiateStreaming === 'function') {
695
- try {
696
- return await WebAssembly.instantiateStreaming(module, imports);
697
- } catch (e) {
698
- const validResponse = expectedResponseType(module.type);
699
-
700
- if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
701
- 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);
702
-
703
- } else { throw e; }
704
- }
705
- }
706
-
707
- const bytes = await module.arrayBuffer();
708
- return await WebAssembly.instantiate(bytes, imports);
709
- } else {
710
- const instance = await WebAssembly.instantiate(module, imports);
711
-
712
- if (instance instanceof WebAssembly.Instance) {
713
- return { instance, module };
714
- } else {
715
- return instance;
716
- }
717
- }
277
+ try {
278
+ try {
279
+ this.#engine.setCycleHook(hook !== undefined);
280
+ units = this.#engine.process(toUnits(text), diagnostics.changes, diagnostics.edits, diagnostics.trace);
281
+ } catch (error) {
282
+ failure = { error: lift(error) };
283
+ }
718
284
 
719
- function expectedResponseType(type) {
720
- switch (type) {
721
- case 'basic': case 'cors': case 'default': return true;
722
- }
723
- return false;
285
+ if (hook) {
286
+ for (const [id, n] of this.#engine.takeCycleLimits()) {
287
+ hook.call(undefined, id, n);
724
288
  }
289
+ }
290
+ } finally {
291
+ this.#processing = false;
725
292
  }
726
293
 
727
- function initSync(module) {
728
- if (wasm !== undefined) return wasm;
729
-
730
-
731
- if (module !== undefined) {
732
- if (Object.getPrototypeOf(module) === Object.prototype) {
733
- ({module} = module)
734
- } else {
735
- console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
736
- }
737
- }
738
-
739
- const imports = __wbg_get_imports();
740
- if (!(module instanceof WebAssembly.Module)) {
741
- module = new WebAssembly.Module(module);
742
- }
743
- const instance = new WebAssembly.Instance(module, imports);
744
- return __wbg_finalize_init(instance, module);
294
+ if (failure) {
295
+ throw failure.error;
745
296
  }
746
297
 
747
- let __wbg_init_promise;
748
- async function __wbg_init(module_or_path) {
749
- if (wasm !== undefined) return wasm;
750
- if (__wbg_init_promise === undefined) {
751
- __wbg_init_promise = __wbg_init_once(module_or_path);
752
- __wbg_init_promise.catch(() => { __wbg_init_promise = undefined; });
753
- }
754
- return __wbg_init_promise;
298
+ if (diagnostics.changes || diagnostics.edits || diagnostics.trace) {
299
+ return JSON.parse(this.#engine.takeDiagnostics());
755
300
  }
301
+ return fromUnits(units);
302
+ }
756
303
 
757
- async function __wbg_init_once(module_or_path) {
758
-
759
- if (module_or_path !== undefined) {
760
- if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
761
- ({module_or_path} = module_or_path)
762
- } else {
763
- console.warn('using deprecated parameters for the initialization function; pass a single object instead')
764
- }
765
- }
766
-
767
- if (module_or_path === undefined && script_src !== undefined) {
768
- module_or_path = script_src.replace(/\.js$/, "_bg.wasm");
769
- }
770
- const imports = __wbg_get_imports();
771
-
772
- if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
773
- module_or_path = fetch(module_or_path);
774
- }
304
+ free() {
305
+ this.#engine.free();
306
+ }
307
+ }
775
308
 
776
- const { instance, module } = await __wbg_load(await module_or_path, imports);
309
+ function microtypo(text, options) {
310
+ return new MicroTypo(options).process(text);
311
+ }
777
312
 
778
- return __wbg_finalize_init(instance, module);
313
+ async function compile(source) {
314
+ if (source instanceof WebAssembly.Module) return source;
315
+ if (typeof source === 'string') source = new URL(source, import.meta.url);
316
+ if (source instanceof URL) {
317
+ if (source.protocol === 'file:') {
318
+ const { readFile } = await import('node:fs/promises');
319
+ return WebAssembly.compile(await readFile(source));
779
320
  }
780
-
781
- return Object.assign(__wbg_init, { initSync }, exports);
782
- })({ __proto__: null });
783
- return wasm_bindgen;
321
+ source = fetch(source);
784
322
  }
785
-
786
- async function compile(source) {
787
- if (source instanceof WebAssembly.Module) return source;
788
- if (typeof source === 'string') source = new URL(source, import.meta.url);
789
- if (source instanceof URL) {
790
- if (source.protocol === 'file:') {
791
- const { readFile } = await import('node:fs/promises');
792
- return WebAssembly.compile(await readFile(source));
793
- }
794
- source = fetch(source);
795
- }
796
- if (source instanceof Promise || (typeof Response === 'function' && source instanceof Response)) {
797
- return WebAssembly.compileStreaming(source);
798
- }
799
- return WebAssembly.compile(source);
323
+ if (source instanceof Promise || source instanceof Response) {
324
+ return WebAssembly.compileStreaming(source);
800
325
  }
326
+ return WebAssembly.compile(source);
327
+ }
801
328
 
802
- function mismatch(found) {
803
- return new MicroTypoVersionError(
804
- `microtypo.wasm is ${found === undefined ? 'from another build' : `version ${found}`}, microtypo.js is version ${VERSION}`,
805
- { details: { expected: VERSION, found } }
806
- );
807
- }
329
+ function mismatch(found) {
330
+ return new MicroTypoVersionError(
331
+ `microtypo.wasm is ${found === undefined ? 'from another build' : `version ${found}`}, microtypo.js is version ${VERSION}`,
332
+ { details: { expected: VERSION, found } }
333
+ );
334
+ }
808
335
 
809
- return async function load(source = new URL('./microtypo.wasm', import.meta.url)) {
810
- const module = await compile(source);
811
- const wasm = glue();
336
+ async function instantiate(source) {
337
+ const module = await compile(source);
812
338
 
813
- if (!WebAssembly.Module.exports(module).some(({ name }) => name === 'version')) {
814
- throw mismatch(undefined);
815
- }
339
+ if (!WebAssembly.Module.exports(module).some(({ name }) => name === 'version')) {
340
+ throw mismatch(undefined);
341
+ }
816
342
 
817
- try {
818
- wasm.initSync({ module });
819
- } catch (error) {
820
- throw error instanceof WebAssembly.LinkError ? mismatch(undefined) : error;
821
- }
343
+ try {
344
+ initSync({ module });
345
+ } catch (error) {
346
+ throw error instanceof WebAssembly.LinkError ? mismatch(undefined) : error;
347
+ }
822
348
 
823
- const found = wasm.version();
349
+ const found = version();
824
350
 
825
- if (found !== VERSION) {
826
- throw mismatch(found);
827
- }
351
+ if (found !== VERSION) {
352
+ throw mismatch(found);
353
+ }
828
354
 
829
- return Object.freeze({
830
- ...bind(wasm),
831
- VERSION,
832
- DEFAULT_MAX_INPUT_LENGTH: wasm.defaultMaxInputLength(),
833
- MAX_ENTRIES,
834
- capacityError,
835
- MicroTypoError,
836
- MicroTypoConfigError,
837
- MicroTypoInputError,
838
- MicroTypoBudgetError,
839
- MicroTypoVersionError
840
- });
841
- };
842
- })();
355
+ return Object.freeze({
356
+ MicroTypo,
357
+ microtypo,
358
+ VERSION,
359
+ DEFAULT_MAX_INPUT_LENGTH: defaultMaxInputLength(),
360
+ MAX_ENTRIES,
361
+ capacityError,
362
+ MicroTypoError,
363
+ MicroTypoConfigError,
364
+ MicroTypoInputError,
365
+ MicroTypoBudgetError,
366
+ MicroTypoVersionError
367
+ });
368
+ }
369
+
370
+ let loading;
371
+
372
+ export function load(source = new URL('./microtypo.wasm', import.meta.url)) {
373
+ loading ??= instantiate(source).catch((error) => {
374
+ loading = undefined;
375
+ throw error;
376
+ });
377
+
378
+ return loading;
379
+ }