@meritt/tokenmeter-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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meritt/tokenmeter-wasm",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Counts the tokens of text in o200k_base with tiktoken's algorithm and splits it into token groups on grapheme boundaries, in WebAssembly",
5
5
  "keywords": [
6
6
  "gpt",
@@ -25,7 +25,7 @@
25
25
  },
26
26
  "type": "module",
27
27
  "engines": {
28
- "node": ">=26.13.0"
28
+ "node": ">=26.13.1"
29
29
  },
30
30
  "sideEffects": false,
31
31
  "exports": {
@@ -42,12 +42,12 @@
42
42
  "devEngines": {
43
43
  "packageManager": {
44
44
  "name": "pnpm",
45
- "version": "^12.15.0",
45
+ "version": "12.25.1",
46
46
  "onFail": "download"
47
47
  },
48
48
  "runtime": {
49
49
  "name": "node",
50
- "version": "^26.13.0",
50
+ "version": "26.14.0",
51
51
  "onFail": "error"
52
52
  }
53
53
  }
package/tokenmeter.js CHANGED
@@ -1,8 +1,9 @@
1
- const VERSION = '0.1.0';
2
- const STATUS = ['ok', 'invalid_utf8', 'invalid_argument', 'internal'];
3
- const OK = 0;
4
- // tokenmeter_groups on wasm32: status, tokens, truncated, then groups as (pointer, length).
5
- const SPLIT_SIZE = 20;
1
+ const VERSION = '0.2.0';
2
+ const STATUS = ['ok', 'invalid_utf8', 'invalid_argument', 'internal', 'input_too_large', 'tokenization'];
3
+ const MAX_BYTES = 1048576;
4
+ const GROUPS = { size: 20, status: 0, tokens: 4, truncated: 8, pairs: 12, length: 16 };
5
+ const encoder = new TextEncoder();
6
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
6
7
 
7
8
  export class TokenMeterError extends Error {
8
9
  constructor(code) {
@@ -12,102 +13,139 @@ export class TokenMeterError extends Error {
12
13
  }
13
14
  }
14
15
 
15
- export async function load(source = new URL('./tokenmeter.wasm', import.meta.url)) {
16
- const module = await compile(source);
17
- const { exports } = await WebAssembly.instantiate(module, {});
18
- return new TokenMeter(exports);
19
- }
20
-
21
- async function compile(source) {
22
- if (source instanceof WebAssembly.Module) return source;
23
- if (typeof source === 'string') source = new URL(source, import.meta.url);
24
- if (source instanceof URL) {
25
- if (source.protocol === 'file:') {
26
- const { readFile } = await import('node:fs/promises');
27
- return WebAssembly.compile(await readFile(source));
28
- }
29
- source = fetch(source);
16
+ export async function load(module) {
17
+ let exports;
18
+ try {
19
+ exports = WebAssembly.Module.exports(module);
20
+ } catch {
21
+ throw new TokenMeterError('invalid_argument');
22
+ }
23
+ if (!exports.some(item => item.name === 'tokenmeter_version' && item.kind === 'function')) {
24
+ throw new TokenMeterError('version');
30
25
  }
31
- if (source instanceof Promise || source instanceof Response) {
32
- return WebAssembly.compileStreaming(source);
26
+ let instance;
27
+ try {
28
+ instance = await WebAssembly.instantiate(module, {});
29
+ } catch {
30
+ throw new TokenMeterError('internal');
33
31
  }
34
- return WebAssembly.compile(source);
32
+ return new TokenMeter(instance.exports);
35
33
  }
36
34
 
37
- const encoder = new TextEncoder();
38
- const decoder = new TextDecoder('utf-8', { fatal: true });
39
-
40
35
  function encode(text) {
41
36
  if (typeof text !== 'string') throw new TokenMeterError('invalid_argument');
42
- // A lone surrogate has no UTF-8 form; TextEncoder would count U+FFFD instead.
37
+ if (text.length > MAX_BYTES) throw new TokenMeterError('input_too_large');
43
38
  if (!text.isWellFormed()) throw new TokenMeterError('invalid_utf8');
44
- return encoder.encode(text);
39
+ const bytes = encoder.encode(text);
40
+ if (bytes.length > MAX_BYTES) throw new TokenMeterError('input_too_large');
41
+ return bytes;
45
42
  }
46
43
 
47
44
  class TokenMeter {
48
- #x;
45
+ #exports;
49
46
 
50
47
  constructor(exports) {
51
- this.#x = exports;
52
- const version = typeof exports.tokenmeter_version === 'function' ? this.#cString(exports.tokenmeter_version()) : '';
53
- if (version !== VERSION) throw new TokenMeterError('version');
54
- this.version = VERSION;
55
- this.encoding = this.#cString(exports.tokenmeter_encoding());
56
- exports.tokenmeter_prepare();
48
+ this.#exports = exports;
49
+ this.#run(() => {
50
+ if (this.#cString('tokenmeter_version') !== VERSION) throw new TokenMeterError('version');
51
+ this.version = VERSION;
52
+ this.encoding = this.#cString('tokenmeter_encoding');
53
+ this.#check(this.#call('tokenmeter_prepare'));
54
+ });
57
55
  }
58
56
 
59
57
  count(text) {
60
- const tokens = this.#with(encode(text), (p, n) => this.#x.tokenmeter_count(p, n) >>> 0);
61
- if (tokens === 0xffffffff) throw new TokenMeterError('invalid_utf8');
62
- return tokens;
58
+ return this.#run(() => this.#withText(text, 4, (bytes, input, out) => {
59
+ this.#check(this.#call('tokenmeter_count', input, bytes.length, out));
60
+ return new DataView(this.#exports.memory.buffer, out, 4).getUint32(0, true);
61
+ }));
63
62
  }
64
63
 
65
64
  split(text, limit = 200) {
66
- if (!Number.isSafeInteger(limit) || limit < 0) throw new TokenMeterError('invalid_argument');
65
+ return this.#run(() => {
66
+ if (!Number.isInteger(limit) || limit < 0 || limit > 0xffffffff) throw new TokenMeterError('invalid_argument');
67
+ return this.#withText(text, GROUPS.size, (bytes, input, out) => {
68
+ this.#call('tokenmeter_split', input, bytes.length, limit, out);
69
+ try {
70
+ return this.#groups(bytes, out);
71
+ } finally {
72
+ if (this.#exports) this.#call('tokenmeter_split_free', out);
73
+ }
74
+ });
75
+ });
76
+ }
77
+
78
+ #groups(bytes, out) {
79
+ const buffer = this.#exports.memory.buffer;
80
+ const view = new DataView(buffer, out, GROUPS.size);
81
+ this.#check(view.getUint32(GROUPS.status, true));
82
+ const pairs = new Uint32Array(buffer, view.getUint32(GROUPS.pairs, true), view.getUint32(GROUPS.length, true) * 2);
83
+ const groups = [];
84
+ let start = 0;
85
+ for (let i = 0; i < pairs.length; i += 2) {
86
+ groups.push({ text: decoder.decode(bytes.subarray(start, pairs[i])), tokens: pairs[i + 1] });
87
+ start = pairs[i];
88
+ }
89
+ return {
90
+ tokens: view.getUint32(GROUPS.tokens, true),
91
+ groups,
92
+ truncated: view.getUint32(GROUPS.truncated, true) !== 0,
93
+ };
94
+ }
95
+
96
+ #withText(text, size, use) {
67
97
  const bytes = encode(text);
68
- const x = this.#x;
69
- const out = x.tokenmeter_alloc(SPLIT_SIZE);
70
- if (out === 0) throw new TokenMeterError('internal');
98
+ return this.#buffer(size, out => this.#buffer(bytes.length, input => {
99
+ new Uint8Array(this.#exports.memory.buffer, input, bytes.length).set(bytes);
100
+ return use(bytes, input, out);
101
+ }));
102
+ }
103
+
104
+ #buffer(size, use) {
105
+ const p = this.#call('tokenmeter_alloc', size) >>> 0;
106
+ if (!p && size) this.#fatal();
71
107
  try {
72
- this.#with(bytes, (p, n) => x.tokenmeter_split(p, n, limit, out));
73
- // Read only after the call: memory may have grown and detached old views.
74
- const view = new DataView(x.memory.buffer, out, SPLIT_SIZE);
75
- const status = view.getUint32(0, true);
76
- if (status !== OK) {
77
- throw new TokenMeterError(STATUS[status] ?? 'internal');
78
- }
79
- const pairs = new Uint32Array(x.memory.buffer, view.getUint32(12, true), view.getUint32(16, true) * 2);
80
- const groups = [];
81
- let start = 0;
82
- for (let i = 0; i < pairs.length; i += 2) {
83
- groups.push({ text: decoder.decode(bytes.subarray(start, pairs[i])), tokens: pairs[i + 1] });
84
- start = pairs[i];
85
- }
86
- const result = { tokens: view.getUint32(4, true), groups, truncated: view.getUint32(8, true) !== 0 };
87
- x.tokenmeter_split_free(out);
88
- return result;
108
+ return use(p);
89
109
  } finally {
90
- x.tokenmeter_dealloc(out, SPLIT_SIZE);
110
+ if (this.#exports && p) this.#call('tokenmeter_dealloc', p, size);
91
111
  }
92
112
  }
93
113
 
94
- #with(bytes, use) {
95
- const x = this.#x;
96
- const n = bytes.length;
97
- const p = x.tokenmeter_alloc(n);
98
- if (n > 0 && p === 0) throw new TokenMeterError('invalid_argument');
114
+ #cString(name) {
115
+ const p = this.#call(name) >>> 0;
116
+ const bytes = new Uint8Array(this.#exports.memory.buffer);
117
+ const end = bytes.indexOf(0, p);
118
+ if (end < 0) this.#fatal();
119
+ return decoder.decode(bytes.subarray(p, end));
120
+ }
121
+
122
+ #check(status) {
123
+ if (status === 0) return;
124
+ const code = STATUS[status];
125
+ if (!code || code === 'internal') this.#fatal();
126
+ throw new TokenMeterError(code);
127
+ }
128
+
129
+ #call(name, ...args) {
99
130
  try {
100
- new Uint8Array(x.memory.buffer, p, n).set(bytes);
101
- return use(p, n);
102
- } finally {
103
- x.tokenmeter_dealloc(p, n);
131
+ return this.#exports[name](...args);
132
+ } catch {
133
+ this.#fatal();
134
+ }
135
+ }
136
+
137
+ #run(use) {
138
+ if (!this.#exports) throw new TokenMeterError('internal');
139
+ try {
140
+ return use();
141
+ } catch (error) {
142
+ if (error instanceof TokenMeterError) throw error;
143
+ this.#fatal();
104
144
  }
105
145
  }
106
146
 
107
- #cString(p) {
108
- const memory = new Uint8Array(this.#x.memory.buffer);
109
- let end = p;
110
- while (memory[end] !== 0) end++;
111
- return decoder.decode(memory.subarray(p, end));
147
+ #fatal() {
148
+ this.#exports = null;
149
+ throw new TokenMeterError('internal');
112
150
  }
113
151
  }
package/tokenmeter.wasm CHANGED
Binary file