@gnufoo/canaad 0.2.0 → 0.4.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/README.md CHANGED
@@ -1,104 +1,84 @@
1
- # canaad-wasm
1
+ # @gnufoo/canaad
2
2
 
3
- WASM bindings for AAD (Additional Authenticated Data) canonicalization per RFC 8785.
4
-
5
- This crate provides WebAssembly bindings for the `canaad-core` library, enabling
6
- AAD canonicalization in browsers, Node.js, and other WASM runtimes like
7
- Cloudflare Workers.
8
-
9
- ## Installation
3
+ AAD canonicalization in your browser or Worker. Same spec, same bytes.
10
4
 
11
5
  ```bash
12
6
  npm install @gnufoo/canaad
13
7
  ```
14
8
 
15
- ## Usage
16
-
17
- ### Canonicalize JSON
9
+ ## canonicalize
18
10
 
19
11
  ```typescript
20
12
  import { canonicalize, canonicalizeString, validate, hash } from '@gnufoo/canaad';
21
13
 
22
- // Canonicalize JSON to bytes
23
- const json = '{"v":1,"tenant":"org_abc","resource":"secrets/db","purpose":"encryption"}';
24
- const bytes: Uint8Array = canonicalize(json);
25
-
26
- // Canonicalize JSON to string
27
- const canonical: string = canonicalizeString(json);
28
- // => '{"purpose":"encryption","resource":"secrets/db","tenant":"org_abc","v":1}'
29
-
30
- // Validate JSON
31
- const isValid: boolean = validate(json);
32
-
33
- // Get SHA-256 hash of canonical form
34
- const hashBytes: Uint8Array = hash(json);
14
+ const bytes = canonicalize('{"v":1,"tenant":"org_abc","resource":"secrets/db","purpose":"encryption"}');
15
+ const str = canonicalizeString('{"v":1,"tenant":"org_abc","resource":"secrets/db","purpose":"encryption"}');
16
+ const ok = validate(json);
17
+ const sha = hash(json); // 32-byte SHA-256
35
18
  ```
36
19
 
37
- ### Builder API
20
+ ## build
38
21
 
39
22
  ```typescript
40
23
  import { AadBuilder } from '@gnufoo/canaad';
41
24
 
42
- const builder = new AadBuilder()
25
+ const aad = new AadBuilder()
43
26
  .tenant("org_abc")
44
27
  .resource("secrets/db")
45
28
  .purpose("encryption")
46
29
  .timestamp(1706400000)
47
30
  .extensionString("x_vault_cluster", "us-east-1")
48
- .extensionInt("x_app_priority", 5);
31
+ .extensionInt("x_app_priority", 5)
32
+ .build(); // Uint8Array
33
+ ```
49
34
 
50
- // Build to bytes
51
- const bytes: Uint8Array = builder.build();
35
+ Numbers only no BigInt. `build()` and `buildString()` validate all inputs:
52
36
 
53
- // Build to string
54
- const canonical: string = builder.buildString();
55
- ```
37
+ - NaN, Infinity, negative, fractional → rejected
38
+ - `-0.0` allowed (equals 0 in IEEE 754)
39
+ - integers > 2^53-1 → rejected (JS safe integer limit)
56
40
 
57
- ### Constants
41
+ ## exports
58
42
 
59
- ```typescript
60
- import { SPEC_VERSION, MAX_SAFE_INTEGER, MAX_SERIALIZED_BYTES } from '@gnufoo/canaad';
43
+ This package follows the gnufoo tool package format with four entry points:
61
44
 
62
- console.log(SPEC_VERSION); // 1
63
- console.log(MAX_SAFE_INTEGER); // 9007199254740991 (2^53 - 1)
64
- console.log(MAX_SERIALIZED_BYTES); // 16384 (16 KiB)
65
- ```
45
+ | Import | What you get |
46
+ |--------|-------------|
47
+ | `@gnufoo/canaad` | Direct WASM functions (after init) |
48
+ | `@gnufoo/canaad/init` | `initWasm()` + `isInitialized()` |
49
+ | `@gnufoo/canaad/meta` | Zod schemas + metadata (no WASM, SSG-safe) |
50
+ | `@gnufoo/canaad/tool` | `toolDefinition` with `execute()` |
66
51
 
67
- ## Error Handling
52
+ The `/meta` import is safe for static site generation — no WASM loaded.
68
53
 
69
- All functions that can fail will throw JavaScript errors with descriptive messages:
54
+ The `/tool` path validates inputs via Zod (`z.number().int().nonnegative()` for timestamps and extension integers). Direct WASM imports bypass Zod — the Rust layer validates as defense-in-depth.
70
55
 
71
- ```typescript
72
- try {
73
- canonicalize('{"v":1}'); // Missing required fields
74
- } catch (e) {
75
- console.error(e.message); // "missing required field: tenant"
76
- }
77
- ```
56
+ ## cloudflare workers
78
57
 
79
- ## Supported Environments
58
+ ```typescript
59
+ import wasmModule from '@gnufoo/canaad/canaad_wasm_bg.wasm';
60
+ import { toolDefinition } from '@gnufoo/canaad/tool';
80
61
 
81
- - **Browsers**: Modern browsers with WASM support
82
- - **Node.js**: v14+ with WASM support
83
- - **Cloudflare Workers**: Full support
84
- - **Deno**: With WASM import
62
+ await toolDefinition.initWasm(wasmModule);
85
63
 
86
- ## Building from Source
64
+ const result = await toolDefinition.execute({
65
+ action: 'build',
66
+ tenant: 'org_abc',
67
+ resource: 'secrets/db',
68
+ purpose: 'encryption',
69
+ });
70
+ ```
87
71
 
88
- ```bash
89
- # Install wasm-pack
90
- cargo install wasm-pack
72
+ ## browser (vite)
91
73
 
92
- # Build for bundlers (webpack, vite, etc.)
93
- wasm-pack build --target bundler
74
+ With `vite-plugin-wasm` and `vite-plugin-top-level-await`:
94
75
 
95
- # Build for Node.js
96
- wasm-pack build --target nodejs
76
+ ```typescript
77
+ import { toolDefinition } from '@gnufoo/canaad/tool';
97
78
 
98
- # Build for web (no bundler)
99
- wasm-pack build --target web
79
+ await toolDefinition.initWasm();
100
80
  ```
101
81
 
102
- ## License
82
+ ## license
103
83
 
104
84
  MIT OR Apache-2.0
package/canaad_wasm.d.ts CHANGED
@@ -2,92 +2,25 @@
2
2
  /* eslint-disable */
3
3
 
4
4
  /**
5
- * Builder for constructing AAD objects programmatically.
6
- *
7
- * Provides a fluent API for building AAD with method chaining.
8
- * All setter methods return a new builder to enable chaining.
9
- *
10
- * # Example (JavaScript)
11
- *
12
- * ```javascript
13
- * const builder = new AadBuilder()
14
- * .tenant("org_abc")
15
- * .resource("secrets/db")
16
- * .purpose("encryption")
17
- * .timestamp(1706400000)
18
- * .extensionString("x_vault_cluster", "us-east-1");
19
- *
20
- * const bytes = builder.build();
21
- * const canonical = builder.buildString();
22
- * ```
5
+ * Fluent builder for AAD objects. Chain setters, call `build()` or `buildString()`.
23
6
  */
24
7
  export class AadBuilder {
25
8
  free(): void;
26
9
  [Symbol.dispose](): void;
27
10
  /**
28
- * Builds the AAD and returns the canonical bytes.
29
- *
30
- * # Returns
31
- *
32
- * A `Uint8Array` containing the UTF-8 encoded canonical JSON.
33
- *
34
- * # Errors
35
- *
36
- * Throws a JavaScript error if:
37
- * - Required fields (tenant, resource, purpose) are missing
38
- * - Any field value is invalid
39
- * - Extension keys don't match the required pattern
40
- * - The serialized output exceeds 16 KiB
11
+ * Builds AAD and returns canonical bytes.
41
12
  */
42
13
  build(): Uint8Array;
43
14
  /**
44
- * Builds the AAD and returns the canonical string.
45
- *
46
- * # Returns
47
- *
48
- * The canonical (JCS) representation as a string.
49
- *
50
- * # Errors
51
- *
52
- * Throws a JavaScript error if:
53
- * - Required fields (tenant, resource, purpose) are missing
54
- * - Any field value is invalid
55
- * - Extension keys don't match the required pattern
56
- * - The serialized output exceeds 16 KiB
15
+ * Builds AAD and returns canonical UTF-8 string.
57
16
  */
58
17
  buildString(): string;
59
18
  /**
60
- * Adds an integer extension field.
61
- *
62
- * Extension keys must match pattern `x_<app>_<field>` where:
63
- * - `<app>` is one or more lowercase letters
64
- * - `<field>` is one or more lowercase letters or underscores
65
- *
66
- * # Arguments
67
- *
68
- * * `key` - Extension key (e.g., `x_app_priority`)
69
- * * `value` - Integer value (0 to 2^53-1)
70
- *
71
- * # Returns
72
- *
73
- * A new builder with the extension added.
19
+ * Adds an integer extension. Validated at `build()`.
74
20
  */
75
21
  extensionInt(key: string, value: number): AadBuilder;
76
22
  /**
77
- * Adds a string extension field.
78
- *
79
- * Extension keys must match pattern `x_<app>_<field>` where:
80
- * - `<app>` is one or more lowercase letters
81
- * - `<field>` is one or more lowercase letters or underscores
82
- *
83
- * # Arguments
84
- *
85
- * * `key` - Extension key (e.g., `x_vault_cluster`)
86
- * * `value` - String value (no NUL bytes)
87
- *
88
- * # Returns
89
- *
90
- * A new builder with the extension added.
23
+ * Adds a string extension. Key format: `x_<app>_<field>`.
91
24
  */
92
25
  extensionString(key: string, value: string): AadBuilder;
93
26
  /**
@@ -95,159 +28,105 @@ export class AadBuilder {
95
28
  */
96
29
  constructor();
97
30
  /**
98
- * Sets the purpose or usage context.
99
- *
100
- * # Arguments
101
- *
102
- * * `value` - Purpose description (1+ bytes, no NUL bytes)
103
- *
104
- * # Returns
105
- *
106
- * A new builder with the purpose set.
31
+ * Sets the purpose. 1+ bytes, no NUL.
107
32
  */
108
33
  purpose(value: string): AadBuilder;
109
34
  /**
110
- * Sets the resource path or identifier.
111
- *
112
- * # Arguments
113
- *
114
- * * `value` - Resource path (1-1024 bytes, no NUL bytes)
115
- *
116
- * # Returns
117
- *
118
- * A new builder with the resource set.
35
+ * Sets the resource. 1-1024 bytes, no NUL.
119
36
  */
120
37
  resource(value: string): AadBuilder;
121
38
  /**
122
- * Sets the tenant identifier.
123
- *
124
- * # Arguments
125
- *
126
- * * `value` - Tenant identifier (1-256 bytes, no NUL bytes)
127
- *
128
- * # Returns
129
- *
130
- * A new builder with the tenant set.
39
+ * Sets the tenant. 1-256 bytes, no NUL.
131
40
  */
132
41
  tenant(value: string): AadBuilder;
133
42
  /**
134
- * Sets the timestamp.
135
- *
136
- * # Arguments
137
- *
138
- * * `ts` - Unix timestamp (0 to 2^53-1)
139
- *
140
- * # Returns
141
- *
142
- * A new builder with the timestamp set.
43
+ * Sets the timestamp. Validated at `build()`.
143
44
  */
144
45
  timestamp(ts: number): AadBuilder;
145
46
  }
146
47
 
147
48
  /**
148
- * Returns the maximum safe integer value (2^53 - 1).
149
- *
150
- * This is the maximum integer value that can be exactly represented in
151
- * JavaScript's Number type.
49
+ * Maximum safe integer (2^53 - 1).
152
50
  */
153
51
  export function MAX_SAFE_INTEGER(): number;
154
52
 
155
53
  /**
156
- * Returns the maximum serialized AAD size in bytes (16 KiB).
54
+ * Maximum serialized AAD size in bytes (16 KiB).
157
55
  */
158
56
  export function MAX_SERIALIZED_BYTES(): number;
159
57
 
160
58
  /**
161
- * Returns the current AAD specification version.
162
- *
163
- * Currently always returns 1.
59
+ * Current AAD specification version (always 1).
164
60
  */
165
61
  export function SPEC_VERSION(): number;
166
62
 
167
63
  /**
168
- * Parses and canonicalizes a JSON string to bytes.
169
- *
170
- * This function:
171
- * 1. Parses the JSON with duplicate key detection
172
- * 2. Validates all fields according to the AAD specification
173
- * 3. Returns the canonical (JCS) representation as bytes
174
- *
175
- * # Arguments
176
- *
177
- * * `json` - A JSON string containing an AAD object
178
- *
179
- * # Returns
180
- *
181
- * A `Uint8Array` containing the UTF-8 encoded canonical JSON.
182
- *
183
- * # Errors
184
- *
185
- * Throws a JavaScript error if:
186
- * - The JSON is invalid or contains duplicate keys
187
- * - Any field violates AAD constraints
188
- * - The serialized output exceeds 16 KiB
64
+ * Parses and canonicalizes a JSON string to bytes (RFC 8785).
189
65
  */
190
66
  export function canonicalize(json: string): Uint8Array;
191
67
 
192
68
  /**
193
69
  * Parses and canonicalizes a JSON string to a UTF-8 string.
194
- *
195
- * This is equivalent to `canonicalize` but returns a string instead of bytes.
196
- *
197
- * # Arguments
198
- *
199
- * * `json` - A JSON string containing an AAD object
200
- *
201
- * # Returns
202
- *
203
- * The canonical (JCS) representation as a string.
204
- *
205
- * # Errors
206
- *
207
- * Throws a JavaScript error if:
208
- * - The JSON is invalid or contains duplicate keys
209
- * - Any field violates AAD constraints
210
- * - The serialized output exceeds 16 KiB
211
70
  */
212
71
  export function canonicalizeString(json: string): string;
213
72
 
214
73
  /**
215
- * Computes the SHA-256 hash of the canonical JSON form.
216
- *
217
- * This function:
218
- * 1. Parses and validates the JSON
219
- * 2. Canonicalizes according to RFC 8785
220
- * 3. Returns the SHA-256 hash of the canonical bytes
221
- *
222
- * # Arguments
223
- *
224
- * * `json` - A JSON string containing an AAD object
225
- *
226
- * # Returns
227
- *
228
- * A 32-byte `Uint8Array` containing the SHA-256 hash.
229
- *
230
- * # Errors
231
- *
232
- * Throws a JavaScript error if:
233
- * - The JSON is invalid or contains duplicate keys
234
- * - Any field violates AAD constraints
235
- * - The serialized output exceeds 16 KiB
74
+ * SHA-256 hash of the canonical JSON form.
236
75
  */
237
76
  export function hash(json: string): Uint8Array;
238
77
 
239
78
  /**
240
79
  * Validates a JSON string against the AAD specification.
80
+ */
81
+ export function validate(json: string): boolean;
82
+
83
+ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
84
+
85
+ export interface InitOutput {
86
+ readonly memory: WebAssembly.Memory;
87
+ readonly MAX_SAFE_INTEGER: () => number;
88
+ readonly MAX_SERIALIZED_BYTES: () => number;
89
+ readonly SPEC_VERSION: () => number;
90
+ readonly __wbg_aadbuilder_free: (a: number, b: number) => void;
91
+ readonly aadbuilder_build: (a: number) => [number, number, number, number];
92
+ readonly aadbuilder_buildString: (a: number) => [number, number, number, number];
93
+ readonly aadbuilder_extensionInt: (a: number, b: number, c: number, d: number) => number;
94
+ readonly aadbuilder_extensionString: (a: number, b: number, c: number, d: number, e: number) => number;
95
+ readonly aadbuilder_new: () => number;
96
+ readonly aadbuilder_purpose: (a: number, b: number, c: number) => number;
97
+ readonly aadbuilder_resource: (a: number, b: number, c: number) => number;
98
+ readonly aadbuilder_tenant: (a: number, b: number, c: number) => number;
99
+ readonly aadbuilder_timestamp: (a: number, b: number) => number;
100
+ readonly canonicalize: (a: number, b: number) => [number, number, number, number];
101
+ readonly canonicalizeString: (a: number, b: number) => [number, number, number, number];
102
+ readonly hash: (a: number, b: number) => [number, number, number, number];
103
+ readonly validate: (a: number, b: number) => number;
104
+ readonly __wbindgen_externrefs: WebAssembly.Table;
105
+ readonly __externref_table_dealloc: (a: number) => void;
106
+ readonly __wbindgen_free: (a: number, b: number, c: number) => void;
107
+ readonly __wbindgen_malloc: (a: number, b: number) => number;
108
+ readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
109
+ readonly __wbindgen_start: () => void;
110
+ }
111
+
112
+ export type SyncInitInput = BufferSource | WebAssembly.Module;
113
+
114
+ /**
115
+ * Instantiates the given `module`, which can either be bytes or
116
+ * a precompiled `WebAssembly.Module`.
241
117
  *
242
- * This function performs full validation without returning the context.
243
- * Use this for quick validation checks.
244
- *
245
- * # Arguments
118
+ * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
246
119
  *
247
- * * `json` - A JSON string to validate
120
+ * @returns {InitOutput}
121
+ */
122
+ export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
123
+
124
+ /**
125
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
126
+ * for everything else, calls `WebAssembly.instantiate` directly.
248
127
  *
249
- * # Returns
128
+ * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
250
129
  *
251
- * `true` if the JSON is valid AAD, `false` otherwise.
130
+ * @returns {Promise<InitOutput>}
252
131
  */
253
- export function validate(json: string): boolean;
132
+ export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
package/canaad_wasm.js CHANGED
@@ -1,9 +1,454 @@
1
1
  /* @ts-self-types="./canaad_wasm.d.ts" */
2
2
 
3
- import * as wasm from "./canaad_wasm_bg.wasm";
4
- import { __wbg_set_wasm } from "./canaad_wasm_bg.js";
5
- __wbg_set_wasm(wasm);
6
- wasm.__wbindgen_start();
7
- export {
8
- AadBuilder, MAX_SAFE_INTEGER, MAX_SERIALIZED_BYTES, SPEC_VERSION, canonicalize, canonicalizeString, hash, validate
9
- } from "./canaad_wasm_bg.js";
3
+ /**
4
+ * Fluent builder for AAD objects. Chain setters, call `build()` or `buildString()`.
5
+ */
6
+ export class AadBuilder {
7
+ static __wrap(ptr) {
8
+ ptr = ptr >>> 0;
9
+ const obj = Object.create(AadBuilder.prototype);
10
+ obj.__wbg_ptr = ptr;
11
+ AadBuilderFinalization.register(obj, obj.__wbg_ptr, obj);
12
+ return obj;
13
+ }
14
+ __destroy_into_raw() {
15
+ const ptr = this.__wbg_ptr;
16
+ this.__wbg_ptr = 0;
17
+ AadBuilderFinalization.unregister(this);
18
+ return ptr;
19
+ }
20
+ free() {
21
+ const ptr = this.__destroy_into_raw();
22
+ wasm.__wbg_aadbuilder_free(ptr, 0);
23
+ }
24
+ /**
25
+ * Builds AAD and returns canonical bytes.
26
+ * @returns {Uint8Array}
27
+ */
28
+ build() {
29
+ const ret = wasm.aadbuilder_build(this.__wbg_ptr);
30
+ if (ret[3]) {
31
+ throw takeFromExternrefTable0(ret[2]);
32
+ }
33
+ var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
34
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
35
+ return v1;
36
+ }
37
+ /**
38
+ * Builds AAD and returns canonical UTF-8 string.
39
+ * @returns {string}
40
+ */
41
+ buildString() {
42
+ let deferred2_0;
43
+ let deferred2_1;
44
+ try {
45
+ const ret = wasm.aadbuilder_buildString(this.__wbg_ptr);
46
+ var ptr1 = ret[0];
47
+ var len1 = ret[1];
48
+ if (ret[3]) {
49
+ ptr1 = 0; len1 = 0;
50
+ throw takeFromExternrefTable0(ret[2]);
51
+ }
52
+ deferred2_0 = ptr1;
53
+ deferred2_1 = len1;
54
+ return getStringFromWasm0(ptr1, len1);
55
+ } finally {
56
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
57
+ }
58
+ }
59
+ /**
60
+ * Adds an integer extension. Validated at `build()`.
61
+ * @param {string} key
62
+ * @param {number} value
63
+ * @returns {AadBuilder}
64
+ */
65
+ extensionInt(key, value) {
66
+ const ptr = this.__destroy_into_raw();
67
+ const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
68
+ const len0 = WASM_VECTOR_LEN;
69
+ const ret = wasm.aadbuilder_extensionInt(ptr, ptr0, len0, value);
70
+ return AadBuilder.__wrap(ret);
71
+ }
72
+ /**
73
+ * Adds a string extension. Key format: `x_<app>_<field>`.
74
+ * @param {string} key
75
+ * @param {string} value
76
+ * @returns {AadBuilder}
77
+ */
78
+ extensionString(key, value) {
79
+ const ptr = this.__destroy_into_raw();
80
+ const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
81
+ const len0 = WASM_VECTOR_LEN;
82
+ const ptr1 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
83
+ const len1 = WASM_VECTOR_LEN;
84
+ const ret = wasm.aadbuilder_extensionString(ptr, ptr0, len0, ptr1, len1);
85
+ return AadBuilder.__wrap(ret);
86
+ }
87
+ /**
88
+ * Creates a new AAD builder.
89
+ */
90
+ constructor() {
91
+ const ret = wasm.aadbuilder_new();
92
+ this.__wbg_ptr = ret >>> 0;
93
+ AadBuilderFinalization.register(this, this.__wbg_ptr, this);
94
+ return this;
95
+ }
96
+ /**
97
+ * Sets the purpose. 1+ bytes, no NUL.
98
+ * @param {string} value
99
+ * @returns {AadBuilder}
100
+ */
101
+ purpose(value) {
102
+ const ptr = this.__destroy_into_raw();
103
+ const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
104
+ const len0 = WASM_VECTOR_LEN;
105
+ const ret = wasm.aadbuilder_purpose(ptr, ptr0, len0);
106
+ return AadBuilder.__wrap(ret);
107
+ }
108
+ /**
109
+ * Sets the resource. 1-1024 bytes, no NUL.
110
+ * @param {string} value
111
+ * @returns {AadBuilder}
112
+ */
113
+ resource(value) {
114
+ const ptr = this.__destroy_into_raw();
115
+ const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
116
+ const len0 = WASM_VECTOR_LEN;
117
+ const ret = wasm.aadbuilder_resource(ptr, ptr0, len0);
118
+ return AadBuilder.__wrap(ret);
119
+ }
120
+ /**
121
+ * Sets the tenant. 1-256 bytes, no NUL.
122
+ * @param {string} value
123
+ * @returns {AadBuilder}
124
+ */
125
+ tenant(value) {
126
+ const ptr = this.__destroy_into_raw();
127
+ const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
128
+ const len0 = WASM_VECTOR_LEN;
129
+ const ret = wasm.aadbuilder_tenant(ptr, ptr0, len0);
130
+ return AadBuilder.__wrap(ret);
131
+ }
132
+ /**
133
+ * Sets the timestamp. Validated at `build()`.
134
+ * @param {number} ts
135
+ * @returns {AadBuilder}
136
+ */
137
+ timestamp(ts) {
138
+ const ptr = this.__destroy_into_raw();
139
+ const ret = wasm.aadbuilder_timestamp(ptr, ts);
140
+ return AadBuilder.__wrap(ret);
141
+ }
142
+ }
143
+ if (Symbol.dispose) AadBuilder.prototype[Symbol.dispose] = AadBuilder.prototype.free;
144
+
145
+ /**
146
+ * Maximum safe integer (2^53 - 1).
147
+ * @returns {number}
148
+ */
149
+ export function MAX_SAFE_INTEGER() {
150
+ const ret = wasm.MAX_SAFE_INTEGER();
151
+ return ret;
152
+ }
153
+
154
+ /**
155
+ * Maximum serialized AAD size in bytes (16 KiB).
156
+ * @returns {number}
157
+ */
158
+ export function MAX_SERIALIZED_BYTES() {
159
+ const ret = wasm.MAX_SERIALIZED_BYTES();
160
+ return ret >>> 0;
161
+ }
162
+
163
+ /**
164
+ * Current AAD specification version (always 1).
165
+ * @returns {number}
166
+ */
167
+ export function SPEC_VERSION() {
168
+ const ret = wasm.SPEC_VERSION();
169
+ return ret >>> 0;
170
+ }
171
+
172
+ /**
173
+ * Parses and canonicalizes a JSON string to bytes (RFC 8785).
174
+ * @param {string} json
175
+ * @returns {Uint8Array}
176
+ */
177
+ export function canonicalize(json) {
178
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
179
+ const len0 = WASM_VECTOR_LEN;
180
+ const ret = wasm.canonicalize(ptr0, len0);
181
+ if (ret[3]) {
182
+ throw takeFromExternrefTable0(ret[2]);
183
+ }
184
+ var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
185
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
186
+ return v2;
187
+ }
188
+
189
+ /**
190
+ * Parses and canonicalizes a JSON string to a UTF-8 string.
191
+ * @param {string} json
192
+ * @returns {string}
193
+ */
194
+ export function canonicalizeString(json) {
195
+ let deferred3_0;
196
+ let deferred3_1;
197
+ try {
198
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
199
+ const len0 = WASM_VECTOR_LEN;
200
+ const ret = wasm.canonicalizeString(ptr0, len0);
201
+ var ptr2 = ret[0];
202
+ var len2 = ret[1];
203
+ if (ret[3]) {
204
+ ptr2 = 0; len2 = 0;
205
+ throw takeFromExternrefTable0(ret[2]);
206
+ }
207
+ deferred3_0 = ptr2;
208
+ deferred3_1 = len2;
209
+ return getStringFromWasm0(ptr2, len2);
210
+ } finally {
211
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
212
+ }
213
+ }
214
+
215
+ /**
216
+ * SHA-256 hash of the canonical JSON form.
217
+ * @param {string} json
218
+ * @returns {Uint8Array}
219
+ */
220
+ export function hash(json) {
221
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
222
+ const len0 = WASM_VECTOR_LEN;
223
+ const ret = wasm.hash(ptr0, len0);
224
+ if (ret[3]) {
225
+ throw takeFromExternrefTable0(ret[2]);
226
+ }
227
+ var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
228
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
229
+ return v2;
230
+ }
231
+
232
+ /**
233
+ * Validates a JSON string against the AAD specification.
234
+ * @param {string} json
235
+ * @returns {boolean}
236
+ */
237
+ export function validate(json) {
238
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
239
+ const len0 = WASM_VECTOR_LEN;
240
+ const ret = wasm.validate(ptr0, len0);
241
+ return ret !== 0;
242
+ }
243
+
244
+ function __wbg_get_imports() {
245
+ const import0 = {
246
+ __proto__: null,
247
+ __wbg_Error_8c4e43fe74559d73: function(arg0, arg1) {
248
+ const ret = Error(getStringFromWasm0(arg0, arg1));
249
+ return ret;
250
+ },
251
+ __wbg___wbindgen_throw_be289d5034ed271b: function(arg0, arg1) {
252
+ throw new Error(getStringFromWasm0(arg0, arg1));
253
+ },
254
+ __wbindgen_init_externref_table: function() {
255
+ const table = wasm.__wbindgen_externrefs;
256
+ const offset = table.grow(4);
257
+ table.set(0, undefined);
258
+ table.set(offset + 0, undefined);
259
+ table.set(offset + 1, null);
260
+ table.set(offset + 2, true);
261
+ table.set(offset + 3, false);
262
+ },
263
+ };
264
+ return {
265
+ __proto__: null,
266
+ "./canaad_wasm_bg.js": import0,
267
+ };
268
+ }
269
+
270
+ const AadBuilderFinalization = (typeof FinalizationRegistry === 'undefined')
271
+ ? { register: () => {}, unregister: () => {} }
272
+ : new FinalizationRegistry(ptr => wasm.__wbg_aadbuilder_free(ptr >>> 0, 1));
273
+
274
+ function getArrayU8FromWasm0(ptr, len) {
275
+ ptr = ptr >>> 0;
276
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
277
+ }
278
+
279
+ function getStringFromWasm0(ptr, len) {
280
+ ptr = ptr >>> 0;
281
+ return decodeText(ptr, len);
282
+ }
283
+
284
+ let cachedUint8ArrayMemory0 = null;
285
+ function getUint8ArrayMemory0() {
286
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
287
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
288
+ }
289
+ return cachedUint8ArrayMemory0;
290
+ }
291
+
292
+ function passStringToWasm0(arg, malloc, realloc) {
293
+ if (realloc === undefined) {
294
+ const buf = cachedTextEncoder.encode(arg);
295
+ const ptr = malloc(buf.length, 1) >>> 0;
296
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
297
+ WASM_VECTOR_LEN = buf.length;
298
+ return ptr;
299
+ }
300
+
301
+ let len = arg.length;
302
+ let ptr = malloc(len, 1) >>> 0;
303
+
304
+ const mem = getUint8ArrayMemory0();
305
+
306
+ let offset = 0;
307
+
308
+ for (; offset < len; offset++) {
309
+ const code = arg.charCodeAt(offset);
310
+ if (code > 0x7F) break;
311
+ mem[ptr + offset] = code;
312
+ }
313
+ if (offset !== len) {
314
+ if (offset !== 0) {
315
+ arg = arg.slice(offset);
316
+ }
317
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
318
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
319
+ const ret = cachedTextEncoder.encodeInto(arg, view);
320
+
321
+ offset += ret.written;
322
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
323
+ }
324
+
325
+ WASM_VECTOR_LEN = offset;
326
+ return ptr;
327
+ }
328
+
329
+ function takeFromExternrefTable0(idx) {
330
+ const value = wasm.__wbindgen_externrefs.get(idx);
331
+ wasm.__externref_table_dealloc(idx);
332
+ return value;
333
+ }
334
+
335
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
336
+ cachedTextDecoder.decode();
337
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
338
+ let numBytesDecoded = 0;
339
+ function decodeText(ptr, len) {
340
+ numBytesDecoded += len;
341
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
342
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
343
+ cachedTextDecoder.decode();
344
+ numBytesDecoded = len;
345
+ }
346
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
347
+ }
348
+
349
+ const cachedTextEncoder = new TextEncoder();
350
+
351
+ if (!('encodeInto' in cachedTextEncoder)) {
352
+ cachedTextEncoder.encodeInto = function (arg, view) {
353
+ const buf = cachedTextEncoder.encode(arg);
354
+ view.set(buf);
355
+ return {
356
+ read: arg.length,
357
+ written: buf.length
358
+ };
359
+ };
360
+ }
361
+
362
+ let WASM_VECTOR_LEN = 0;
363
+
364
+ let wasmModule, wasm;
365
+ function __wbg_finalize_init(instance, module) {
366
+ wasm = instance.exports;
367
+ wasmModule = module;
368
+ cachedUint8ArrayMemory0 = null;
369
+ wasm.__wbindgen_start();
370
+ return wasm;
371
+ }
372
+
373
+ async function __wbg_load(module, imports) {
374
+ if (typeof Response === 'function' && module instanceof Response) {
375
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
376
+ try {
377
+ return await WebAssembly.instantiateStreaming(module, imports);
378
+ } catch (e) {
379
+ const validResponse = module.ok && expectedResponseType(module.type);
380
+
381
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
382
+ 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);
383
+
384
+ } else { throw e; }
385
+ }
386
+ }
387
+
388
+ const bytes = await module.arrayBuffer();
389
+ return await WebAssembly.instantiate(bytes, imports);
390
+ } else {
391
+ const instance = await WebAssembly.instantiate(module, imports);
392
+
393
+ if (instance instanceof WebAssembly.Instance) {
394
+ return { instance, module };
395
+ } else {
396
+ return instance;
397
+ }
398
+ }
399
+
400
+ function expectedResponseType(type) {
401
+ switch (type) {
402
+ case 'basic': case 'cors': case 'default': return true;
403
+ }
404
+ return false;
405
+ }
406
+ }
407
+
408
+ function initSync(module) {
409
+ if (wasm !== undefined) return wasm;
410
+
411
+
412
+ if (module !== undefined) {
413
+ if (Object.getPrototypeOf(module) === Object.prototype) {
414
+ ({module} = module)
415
+ } else {
416
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
417
+ }
418
+ }
419
+
420
+ const imports = __wbg_get_imports();
421
+ if (!(module instanceof WebAssembly.Module)) {
422
+ module = new WebAssembly.Module(module);
423
+ }
424
+ const instance = new WebAssembly.Instance(module, imports);
425
+ return __wbg_finalize_init(instance, module);
426
+ }
427
+
428
+ async function __wbg_init(module_or_path) {
429
+ if (wasm !== undefined) return wasm;
430
+
431
+
432
+ if (module_or_path !== undefined) {
433
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
434
+ ({module_or_path} = module_or_path)
435
+ } else {
436
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
437
+ }
438
+ }
439
+
440
+ if (module_or_path === undefined) {
441
+ module_or_path = new URL('canaad_wasm_bg.wasm', import.meta.url);
442
+ }
443
+ const imports = __wbg_get_imports();
444
+
445
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
446
+ module_or_path = fetch(module_or_path);
447
+ }
448
+
449
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
450
+
451
+ return __wbg_finalize_init(instance, module);
452
+ }
453
+
454
+ export { initSync, __wbg_init as default };
Binary file
package/init.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Initialize WASM. Call once before using any WASM functions.
3
+ *
4
+ * @param wasmModule - Pass the WebAssembly.Module in Workers, omit in browser
5
+ */
6
+ export function initWasm(wasmModule?: WebAssembly.Module): Promise<void>;
7
+
8
+ /**
9
+ * Check if WASM has been initialized.
10
+ */
11
+ export function isInitialized(): boolean;
package/init.js ADDED
@@ -0,0 +1,24 @@
1
+ import init from './canaad_wasm.js';
2
+
3
+ let initialized = false;
4
+ let initPromise = null;
5
+
6
+ /**
7
+ * Initialize WASM. Call once before using any WASM functions.
8
+ *
9
+ * @param {WebAssembly.Module | undefined} wasmModule - Pass the Module in Workers, omit in browser
10
+ */
11
+ export async function initWasm(wasmModule) {
12
+ if (initialized) return;
13
+ if (initPromise) return initPromise;
14
+
15
+ initPromise = init(wasmModule).then(() => {
16
+ initialized = true;
17
+ });
18
+
19
+ return initPromise;
20
+ }
21
+
22
+ export function isInitialized() {
23
+ return initialized;
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gnufoo/canaad",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "main": "canaad_wasm.js",
6
6
  "types": "canaad_wasm.d.ts",
@@ -16,6 +16,10 @@
16
16
  "./tool": {
17
17
  "types": "./tool.d.ts",
18
18
  "import": "./tool.js"
19
+ },
20
+ "./init": {
21
+ "types": "./init.d.ts",
22
+ "import": "./init.js"
19
23
  }
20
24
  },
21
25
  "dependencies": {
@@ -26,9 +30,7 @@
26
30
  "*.d.ts",
27
31
  "*.wasm"
28
32
  ],
29
- "sideEffects": [
30
- "./canaad_wasm.js"
31
- ],
33
+ "sideEffects": false,
32
34
  "keywords": [
33
35
  "aead",
34
36
  "aad",
package/tool.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import type { meta, CanaadInput, CanaadOutput } from './meta.js';
2
+ import type { initWasm, isInitialized } from './init.js';
2
3
 
3
4
  export declare const toolDefinition: typeof meta & {
5
+ initWasm: typeof initWasm;
6
+ isInitialized: typeof isInitialized;
4
7
  execute(input: CanaadInput): Promise<CanaadOutput>;
5
8
  };
package/tool.js CHANGED
@@ -1,13 +1,25 @@
1
1
  import { meta, inputSchema } from './meta.js';
2
+ import { initWasm, isInitialized } from './init.js';
2
3
  import { canonicalize, canonicalizeString, hash, validate, AadBuilder } from './canaad_wasm.js';
3
4
 
4
5
  const bytesToHex = (bytes) => Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
5
- const bytesToBase64 = (bytes) => btoa(String.fromCharCode(...bytes));
6
+ const bytesToBase64 = (bytes) => globalThis.btoa(String.fromCharCode(...bytes));
6
7
 
7
8
  export const toolDefinition = {
8
9
  ...meta,
9
10
 
11
+ /**
12
+ * Initialize WASM. Must be called before execute() in Workers.
13
+ * In browsers with vite-plugin-wasm, this is optional.
14
+ */
15
+ initWasm,
16
+ isInitialized,
17
+
10
18
  async execute(rawInput) {
19
+ if (!isInitialized()) {
20
+ throw new Error('WASM not initialized. Call initWasm() first.');
21
+ }
22
+
11
23
  const input = inputSchema.parse(rawInput);
12
24
 
13
25
  switch (input.action) {