@mailwoman/sentencepiece-wasm 10.1.0 → 10.2.4-beta.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/index.js ADDED
@@ -0,0 +1 @@
1
+ export const diagnostic = "10.2.4-beta.0"
package/package.json CHANGED
@@ -1,35 +1,9 @@
1
1
  {
2
- "name": "@mailwoman/sentencepiece-wasm",
3
- "version": "10.1.0",
4
- "description": "google/sentencepiece v0.2.2 compiled to WASM with a native-offsets binding — the tokenizer core for @mailwoman/neural. Single-file ESM (wasm embedded), no runtime deps; per-piece byte offsets come from SentencePiece itself instead of TS-side reconstruction.",
5
- "license": "AGPL-3.0-only OR LicenseRef-Commercial",
6
- "repository": {
7
- "type": "git",
8
- "url": "https://github.com/sister-software/mailwoman.git",
9
- "directory": "packages/sentencepiece-wasm"
10
- },
11
- "files": [
12
- "sentencepiece.mjs",
13
- "index.d.ts",
14
- "binding.cpp",
15
- "build.sh",
16
- "!test/**"
17
- ],
18
- "type": "module",
19
- "exports": {
20
- "./package.json": "./package.json",
21
- ".": {
22
- "types": "./index.d.ts",
23
- "default": "./sentencepiece.mjs"
24
- }
25
- },
26
- "publishConfig": {
27
- "exports": {
28
- "./package.json": "./package.json",
29
- ".": {
30
- "types": "./index.d.ts",
31
- "default": "./sentencepiece.mjs"
32
- }
33
- }
34
- }
35
- }
2
+ "name": "@mailwoman/sentencepiece-wasm",
3
+ "version": "10.2.4-beta.0",
4
+ "description": "diagnostic publish: one JavaScript file under the beta tag",
5
+ "license": "AGPL-3.0-only",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "files": ["index.js"]
9
+ }
package/binding.cpp DELETED
@@ -1,119 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Embind wrapper for google/sentencepiece v0.2.2 — the mailwoman tokenizer's WASM core (task #26,
7
- * the SP 0.2.2 native-offsets change from the 2026-07-30 Latin tokenizer survey).
8
- *
9
- * Why this exists: the previous runtime (`@sctg/sentencepiece-js`, an emscripten build of an older
10
- * sentencepiece) exposed pieces + ids but never bound the offset-carrying proto API, forcing
11
- * `neural/tokenizer.ts` to RECONSTRUCT char offsets by re-walking the input — the source of the
12
- * byte-fallback desync class and the documented surrogate-pair deferral. SentencePiece itself has
13
- * always known the answer: `Encode(text, &SentencePieceText)` yields per-piece `begin`/`end` BYTE
14
- * offsets with the documented invariant `text.substr(begin, end - begin) == surface` and
15
- * contiguity between consecutive pieces. This wrapper binds exactly that.
16
- *
17
- * API surface (deliberately minimal — one class, three methods):
18
- *
19
- * - `loadFromSerializedProto(bytes)` — load a `tokenizer.model` from bytes; returns "" on success,
20
- * the status message on failure (no exceptions across the WASM boundary).
21
- * - `encodeWithOffsets(text)` — returns { pieces: string[], ids: Int32Array-like, begins, ends }
22
- * where begins/ends are UTF-8 BYTE offsets into the input. The TS layer owns the byte→UTF-16
23
- * conversion (exact, via a code-point walk — see neural/tokenizer.ts).
24
- * - `decodeIDs(ids)` — detokenize back to a string.
25
- *
26
- * Build: `./build.sh` (fetches sentencepiece at the pinned tag, emcmake+emmake, links this file
27
- * with embind, emits the committed single-file ESM artifact `sentencepiece.mjs`).
28
- */
29
-
30
- #include <emscripten/bind.h>
31
- #include <emscripten/val.h>
32
-
33
- #include <cstdint>
34
- #include <string>
35
- #include <vector>
36
-
37
- #include "builtin_pb/sentencepiece.pb.h"
38
- #include "sentencepiece_processor.h"
39
-
40
- namespace {
41
-
42
- class SentencePieceWASM {
43
- public:
44
- /**
45
- * Load a tokenizer.model from its serialized-proto bytes (a JS Uint8Array). Returns "" on
46
- * success, the status message on failure — errors cross the WASM boundary as values, never
47
- * exceptions. NOTE the parameter is emscripten::val, NOT std::string: embind marshals JS
48
- * strings to std::string as UTF-8, which corrupts arbitrary binary — the exact trap that made
49
- * the first smoke fail to parse the model proto.
50
- */
51
- std::string loadFromSerializedProto(const emscripten::val& data) {
52
- const std::vector<uint8_t> bytes = emscripten::convertJSArrayToNumberVector<uint8_t>(data);
53
- const auto status = processor_.LoadFromSerializedProto(
54
- absl::string_view(reinterpret_cast<const char*>(bytes.data()), bytes.size()));
55
- return status.ok() ? std::string() : std::string(status.message());
56
- }
57
-
58
- /**
59
- * Encode with native offsets. Returns a JS object:
60
- * { pieces: string[], ids: number[], begins: number[], ends: number[] } — begins/ends are byte
61
- * offsets into the UTF-8 encoding of `text` (the exact bytes embind marshaled in).
62
- */
63
- emscripten::val encodeWithOffsets(const std::string& text) const {
64
- sentencepiece::SentencePieceText spt;
65
- const auto status = processor_.Encode(text, &spt);
66
-
67
- emscripten::val result = emscripten::val::object();
68
-
69
- if (!status.ok()) {
70
- result.set("error", std::string(status.message()));
71
- return result;
72
- }
73
-
74
- const int n = spt.pieces_size();
75
- emscripten::val pieces = emscripten::val::array();
76
- emscripten::val ids = emscripten::val::array();
77
- emscripten::val begins = emscripten::val::array();
78
- emscripten::val ends = emscripten::val::array();
79
-
80
- for (int i = 0; i < n; i++) {
81
- const auto& p = spt.pieces(i);
82
- pieces.set(i, p.piece());
83
- ids.set(i, p.id());
84
- begins.set(i, p.begin());
85
- ends.set(i, p.end());
86
- }
87
-
88
- result.set("pieces", pieces);
89
- result.set("ids", ids);
90
- result.set("begins", begins);
91
- result.set("ends", ends);
92
- return result;
93
- }
94
-
95
- /**
96
- * Detokenize ids back to text. Invalid ids surface as the empty string plus the error field on
97
- * the wrapper's interface being violated upstream — the TS layer validates lengths.
98
- */
99
- std::string decodeIDs(const std::vector<int>& ids) const {
100
- std::string out;
101
- const auto status = processor_.Decode(ids, &out);
102
- return status.ok() ? out : std::string();
103
- }
104
-
105
- private:
106
- sentencepiece::SentencePieceProcessor processor_;
107
- };
108
-
109
- } // namespace
110
-
111
- EMSCRIPTEN_BINDINGS(sentencepiece_wasm) {
112
- emscripten::register_vector<int>("IntVector");
113
-
114
- emscripten::class_<SentencePieceWASM>("SentencePieceProcessor")
115
- .constructor<>()
116
- .function("loadFromSerializedProto", &SentencePieceWASM::loadFromSerializedProto)
117
- .function("encodeWithOffsets", &SentencePieceWASM::encodeWithOffsets)
118
- .function("decodeIDs", &SentencePieceWASM::decodeIDs);
119
- }
package/build.sh DELETED
@@ -1,92 +0,0 @@
1
- #!/usr/bin/env bash
2
- #
3
- # @copyright Sister Software
4
- # @license AGPL-3.0
5
- # @author Teffen Ellis, et al.
6
- #
7
- # Build the committed `sentencepiece.mjs` artifact: google/sentencepiece at the pinned tag below,
8
- # compiled to wasm with emscripten and linked against binding.cpp (the embind wrapper exposing
9
- # native per-piece byte offsets — task #26).
10
- #
11
- # The artifact is committed (like core/data's reference blobs): consumers import
12
- # `@mailwoman/sentencepiece-wasm` as a plain dependency and never need emscripten. Re-run this
13
- # script only to bump the sentencepiece tag or change the binding; commit the regenerated .mjs in
14
- # the same PR and note the tag bump in the header of index.d.ts.
15
- #
16
- # Prereqs: emsdk activated (`source ~/tools/emsdk/emsdk_env.sh`), cmake, git. The sentencepiece
17
- # checkout is cached outside the repo (a toolchain input, not a repo artifact).
18
- #
19
- # Single-file output on purpose: -sSINGLE_FILE=1 embeds the wasm as base64 in the .mjs, matching
20
- # how the previous runtime (@sctg/sentencepiece-js) shipped — no separate .wasm delivery path to
21
- # thread through the neural web loader, the docs demo, or the drop-in APIs. The size cost (~4/3× the wasm) is
22
- # accepted; the artifact is fetched once and cached.
23
-
24
- set -euo pipefail
25
-
26
- # The pin. corpus-python trains with `sentencepiece>=0.2.2` — the runtime must tokenize
27
- # byte-identically to the trainer, so the tags travel together (see project-tokenizer-mismatch).
28
- SP_TAG="v0.2.2"
29
-
30
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
31
- SP_SRC="${SENTENCEPIECE_SRC:-$HOME/tools/sentencepiece}"
32
- BUILD_DIR="$SP_SRC/build-wasm"
33
-
34
- command -v emcc > /dev/null || {
35
- echo "emcc not found — source the emsdk env first (see header)." >&2
36
- exit 1
37
- }
38
-
39
- if [ ! -d "$SP_SRC" ]; then
40
- git clone https://github.com/google/sentencepiece.git "$SP_SRC"
41
- fi
42
-
43
- git -C "$SP_SRC" fetch --tags
44
- git -C "$SP_SRC" checkout "$SP_TAG"
45
-
46
- # Static library build. SPM_ENABLE_SHARED=off is required under emscripten; the TCMalloc probe is
47
- # meaningless in wasm.
48
- emcmake cmake -S "$SP_SRC" -B "$BUILD_DIR" \
49
- -DCMAKE_BUILD_TYPE=Release \
50
- -DSPM_ENABLE_SHARED=OFF \
51
- -DSPM_ENABLE_TCMALLOC=OFF > /dev/null
52
-
53
- # Full build (not just sentencepiece-static): v0.2.2 links against the vendored abseil-cpp, whose
54
- # ~90 small static libs only materialize with the default target set.
55
- cmake --build "$BUILD_DIR" -j "$(nproc)" > /dev/null
56
-
57
- # Every abseil archive joins the link line — wasm-ld's resolution across this many inter-dependent
58
- # archives is handled by listing them all; the dead ones are dropped by -Oz + gc-sections anyway.
59
- ABSL_LIBS=$(find "$BUILD_DIR/third_party/abseil-cpp" -name "*.a" | sort)
60
-
61
- # Link the binding. Notes on the flags:
62
- # - modularize + EXPORT_ES6: the artifact default-exports an async factory (createSentencePiece).
63
- # - SINGLE_FILE: wasm embedded as base64 (see header).
64
- # - environment=web,webview,worker,node: every consumer surface (browser demo, workers, Node CLI).
65
- # - ALLOW_MEMORY_GROWTH: tokenizer.model is ~1.6MB and encode allocations scale with input length.
66
- # - DISABLE_EXCEPTION_CATCHING=0: protobuf-lite + sentencepiece throw in cold error paths; without
67
- # catching enabled a bad model file aborts the runtime instead of returning a status.
68
- # - filesystem=0: only LoadFromSerializedProto is bound — no FS use anywhere.
69
- emcc "$SCRIPT_DIR/binding.cpp" \
70
- -I "$SP_SRC/src" -I "$SP_SRC" -I "$SP_SRC/third_party/abseil-cpp" -I "$SP_SRC/third_party/protobuf-lite" -I "$SP_SRC/src/builtin_pb" -I "$BUILD_DIR" \
71
- "$BUILD_DIR/src/libsentencepiece.a" \
72
- $ABSL_LIBS \
73
- -Oz \
74
- -lembind \
75
- -sMODULARIZE=1 \
76
- -sEXPORT_ES6=1 \
77
- -sEXPORT_NAME=createSentencePiece \
78
- -sSINGLE_FILE=1 \
79
- -sALLOW_MEMORY_GROWTH=1 \
80
- -sENVIRONMENT=web,webview,worker,node \
81
- -sDISABLE_EXCEPTION_CATCHING=0 \
82
- -sFILESYSTEM=0 \
83
- -o "$SCRIPT_DIR/sentencepiece.mjs"
84
-
85
- # The Node branch of the preamble imports `node:module` dynamically, behind ENVIRONMENT_IS_NODE. A browser bundler
86
- # bundles a literal dynamic import, and webpack has no handler for the `node:` scheme; the comment tells webpack to
87
- # leave the import to run time, where the branch never executes in a browser. esbuild and Vite ignore the comment
88
- # and treat the specifier as a builtin, which is what the bundle-graph health check's allowance names.
89
- sed -i 's|await import("node:module")|await import(/* webpackIgnore: true */ "node:module")|' "$SCRIPT_DIR/sentencepiece.mjs"
90
-
91
- echo "Built $SCRIPT_DIR/sentencepiece.mjs from sentencepiece $SP_TAG:"
92
- ls -la "$SCRIPT_DIR/sentencepiece.mjs"
package/index.d.ts DELETED
@@ -1,83 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * Type surface of the committed `sentencepiece.mjs` artifact, google/sentencepiece **v0.2.2**
7
- * compiled to wasm with the native-offsets embind wrapper (`binding.cpp`). Rebuilt only by
8
- * `build.sh`. Bump the tag there and note it here.
9
- */
10
-
11
- /**
12
- * One encode result.
13
- *
14
- * `begins` and `ends` are UTF-8 byte offsets into the encoded input.
15
- * The upstream invariant is `utf8(text).slice(begins[i], ends[i])` equals the piece's surface.
16
- *
17
- * Consecutive pieces also occupy contiguous byte ranges.
18
- * The TS tokenizer layer owns byte→UTF-16 conversion.
19
- */
20
- export interface EncodeWithOffsetsResult {
21
- pieces: string[]
22
- ids: number[]
23
- begins: number[]
24
- ends: number[]
25
- /**
26
- * Present instead of the arrays when encoding failed (errors cross the boundary as values).
27
- */
28
- error?: string
29
- }
30
-
31
- /**
32
- * The bound processor.
33
- *
34
- * Construct via the module factory, then `loadFromSerializedProto` once.
35
- */
36
- export declare class SentencePieceProcessor {
37
- constructor()
38
- /**
39
- * Load a `tokenizer.model` from its serialized-proto bytes.
40
- *
41
- * Takes serialized model bytes as a `Uint8Array`.
42
- * Embind marshals JS strings to `std::string` as UTF-8, corrupting arbitrary binary bytes.
43
- *
44
- * Returns `""` on success, the sentencepiece status message on failure.
45
- */
46
- loadFromSerializedProto(serialized: Uint8Array): string
47
- encodeWithOffsets(text: string): EncodeWithOffsetsResult
48
- decodeIDs(ids: IntVector): string
49
- /**
50
- * Embind object lifetime.
51
- *
52
- * The processor owns wasm-heap memory, so call `delete()` when done.
53
- * Long-lived singletons in practice never do.
54
- */
55
- delete(): void
56
- }
57
-
58
- /**
59
- * Embind-registered `std::vector<int>`.
60
- *
61
- * Build with `module.IntVector` and add ids with `push_back`.
62
- * Call `delete()` after use.
63
- */
64
- export declare class IntVector {
65
- constructor()
66
- push_back(value: number): void
67
- size(): number
68
- get(index: number): number
69
- delete(): void
70
- }
71
-
72
- export interface SentencePieceModule {
73
- SentencePieceProcessor: typeof SentencePieceProcessor
74
- IntVector: typeof IntVector
75
- }
76
-
77
- /**
78
- * The emscripten modularize factory.
79
- * It resolves once the embedded wasm is instantiated.
80
- */
81
- declare function createSentencePiece(): Promise<SentencePieceModule>
82
-
83
- export default createSentencePiece
package/sentencepiece.mjs DELETED
Binary file