@openedges/pkl-napi 0.0.0-stage → 0.32.0-rc.3

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/dist/index.cjs ADDED
@@ -0,0 +1,2606 @@
1
+ "use strict";
2
+
3
+ const { existsSync } = require("node:fs");
4
+ const { resolve } = require("node:path");
5
+
6
+ function detectLinuxLibc() {
7
+ if (process.platform !== "linux") return null;
8
+ try {
9
+ const report =
10
+ process.report && typeof process.report.getReport === "function"
11
+ ? process.report.getReport()
12
+ : null;
13
+ if (report && report.header && report.header.glibcVersionRuntime) {
14
+ return "gnu";
15
+ }
16
+ const shared = report && Array.isArray(report.sharedObjects) ? report.sharedObjects : [];
17
+ if (shared.some((s) => typeof s === "string" && (s.includes("musl") || s.includes("ld-musl")))) {
18
+ return "musl";
19
+ }
20
+ } catch {
21
+ // Fall through to filesystem probe
22
+ }
23
+ if (
24
+ existsSync("/lib/ld-musl-x86_64.so.1") ||
25
+ existsSync("/lib/ld-musl-aarch64.so.1")
26
+ ) {
27
+ return "musl";
28
+ }
29
+ return "gnu";
30
+ }
31
+
32
+ function loadNativeAddon() {
33
+ const linuxLibc = detectLinuxLibc();
34
+ const candidates = [
35
+ process.env.PKL_NAPI_ADDON_PATH,
36
+ linuxLibc
37
+ ? resolve(__dirname, "..", "native", `pkl_napi.linux-${process.arch}-${linuxLibc}.node`)
38
+ : null,
39
+ resolve(__dirname, "..", "native", `pkl_napi.${process.platform}-${process.arch}.node`),
40
+ resolve(__dirname, "..", "native", "pkl_napi.node"),
41
+ ].filter(Boolean);
42
+
43
+ for (const candidate of candidates) {
44
+ if (existsSync(candidate)) {
45
+ return require(candidate);
46
+ }
47
+ }
48
+ throw new Error(
49
+ `Unable to load native @openedges/pkl-napi addon for ${process.platform}-${process.arch}${linuxLibc ? `-${linuxLibc}` : ""}. Checked: ${candidates.join(", ")}`,
50
+ );
51
+ }
52
+
53
+ const native = loadNativeAddon();
54
+
55
+ const PKL_VERSION = native.productPklVersion ? native.productPklVersion() : "0.32.0";
56
+ const MAX_U64 = (1n << 64n) - 1n;
57
+ const MIN_I64 = -(1n << 63n);
58
+ const MAX_I64 = (1n << 63n) - 1n;
59
+ const FAST_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
60
+ const VALID_DURATION_UNITS = new Set(["ns", "us", "ms", "s", "min", "h", "d"]);
61
+ const VALID_DATA_SIZE_UNITS = new Set([
62
+ "b", "kb", "mb", "gb", "tb", "pb", "kib", "mib", "gib", "tib", "pib",
63
+ ]);
64
+ const BLANK_OR_CTRL_RE = /^[\s\x00-\x20]*$/;
65
+ const DECODE_FALLBACK = Symbol("pkl.decode.fallback");
66
+
67
+ class PklError extends Error {
68
+ constructor(message, kind = "evaluation", capability = undefined) {
69
+ super(message);
70
+ this.name = "PklError";
71
+ this.kind = kind;
72
+ this.code = kind;
73
+ if (capability !== undefined) {
74
+ this.capability = capability;
75
+ }
76
+ }
77
+ }
78
+
79
+ function unwrapOutcome(outcome) {
80
+ if (!outcome || typeof outcome !== "object") {
81
+ throw new PklError("Malformed native outcome from pkl-napi.", "evaluation");
82
+ }
83
+ if (!outcome.ok) {
84
+ throw new PklError(
85
+ outcome.message ?? "Unknown Pkl error",
86
+ outcome.kind ?? "evaluation",
87
+ outcome.capability,
88
+ );
89
+ }
90
+ return outcome.value;
91
+ }
92
+
93
+ function capabilities() {
94
+ return {
95
+ vfs: false,
96
+ asyncModuleLoader: true,
97
+ asyncResourceLoader: true,
98
+ nativeFs: true,
99
+ nativeHttp: true,
100
+ externalReaders: true,
101
+ modulePathJar: true,
102
+ projectResolution: true,
103
+ packageCache: true,
104
+ formatter: true,
105
+ repl: true,
106
+ schema: true,
107
+ analyzeImports: true,
108
+ bigint64: true,
109
+ uint8ArrayBytes: true,
110
+ clock64Bit: true,
111
+ platform: process.platform,
112
+ runtime: "napi-node",
113
+ arch: process.arch,
114
+ };
115
+ }
116
+
117
+ class ModuleSource {
118
+ constructor(uri, contents = undefined) {
119
+ if (typeof uri !== "string" || uri.length === 0) {
120
+ throw new PklError("ModuleSource uri must be a non-empty string.", "invalid-argument");
121
+ }
122
+ if (contents !== undefined && typeof contents !== "string") {
123
+ throw new PklError("ModuleSource contents must be a string or undefined.", "invalid-argument");
124
+ }
125
+ this.uri = uri;
126
+ if (contents !== undefined) {
127
+ this.contents = contents;
128
+ }
129
+ Object.freeze(this);
130
+ }
131
+
132
+ static text(text, uri = "repl:text") {
133
+ if (typeof text !== "string") {
134
+ throw new PklError("ModuleSource.text requires a string source.", "invalid-argument");
135
+ }
136
+ if (typeof uri !== "string" || uri.length === 0) {
137
+ throw new PklError("ModuleSource.text uri must be a non-empty string.", "invalid-argument");
138
+ }
139
+ return new ModuleSource(uri, text);
140
+ }
141
+
142
+ static uri(uri) {
143
+ if (typeof uri !== "string" || uri.length === 0) {
144
+ throw new PklError("ModuleSource.uri requires a non-empty string.", "invalid-argument");
145
+ }
146
+ return new ModuleSource(uri, undefined);
147
+ }
148
+
149
+ static path(fsPath) {
150
+ if (typeof fsPath !== "string" || fsPath.length === 0) {
151
+ throw new PklError("ModuleSource.path requires a non-empty string path.", "invalid-argument");
152
+ }
153
+ const uri = unwrapOutcome(native.productPathToFileUri(fsPath));
154
+ return new ModuleSource(uri, undefined);
155
+ }
156
+
157
+ static modulePath(modulePath) {
158
+ if (typeof modulePath !== "string" || modulePath.length === 0) {
159
+ throw new PklError(
160
+ "ModuleSource.modulePath requires a non-empty string path.",
161
+ "invalid-argument",
162
+ );
163
+ }
164
+ let uri;
165
+ if (modulePath.startsWith("modulepath:")) {
166
+ uri = modulePath;
167
+ } else if (modulePath.startsWith("/")) {
168
+ uri = `modulepath:${modulePath}`;
169
+ } else {
170
+ uri = `modulepath:/${modulePath}`;
171
+ }
172
+ return new ModuleSource(uri, undefined);
173
+ }
174
+ }
175
+
176
+ function normalizeSource(source) {
177
+ if (source instanceof ModuleSource) {
178
+ return { uri: source.uri, contents: source.contents };
179
+ }
180
+ if (source && typeof source === "object" && typeof source.uri === "string") {
181
+ if (source.contents !== undefined && typeof source.contents !== "string") {
182
+ throw new PklError("ModuleSource.contents must be a string.", "invalid-argument");
183
+ }
184
+ return { uri: source.uri, contents: source.contents };
185
+ }
186
+ throw new PklError("Expected a ModuleSource instance.", "invalid-argument");
187
+ }
188
+
189
+ class PklDuration {
190
+ constructor(value, unit) {
191
+ this.value = value;
192
+ this.unit = unit;
193
+ }
194
+ }
195
+
196
+ class PklDataSize {
197
+ constructor(value, unit) {
198
+ this.value = value;
199
+ this.unit = unit;
200
+ }
201
+ }
202
+
203
+ class PklPair {
204
+ constructor(first, second) {
205
+ this.first = first;
206
+ this.second = second;
207
+ }
208
+ }
209
+
210
+ class PklRegex {
211
+ constructor(pattern) {
212
+ this.pattern = pattern;
213
+ }
214
+ }
215
+
216
+ class PklObject {
217
+ constructor(className, moduleUri, properties = {}, entries = new Map(), elements = []) {
218
+ this.className = className;
219
+ this.moduleUri = moduleUri;
220
+ this.properties = properties;
221
+ this.entries = entries instanceof Map ? entries : new Map(entries);
222
+ this.elements = Array.isArray(elements) ? elements : Array.from(elements);
223
+ }
224
+ }
225
+
226
+ class PklClass {
227
+ constructor(name, moduleUri) {
228
+ this.name = name;
229
+ this.moduleUri = moduleUri;
230
+ }
231
+ }
232
+
233
+ class PklTypeAlias {
234
+ constructor(name, moduleUri) {
235
+ this.name = name;
236
+ this.moduleUri = moduleUri;
237
+ }
238
+ }
239
+
240
+ class PklIntSeq {
241
+ constructor(start, end, step) {
242
+ this.start = BigInt(start);
243
+ this.end = BigInt(end);
244
+ this.step = BigInt(step);
245
+ }
246
+ }
247
+
248
+ class PklFunction {}
249
+
250
+ class PklReference {
251
+ constructor(domain, data, path = []) {
252
+ this.domain = domain;
253
+ this.data = data;
254
+ this.path = Array.isArray(path) ? path : Array.from(path);
255
+ }
256
+ }
257
+
258
+ function definePropSafe(obj, key, value) {
259
+ Object.defineProperty(obj, key, {
260
+ value,
261
+ enumerable: true,
262
+ writable: true,
263
+ configurable: true,
264
+ });
265
+ }
266
+
267
+ function hydrateValue(raw) {
268
+ if (
269
+ raw === null ||
270
+ raw === undefined ||
271
+ typeof raw === "boolean" ||
272
+ typeof raw === "number" ||
273
+ typeof raw === "bigint" ||
274
+ typeof raw === "string"
275
+ ) {
276
+ return raw;
277
+ }
278
+ if (raw instanceof Uint8Array) {
279
+ return raw;
280
+ }
281
+ if (Array.isArray(raw)) {
282
+ return raw.map(hydrateValue);
283
+ }
284
+ if (typeof raw === "object" && typeof raw.__pklTag === "string") {
285
+ switch (raw.__pklTag) {
286
+ case "set": {
287
+ const set = new Set();
288
+ for (const item of raw.items) {
289
+ set.add(hydrateValue(item));
290
+ }
291
+ return set;
292
+ }
293
+ case "map": {
294
+ const map = new Map();
295
+ for (const [k, v] of raw.entries) {
296
+ map.set(hydrateValue(k), hydrateValue(v));
297
+ }
298
+ return map;
299
+ }
300
+ case "duration":
301
+ return new PklDuration(raw.value, raw.unit);
302
+ case "dataSize":
303
+ return new PklDataSize(raw.value, raw.unit);
304
+ case "regex":
305
+ return new PklRegex(raw.pattern);
306
+ case "pair":
307
+ return new PklPair(hydrateValue(raw.first), hydrateValue(raw.second));
308
+ case "object": {
309
+ const properties = {};
310
+ for (const [k, v] of raw.properties) {
311
+ definePropSafe(properties, k, hydrateValue(v));
312
+ }
313
+ const entries = new Map();
314
+ for (const [k, v] of raw.entries) {
315
+ entries.set(hydrateValue(k), hydrateValue(v));
316
+ }
317
+ const elements = raw.elements.map(hydrateValue);
318
+ return new PklObject(raw.className, raw.moduleUri, properties, entries, elements);
319
+ }
320
+ case "class":
321
+ return new PklClass(raw.name, raw.moduleUri);
322
+ case "typeAlias":
323
+ return new PklTypeAlias(raw.name, raw.moduleUri);
324
+ case "intSeq":
325
+ return new PklIntSeq(raw.start, raw.end, raw.step);
326
+ case "function":
327
+ return new PklFunction();
328
+ case "reference":
329
+ return new PklReference(
330
+ hydrateValue(raw.domain),
331
+ hydrateValue(raw.data),
332
+ raw.path.map(hydrateValue),
333
+ );
334
+ default:
335
+ throw new PklError(`Unknown Pkl tag: ${raw.__pklTag}`, "decode");
336
+ }
337
+ }
338
+ return raw;
339
+ }
340
+
341
+ function hydrateSchema(schema) {
342
+ if (!schema || typeof schema !== "object") return schema;
343
+ if (Array.isArray(schema.annotations)) {
344
+ schema.annotations = schema.annotations.map(hydrateValue);
345
+ }
346
+ if (schema.supermodule) {
347
+ hydrateSchema(schema.supermodule);
348
+ }
349
+ const hydrateClass = (cls) => {
350
+ if (!cls) return;
351
+ if (Array.isArray(cls.annotations)) {
352
+ cls.annotations = cls.annotations.map(hydrateValue);
353
+ }
354
+ for (const mapName of ["properties", "allProperties", "methods", "allMethods"]) {
355
+ const m = cls[mapName];
356
+ if (m && typeof m === "object") {
357
+ for (const member of Object.values(m)) {
358
+ if (member && Array.isArray(member.annotations)) {
359
+ member.annotations = member.annotations.map(hydrateValue);
360
+ }
361
+ }
362
+ }
363
+ }
364
+ };
365
+ hydrateClass(schema.moduleClass);
366
+ for (const mapName of ["classes", "allClasses"]) {
367
+ const m = schema[mapName];
368
+ if (m && typeof m === "object") {
369
+ for (const cls of Object.values(m)) {
370
+ hydrateClass(cls);
371
+ }
372
+ }
373
+ }
374
+ for (const mapName of ["typeAliases", "allTypeAliases"]) {
375
+ const m = schema[mapName];
376
+ if (m && typeof m === "object") {
377
+ for (const alias of Object.values(m)) {
378
+ if (alias && Array.isArray(alias.annotations)) {
379
+ alias.annotations = alias.annotations.map(hydrateValue);
380
+ }
381
+ }
382
+ }
383
+ }
384
+ return schema;
385
+ }
386
+
387
+ function dehydrateValue(val) {
388
+ if (val === null) return null;
389
+ if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") {
390
+ return val;
391
+ }
392
+ if (typeof val === "bigint") {
393
+ if (val < MIN_I64 || val > MAX_I64) {
394
+ throw new PklError(
395
+ `BigInt ${val} is outside signed 64-bit integer range (${MIN_I64}..=${MAX_I64}).`,
396
+ "invalid-argument",
397
+ );
398
+ }
399
+ return val;
400
+ }
401
+ if (val instanceof Uint8Array) {
402
+ return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
403
+ }
404
+ if (Array.isArray(val)) {
405
+ return val.map(dehydrateValue);
406
+ }
407
+ if (val instanceof Set) {
408
+ return { __pklTag: "set", items: Array.from(val, dehydrateValue) };
409
+ }
410
+ if (val instanceof Map) {
411
+ return {
412
+ __pklTag: "map",
413
+ entries: Array.from(val.entries(), ([k, v]) => [dehydrateValue(k), dehydrateValue(v)]),
414
+ };
415
+ }
416
+ if (val instanceof PklDuration) {
417
+ return { __pklTag: "duration", value: val.value, unit: val.unit };
418
+ }
419
+ if (val instanceof PklDataSize) {
420
+ return { __pklTag: "dataSize", value: val.value, unit: val.unit };
421
+ }
422
+ if (val instanceof PklRegex) {
423
+ return { __pklTag: "regex", pattern: val.pattern };
424
+ }
425
+ if (val instanceof PklPair) {
426
+ return {
427
+ __pklTag: "pair",
428
+ first: dehydrateValue(val.first),
429
+ second: dehydrateValue(val.second),
430
+ };
431
+ }
432
+ if (val instanceof PklObject) {
433
+ const properties = Object.entries(val.properties).map(([k, v]) => [k, dehydrateValue(v)]);
434
+ const entries = Array.from(val.entries.entries(), ([k, v]) => [
435
+ dehydrateValue(k),
436
+ dehydrateValue(v),
437
+ ]);
438
+ const elements = val.elements.map(dehydrateValue);
439
+ return {
440
+ __pklTag: "object",
441
+ className: val.className,
442
+ moduleUri: val.moduleUri,
443
+ properties,
444
+ entries,
445
+ elements,
446
+ };
447
+ }
448
+ if (val instanceof PklClass) {
449
+ return { __pklTag: "class", name: val.name, moduleUri: val.moduleUri };
450
+ }
451
+ if (val instanceof PklTypeAlias) {
452
+ return { __pklTag: "typeAlias", name: val.name, moduleUri: val.moduleUri };
453
+ }
454
+ if (val instanceof PklIntSeq) {
455
+ return {
456
+ __pklTag: "intSeq",
457
+ start: dehydrateValue(val.start),
458
+ end: dehydrateValue(val.end),
459
+ step: dehydrateValue(val.step),
460
+ };
461
+ }
462
+ if (val instanceof PklFunction) {
463
+ return { __pklTag: "function" };
464
+ }
465
+ if (val instanceof PklReference) {
466
+ return {
467
+ __pklTag: "reference",
468
+ domain: dehydrateValue(val.domain),
469
+ data: dehydrateValue(val.data),
470
+ path: val.path.map(dehydrateValue),
471
+ };
472
+ }
473
+ if (typeof val === "object") {
474
+ const properties = Object.entries(val).map(([k, v]) => [k, dehydrateValue(v)]);
475
+ return {
476
+ __pklTag: "object",
477
+ className: "Dynamic",
478
+ moduleUri: "pkl:base",
479
+ properties,
480
+ entries: [],
481
+ elements: [],
482
+ };
483
+ }
484
+ throw new PklError(`Unsupported JS value type for Pkl conversion: ${typeof val}`, "invalid-argument");
485
+ }
486
+
487
+ function parseTimeoutMs(value) {
488
+ if (value === undefined || value === null) return undefined;
489
+ if (typeof value === "bigint") {
490
+ if (value < 0n || value > MAX_U64) {
491
+ throw new PklError(
492
+ `timeoutMs must be an unsigned 64-bit integer (0..=${MAX_U64}), got ${value}.`,
493
+ "invalid-argument",
494
+ );
495
+ }
496
+ return value;
497
+ }
498
+ if (typeof value === "number") {
499
+ if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value) || value < 0) {
500
+ throw new PklError(
501
+ `timeoutMs must be a non-negative safe integer or unsigned 64-bit BigInt, got ${value}.`,
502
+ "invalid-argument",
503
+ );
504
+ }
505
+ return BigInt(value);
506
+ }
507
+ throw new PklError(
508
+ `timeoutMs must be a number or bigint, got ${typeof value}.`,
509
+ "invalid-argument",
510
+ );
511
+ }
512
+
513
+ function toKeyValueList(input, fieldName) {
514
+ if (input === undefined || input === null) return undefined;
515
+ const out = [];
516
+ if (input instanceof Map) {
517
+ for (const [k, v] of input.entries()) {
518
+ if (v === undefined) continue;
519
+ out.push({ key: String(k), value: String(v) });
520
+ }
521
+ return out;
522
+ }
523
+ if (typeof input === "object" && !Array.isArray(input)) {
524
+ for (const [k, v] of Object.entries(input)) {
525
+ if (v === undefined) continue;
526
+ out.push({ key: k, value: String(v) });
527
+ }
528
+ return out;
529
+ }
530
+ throw new PklError(`${fieldName} must be an object or Map.`, "invalid-argument");
531
+ }
532
+
533
+ function decodeU16(arr) {
534
+ if (!arr || arr.length === 0) return "";
535
+ const CHUNK = 8192;
536
+ if (arr.length <= CHUNK) {
537
+ return String.fromCharCode(...arr);
538
+ }
539
+ let out = "";
540
+ for (let i = 0; i < arr.length; i += CHUNK) {
541
+ out += String.fromCharCode(...arr.subarray(i, Math.min(i + CHUNK, arr.length)));
542
+ }
543
+ return out;
544
+ }
545
+
546
+ function decodeBridgeFrame(frame) {
547
+ if (!frame) return undefined;
548
+ return {
549
+ moduleUri: decodeU16(frame.moduleUriU16),
550
+ memberName: frame.memberNameU16 ? decodeU16(frame.memberNameU16) : null,
551
+ sourceLines: (frame.sourceLinesU16 || []).map(decodeU16),
552
+ startLine: frame.startLine,
553
+ startColumn: frame.startColumn,
554
+ endLine: frame.endLine,
555
+ endColumn: frame.endColumn,
556
+ };
557
+ }
558
+
559
+ function normalizeColorOption(color) {
560
+ if (color === undefined || color === null) return undefined;
561
+ if (typeof color === "boolean") return color ? "always" : "never";
562
+ if (typeof color === "string") {
563
+ const lower = color.toLowerCase();
564
+ if (lower === "never" || lower === "auto" || lower === "always") {
565
+ return lower;
566
+ }
567
+ }
568
+ throw new PklError(
569
+ `Invalid color option "${color}". Expected boolean or "never" | "auto" | "always".`,
570
+ "invalid-argument",
571
+ );
572
+ }
573
+
574
+ function buildNativeOptions(options = {}) {
575
+ if (options !== undefined && options !== null && typeof options !== "object") {
576
+ throw new PklError("EvaluatorOptions must be an object.", "invalid-argument");
577
+ }
578
+ const opts = options || {};
579
+ const nativeOpts = {};
580
+
581
+ if (opts.allowedModules !== undefined) {
582
+ if (!Array.isArray(opts.allowedModules)) {
583
+ throw new PklError("allowedModules must be an array of strings.", "invalid-argument");
584
+ }
585
+ nativeOpts.allowedModules = opts.allowedModules.map(String);
586
+ }
587
+ if (opts.allowedResources !== undefined) {
588
+ if (!Array.isArray(opts.allowedResources)) {
589
+ throw new PklError("allowedResources must be an array of strings.", "invalid-argument");
590
+ }
591
+ nativeOpts.allowedResources = opts.allowedResources.map(String);
592
+ }
593
+ if (opts.rootDir !== undefined && opts.rootDir !== null) {
594
+ nativeOpts.rootDir = String(opts.rootDir);
595
+ }
596
+ if (opts.workingDir !== undefined && opts.workingDir !== null) {
597
+ nativeOpts.workingDir = String(opts.workingDir);
598
+ }
599
+ if (opts.modulePaths !== undefined) {
600
+ if (!Array.isArray(opts.modulePaths)) {
601
+ throw new PklError("modulePaths must be an array of paths.", "invalid-argument");
602
+ }
603
+ nativeOpts.modulePaths = opts.modulePaths.map(String);
604
+ }
605
+ if (opts.properties !== undefined) {
606
+ nativeOpts.properties = toKeyValueList(opts.properties, "properties");
607
+ }
608
+ if (opts.env !== undefined) {
609
+ nativeOpts.env = toKeyValueList(opts.env, "env");
610
+ } else if (opts.project === undefined && opts.projectDir === undefined) {
611
+ // Default to current Node process.env when neither explicit env nor project overrides it.
612
+ nativeOpts.env = toKeyValueList(process.env, "env");
613
+ }
614
+ if (opts.outputFormat !== undefined && opts.outputFormat !== null) {
615
+ nativeOpts.outputFormat = String(opts.outputFormat);
616
+ }
617
+ if (opts.traceMode !== undefined && opts.traceMode !== null) {
618
+ if (opts.traceMode !== "compact" && opts.traceMode !== "pretty") {
619
+ throw new PklError(
620
+ `Invalid traceMode "${opts.traceMode}". Expected "compact" or "pretty".`,
621
+ "invalid-argument",
622
+ );
623
+ }
624
+ nativeOpts.traceMode = opts.traceMode;
625
+ }
626
+ if (opts.powerAssertions !== undefined) {
627
+ nativeOpts.powerAssertions = Boolean(opts.powerAssertions);
628
+ }
629
+ const color = normalizeColorOption(opts.color);
630
+ if (color !== undefined) {
631
+ nativeOpts.color = color;
632
+ }
633
+ const timeoutMs = parseTimeoutMs(opts.timeoutMs);
634
+ if (timeoutMs !== undefined) {
635
+ nativeOpts.timeoutMs = timeoutMs;
636
+ }
637
+ if (opts.noCache === true || opts.cacheDir === null) {
638
+ nativeOpts.noCache = true;
639
+ } else if (opts.cacheDir !== undefined) {
640
+ nativeOpts.cacheDir = String(opts.cacheDir);
641
+ }
642
+ if (opts.projectDir !== undefined && opts.projectDir !== null) {
643
+ nativeOpts.projectDir = String(opts.projectDir);
644
+ }
645
+ if (opts.testMode !== undefined) {
646
+ nativeOpts.testMode = Boolean(opts.testMode);
647
+ }
648
+
649
+ if (opts.http !== undefined && opts.http !== null) {
650
+ const http = opts.http;
651
+ const nativeHttp = {};
652
+ const certFiles = [];
653
+ const certPems = [];
654
+ if (Array.isArray(http.caCertificates)) {
655
+ for (const cert of http.caCertificates) {
656
+ if (cert instanceof Uint8Array) {
657
+ certPems.push(new Uint8Array(cert.buffer, cert.byteOffset, cert.byteLength));
658
+ } else if (typeof cert === "string") {
659
+ if (cert.includes("-----BEGIN")) {
660
+ certPems.push(Buffer.from(cert, "utf8"));
661
+ } else {
662
+ certFiles.push(cert);
663
+ }
664
+ } else {
665
+ throw new PklError(
666
+ "http.caCertificates entries must be file paths, PEM strings, or Uint8Array.",
667
+ "invalid-argument",
668
+ );
669
+ }
670
+ }
671
+ }
672
+ if (Array.isArray(http.caCertificateFiles)) {
673
+ for (const filePath of http.caCertificateFiles) {
674
+ if (typeof filePath !== "string") {
675
+ throw new PklError(
676
+ "http.caCertificateFiles entries must be file path strings.",
677
+ "invalid-argument",
678
+ );
679
+ }
680
+ certFiles.push(filePath);
681
+ }
682
+ }
683
+ if (Array.isArray(http.caCertificatePems)) {
684
+ for (const pem of http.caCertificatePems) {
685
+ if (pem instanceof Uint8Array) {
686
+ certPems.push(new Uint8Array(pem.buffer, pem.byteOffset, pem.byteLength));
687
+ } else if (typeof pem === "string") {
688
+ certPems.push(Buffer.from(pem, "utf8"));
689
+ } else {
690
+ throw new PklError(
691
+ "http.caCertificatePems entries must be PEM strings or Uint8Array.",
692
+ "invalid-argument",
693
+ );
694
+ }
695
+ }
696
+ }
697
+ if (certFiles.length > 0) nativeHttp.caCertificateFiles = certFiles;
698
+ if (certPems.length > 0) nativeHttp.caCertificatePems = certPems;
699
+ if (http.proxy !== undefined && http.proxy !== null) {
700
+ if (http.proxy.address !== undefined && http.proxy.address !== null) {
701
+ nativeHttp.proxyAddress = String(http.proxy.address);
702
+ }
703
+ if (Array.isArray(http.proxy.noProxy)) {
704
+ nativeHttp.noProxy = http.proxy.noProxy.map(String);
705
+ }
706
+ }
707
+ if (http.rewrites !== undefined && http.rewrites !== null) {
708
+ nativeHttp.rewrites = toKeyValueList(http.rewrites, "http.rewrites");
709
+ }
710
+ if (http.headers !== undefined && http.headers !== null) {
711
+ const entries = [];
712
+ for (const [urlPattern, hdrMap] of Object.entries(http.headers)) {
713
+ if (!hdrMap || typeof hdrMap !== "object") continue;
714
+ for (const [name, value] of Object.entries(hdrMap)) {
715
+ entries.push({ urlPattern, name, value: String(value) });
716
+ }
717
+ }
718
+ nativeHttp.headers = entries;
719
+ }
720
+ if (http.testPort !== undefined && http.testPort !== null) {
721
+ nativeHttp.testPort = Number(http.testPort);
722
+ }
723
+ nativeOpts.http = nativeHttp;
724
+ }
725
+
726
+ if (opts.externalModuleReaders && typeof opts.externalModuleReaders === "object") {
727
+ nativeOpts.externalModuleReaders = Object.entries(opts.externalModuleReaders).map(
728
+ ([scheme, cfg]) => ({
729
+ scheme: scheme.replace(/:$/, ""),
730
+ executable: String(cfg.executable),
731
+ arguments: Array.isArray(cfg.arguments) ? cfg.arguments.map(String) : [],
732
+ }),
733
+ );
734
+ }
735
+ if (opts.externalResourceReaders && typeof opts.externalResourceReaders === "object") {
736
+ nativeOpts.externalResourceReaders = Object.entries(opts.externalResourceReaders).map(
737
+ ([scheme, cfg]) => ({
738
+ scheme: scheme.replace(/:$/, ""),
739
+ executable: String(cfg.executable),
740
+ arguments: Array.isArray(cfg.arguments) ? cfg.arguments.map(String) : [],
741
+ }),
742
+ );
743
+ }
744
+
745
+ const moduleReaders = Array.isArray(opts.moduleReaders) ? opts.moduleReaders : [];
746
+ if (moduleReaders.length > 0) {
747
+ nativeOpts.moduleReaders = moduleReaders.map((r, index) => {
748
+ if (!r || typeof r.scheme !== "string" || typeof r.read !== "function") {
749
+ throw new PklError(
750
+ `moduleReaders[${index}] must have string scheme and read() function.`,
751
+ "invalid-argument",
752
+ );
753
+ }
754
+ return {
755
+ index,
756
+ scheme: r.scheme.replace(/:$/, ""),
757
+ isLocal: Boolean(r.isLocal),
758
+ isGlobbable: Boolean(r.isGlobbable),
759
+ hasHierarchicalUris: Boolean(r.hasHierarchicalUris),
760
+ isCached: r.isCached === undefined ? true : Boolean(r.isCached),
761
+ hasHasElement: typeof r.hasElement === "function",
762
+ hasListElements: typeof r.listElements === "function",
763
+ };
764
+ });
765
+ }
766
+
767
+ const resourceReaders = Array.isArray(opts.resourceReaders) ? opts.resourceReaders : [];
768
+ if (resourceReaders.length > 0) {
769
+ nativeOpts.resourceReaders = resourceReaders.map((r, index) => {
770
+ if (!r || typeof r.scheme !== "string" || typeof r.read !== "function") {
771
+ throw new PklError(
772
+ `resourceReaders[${index}] must have string scheme and read() function.`,
773
+ "invalid-argument",
774
+ );
775
+ }
776
+ return {
777
+ index,
778
+ scheme: r.scheme.replace(/:$/, ""),
779
+ isGlobbable: Boolean(r.isGlobbable),
780
+ hasHierarchicalUris: Boolean(r.hasHierarchicalUris),
781
+ hasHasElement: typeof r.hasElement === "function",
782
+ hasListElements: typeof r.listElements === "function",
783
+ };
784
+ });
785
+ }
786
+
787
+ const logger = opts.logger || null;
788
+ if (logger !== null) {
789
+ nativeOpts.hasCustomLogger = true;
790
+ nativeOpts.hasLoggerTrace = typeof logger.trace === "function";
791
+ nativeOpts.hasLoggerWarn = typeof logger.warn === "function";
792
+ }
793
+
794
+ const frameTransformer = typeof opts.frameTransformer === "function" ? opts.frameTransformer : null;
795
+ if (frameTransformer) {
796
+ nativeOpts.hasFrameTransformer = true;
797
+ }
798
+
799
+ const securityManager = opts.securityManager || null;
800
+ if (securityManager) {
801
+ nativeOpts.hasSecurityResolveModule = typeof securityManager.checkResolveModule === "function";
802
+ nativeOpts.hasSecurityImportModule = typeof securityManager.checkImportModule === "function";
803
+ nativeOpts.hasSecurityReadResource = typeof securityManager.checkReadResource === "function";
804
+ nativeOpts.hasSecurityResolveResource =
805
+ typeof securityManager.checkResolveResource === "function";
806
+ }
807
+
808
+ const hasCallbacks = Boolean(
809
+ logger ||
810
+ frameTransformer ||
811
+ (securityManager &&
812
+ (nativeOpts.hasSecurityResolveModule ||
813
+ nativeOpts.hasSecurityImportModule ||
814
+ nativeOpts.hasSecurityReadResource ||
815
+ nativeOpts.hasSecurityResolveResource)) ||
816
+ moduleReaders.length > 0 ||
817
+ resourceReaders.length > 0,
818
+ );
819
+
820
+ let nativeProject = undefined;
821
+ if (opts.project !== undefined && opts.project !== null) {
822
+ if (opts.project instanceof Project && opts.project._native) {
823
+ nativeProject = opts.project._native;
824
+ } else {
825
+ throw new PklError("options.project must be a Project instance.", "invalid-argument");
826
+ }
827
+ }
828
+
829
+ let bridgeTarget = null;
830
+ const setBridgeTarget = (target) => {
831
+ bridgeTarget = target;
832
+ };
833
+
834
+ const bridgeCallback = hasCallbacks
835
+ ? (req) => {
836
+ void (async () => {
837
+ const target = bridgeTarget;
838
+ if (!target) return;
839
+ try {
840
+ const payload = await dispatchBridgeRequest(req, {
841
+ logger,
842
+ frameTransformer,
843
+ securityManager,
844
+ moduleReaders,
845
+ resourceReaders,
846
+ });
847
+ target.completeBridgeCallback(req.id, { ok: true, ...payload });
848
+ } catch (err) {
849
+ const isSecurity = err instanceof PklError && err.kind === "security";
850
+ const isIo = err instanceof PklError && err.kind === "io";
851
+ const msg = err instanceof Error ? err.message : String(err);
852
+ target.completeBridgeCallback(req.id, {
853
+ ok: false,
854
+ errorKind: isSecurity ? "security" : isIo ? "io" : "evaluation",
855
+ errorMessage: msg,
856
+ });
857
+ }
858
+ })();
859
+ }
860
+ : undefined;
861
+
862
+ return {
863
+ nativeOpts,
864
+ nativeProject,
865
+ bridgeCallback,
866
+ setBridgeTarget,
867
+ signal: opts.signal,
868
+ };
869
+ }
870
+
871
+ async function dispatchBridgeRequest(req, hooks) {
872
+ switch (req.op) {
873
+ case "log": {
874
+ const msg = decodeU16(req.messageU16);
875
+ const frame = decodeBridgeFrame(req.frame);
876
+ if (req.level === "trace" && hooks.logger && typeof hooks.logger.trace === "function") {
877
+ await hooks.logger.trace(msg, frame);
878
+ } else if (req.level === "warn" && hooks.logger && typeof hooks.logger.warn === "function") {
879
+ await hooks.logger.warn(msg, frame);
880
+ }
881
+ return {};
882
+ }
883
+ case "transformFrame": {
884
+ const frame = decodeBridgeFrame(req.frame);
885
+ const transformed = await hooks.frameTransformer(frame);
886
+ if (!transformed || typeof transformed !== "object") {
887
+ return {};
888
+ }
889
+ return {
890
+ frame: {
891
+ moduleUri: String(transformed.moduleUri ?? frame.moduleUri),
892
+ memberName:
893
+ transformed.memberName === undefined
894
+ ? frame.memberName
895
+ : transformed.memberName === null
896
+ ? undefined
897
+ : String(transformed.memberName),
898
+ sourceLines: Array.isArray(transformed.sourceLines)
899
+ ? transformed.sourceLines.map(String)
900
+ : frame.sourceLines,
901
+ startLine: Number(transformed.startLine ?? frame.startLine),
902
+ startColumn: Number(transformed.startColumn ?? frame.startColumn),
903
+ endLine: Number(transformed.endLine ?? frame.endLine),
904
+ endColumn: Number(transformed.endColumn ?? frame.endColumn),
905
+ },
906
+ };
907
+ }
908
+ case "checkResolveModule": {
909
+ await hooks.securityManager.checkResolveModule(decodeU16(req.uriU16));
910
+ return {};
911
+ }
912
+ case "checkImportModule": {
913
+ await hooks.securityManager.checkImportModule(
914
+ decodeU16(req.uriU16),
915
+ decodeU16(req.uri2U16),
916
+ );
917
+ return {};
918
+ }
919
+ case "checkReadResource": {
920
+ await hooks.securityManager.checkReadResource(decodeU16(req.uriU16));
921
+ return {};
922
+ }
923
+ case "checkResolveResource": {
924
+ await hooks.securityManager.checkResolveResource(decodeU16(req.uriU16));
925
+ return {};
926
+ }
927
+ case "moduleRead": {
928
+ const reader = hooks.moduleReaders[req.readerIndex];
929
+ const text = await reader.read(decodeU16(req.uriU16));
930
+ if (text === null || text === undefined) {
931
+ return { text: undefined };
932
+ }
933
+ return { text: String(text) };
934
+ }
935
+ case "moduleHasElement": {
936
+ const reader = hooks.moduleReaders[req.readerIndex];
937
+ const exists = await reader.hasElement(decodeU16(req.uriU16));
938
+ return { boolValue: Boolean(exists) };
939
+ }
940
+ case "moduleListElements": {
941
+ const reader = hooks.moduleReaders[req.readerIndex];
942
+ const elements = await reader.listElements(decodeU16(req.uriU16));
943
+ return {
944
+ elements: Array.isArray(elements)
945
+ ? elements.map((el) => ({
946
+ name: String(el.name),
947
+ isDirectory: Boolean(el.isDirectory),
948
+ }))
949
+ : [],
950
+ };
951
+ }
952
+ case "resourceRead": {
953
+ const reader = hooks.resourceReaders[req.readerIndex];
954
+ const value = await reader.read(decodeU16(req.uriU16));
955
+ if (value === null || value === undefined) {
956
+ return { missing: true };
957
+ }
958
+ if (value instanceof Uint8Array) {
959
+ return { bytes: new Uint8Array(value.buffer, value.byteOffset, value.byteLength) };
960
+ }
961
+ if (typeof value === "string") {
962
+ return { text: value };
963
+ }
964
+ if (typeof value === "object" && value.bytes instanceof Uint8Array) {
965
+ return {
966
+ bytes: new Uint8Array(value.bytes.buffer, value.bytes.byteOffset, value.bytes.byteLength),
967
+ };
968
+ }
969
+ if (typeof value === "object" && typeof value.text === "string") {
970
+ return { text: value.text };
971
+ }
972
+ throw new PklError(
973
+ `ResourceReader.read must return Uint8Array, string, null, or undefined.`,
974
+ "invalid-argument",
975
+ );
976
+ }
977
+ case "resourceHasElement": {
978
+ const reader = hooks.resourceReaders[req.readerIndex];
979
+ const exists = await reader.hasElement(decodeU16(req.uriU16));
980
+ return { boolValue: Boolean(exists) };
981
+ }
982
+ case "resourceListElements": {
983
+ const reader = hooks.resourceReaders[req.readerIndex];
984
+ const elements = await reader.listElements(decodeU16(req.uriU16));
985
+ return {
986
+ elements: Array.isArray(elements)
987
+ ? elements.map((el) => ({
988
+ name: String(el.name),
989
+ isDirectory: Boolean(el.isDirectory),
990
+ }))
991
+ : [],
992
+ };
993
+ }
994
+ default:
995
+ throw new PklError(`Unknown bridge callback op: ${req.op}`, "evaluation");
996
+ }
997
+ }
998
+
999
+ class Project {
1000
+ constructor(nativeProject) {
1001
+ this._native = nativeProject;
1002
+ const info = nativeProject.info();
1003
+ this.projectDir = info.projectDir;
1004
+ this.projectFileUri = info.projectFileUri;
1005
+ this.projectBaseUri = info.projectBaseUri;
1006
+ this.package = info.package;
1007
+ this.evaluatorSettings = info.evaluatorSettings;
1008
+ this.tests = info.tests;
1009
+ Object.freeze(this);
1010
+ }
1011
+
1012
+ static async load(dirOrFile, options = undefined) {
1013
+ if (typeof dirOrFile !== "string" || dirOrFile.length === 0) {
1014
+ throw new PklError("Project.load requires a directory or file path.", "invalid-argument");
1015
+ }
1016
+ const env = options?.env !== undefined ? toKeyValueList(options.env, "env") : undefined;
1017
+ const props =
1018
+ options?.properties !== undefined
1019
+ ? toKeyValueList(options.properties, "properties")
1020
+ : undefined;
1021
+ const outcome = await native.NativeProject.load(dirOrFile, env, props);
1022
+ return new Project(unwrapOutcome(outcome));
1023
+ }
1024
+
1025
+ static loadSync(dirOrFile, options = undefined) {
1026
+ if (typeof dirOrFile !== "string" || dirOrFile.length === 0) {
1027
+ throw new PklError("Project.loadSync requires a directory or file path.", "invalid-argument");
1028
+ }
1029
+ const env = options?.env !== undefined ? toKeyValueList(options.env, "env") : undefined;
1030
+ const props =
1031
+ options?.properties !== undefined
1032
+ ? toKeyValueList(options.properties, "properties")
1033
+ : undefined;
1034
+ const outcome = native.NativeProject.loadSync(dirOrFile, env, props);
1035
+ return new Project(unwrapOutcome(outcome));
1036
+ }
1037
+ }
1038
+
1039
+ class Evaluator {
1040
+ constructor(nativeEval, signal = undefined) {
1041
+ this._native = nativeEval;
1042
+ this._closed = false;
1043
+ this._closePromise = null;
1044
+ this._nextCallId = 1n;
1045
+ this._signal = signal || null;
1046
+ this._onAbort = null;
1047
+ if (this._signal && !this._signal.aborted) {
1048
+ this._onAbort = () => {
1049
+ this.cancel();
1050
+ };
1051
+ this._signal.addEventListener("abort", this._onAbort, { once: true });
1052
+ }
1053
+ }
1054
+
1055
+ get isClosed() {
1056
+ return this._closed || this._native.isClosed;
1057
+ }
1058
+
1059
+ cancel() {
1060
+ if (!this._closed) {
1061
+ this._native.cancel();
1062
+ }
1063
+ }
1064
+
1065
+ close() {
1066
+ if (this._closed) {
1067
+ return this._closePromise || Promise.resolve();
1068
+ }
1069
+ this._closed = true;
1070
+ if (this._signal && this._onAbort) {
1071
+ this._signal.removeEventListener("abort", this._onAbort);
1072
+ this._onAbort = null;
1073
+ }
1074
+ const closedImmediately = this._native.closeNow();
1075
+ if (closedImmediately) {
1076
+ this._closePromise = Promise.resolve();
1077
+ return this._closePromise;
1078
+ }
1079
+ this._closePromise = this._native.closeAsync();
1080
+ return this._closePromise;
1081
+ }
1082
+
1083
+ async _runAsync(callOptions, invoke) {
1084
+ if (this.isClosed) {
1085
+ throw new PklError("Evaluator has been closed.", "closed");
1086
+ }
1087
+ const callSignal = callOptions?.signal;
1088
+ if (this._signal?.aborted || callSignal?.aborted) {
1089
+ throw new PklError("Evaluation was cancelled.", "cancelled");
1090
+ }
1091
+ const timeoutMs = parseTimeoutMs(callOptions?.timeoutMs);
1092
+ const callId = this._nextCallId++;
1093
+ let onCallAbort = null;
1094
+ if (callSignal) {
1095
+ onCallAbort = () => {
1096
+ this._native.cancelCall(callId);
1097
+ };
1098
+ callSignal.addEventListener("abort", onCallAbort, { once: true });
1099
+ }
1100
+ try {
1101
+ const outcome = await invoke(timeoutMs, callId);
1102
+ return unwrapOutcome(outcome);
1103
+ } finally {
1104
+ if (callSignal && onCallAbort) {
1105
+ callSignal.removeEventListener("abort", onCallAbort);
1106
+ }
1107
+ }
1108
+ }
1109
+
1110
+ _runSync(callOptions, invoke) {
1111
+ if (this.isClosed) {
1112
+ throw new PklError("Evaluator has been closed.", "closed");
1113
+ }
1114
+ if (this._signal?.aborted || callOptions?.signal?.aborted) {
1115
+ throw new PklError("Evaluation was cancelled.", "cancelled");
1116
+ }
1117
+ const timeoutMs = parseTimeoutMs(callOptions?.timeoutMs);
1118
+ return unwrapOutcome(invoke(timeoutMs));
1119
+ }
1120
+
1121
+ async evaluateOutputText(source, callOptions = undefined) {
1122
+ const { uri, contents } = normalizeSource(source);
1123
+ if (
1124
+ !this.isClosed &&
1125
+ !this._signal?.aborted &&
1126
+ !callOptions?.signal &&
1127
+ callOptions?.timeoutMs === undefined
1128
+ ) {
1129
+ const fast = this._native.tryEvaluateOutputTextFast(uri, contents);
1130
+ if (fast !== null && fast !== undefined) {
1131
+ if (fast.__continueAsync) {
1132
+ return this._runAsync(callOptions, (t, id) =>
1133
+ this._native.continuePendingFast(false, t, id),
1134
+ );
1135
+ }
1136
+ return unwrapOutcome(fast);
1137
+ }
1138
+ }
1139
+ return this._runAsync(callOptions, (t, id) =>
1140
+ this._native.evaluateOutputText(uri, contents, t, id),
1141
+ );
1142
+ }
1143
+
1144
+ evaluateOutputTextSync(source, callOptions = undefined) {
1145
+ const { uri, contents } = normalizeSource(source);
1146
+ return this._runSync(callOptions, (t) =>
1147
+ this._native.evaluateOutputTextSync(uri, contents, t),
1148
+ );
1149
+ }
1150
+
1151
+ async evaluateOutputBytes(source, callOptions = undefined) {
1152
+ const { uri, contents } = normalizeSource(source);
1153
+ return this._runAsync(callOptions, (t, id) =>
1154
+ this._native.evaluateOutputBytes(uri, contents, t, id),
1155
+ );
1156
+ }
1157
+
1158
+ evaluateOutputBytesSync(source, callOptions = undefined) {
1159
+ const { uri, contents } = normalizeSource(source);
1160
+ return this._runSync(callOptions, (t) =>
1161
+ this._native.evaluateOutputBytesSync(uri, contents, t),
1162
+ );
1163
+ }
1164
+
1165
+ async evaluateOutputFiles(source, callOptions = undefined) {
1166
+ const { uri, contents } = normalizeSource(source);
1167
+ const entries = await this._runAsync(callOptions, (t, id) =>
1168
+ this._native.evaluateOutputFiles(uri, contents, t, id),
1169
+ );
1170
+ const out = new Map();
1171
+ for (const entry of entries) {
1172
+ out.set(entry.path, entry.bytes);
1173
+ }
1174
+ return out;
1175
+ }
1176
+
1177
+ evaluateOutputFilesSync(source, callOptions = undefined) {
1178
+ const { uri, contents } = normalizeSource(source);
1179
+ const entries = this._runSync(callOptions, (t) =>
1180
+ this._native.evaluateOutputFilesSync(uri, contents, t),
1181
+ );
1182
+ const out = new Map();
1183
+ for (const entry of entries) {
1184
+ out.set(entry.path, entry.bytes);
1185
+ }
1186
+ return out;
1187
+ }
1188
+
1189
+ async evaluateOutputValue(source, callOptions = undefined) {
1190
+ return this.evaluateExpressionValue(source, "output.value", callOptions);
1191
+ }
1192
+
1193
+ evaluateOutputValueSync(source, callOptions = undefined) {
1194
+ const bytes = this.evaluateExpressionPklBinarySync(source, "output.value", callOptions);
1195
+ return decodePklBinary(bytes);
1196
+ }
1197
+
1198
+ async evaluateExpression(source, expr, callOptions = undefined) {
1199
+ const { uri, contents } = normalizeSource(source);
1200
+ if (typeof expr !== "string") {
1201
+ throw new PklError("Expression must be a string.", "invalid-argument");
1202
+ }
1203
+ if (
1204
+ !this.isClosed &&
1205
+ !this._signal?.aborted &&
1206
+ !callOptions?.signal &&
1207
+ callOptions?.timeoutMs === undefined
1208
+ ) {
1209
+ const fast = this._native.tryEvaluateExpressionFast(uri, contents, expr);
1210
+ if (fast !== null && fast !== undefined) {
1211
+ if (fast.__continueAsync) {
1212
+ return this._runAsync(callOptions, (t, id) =>
1213
+ this._native.continuePendingFast(false, t, id),
1214
+ );
1215
+ }
1216
+ return unwrapOutcome(fast);
1217
+ }
1218
+ }
1219
+ return this._runAsync(callOptions, (t, id) =>
1220
+ this._native.evaluateExpression(uri, contents, expr, t, id),
1221
+ );
1222
+ }
1223
+
1224
+ evaluateExpressionSync(source, expr, callOptions = undefined) {
1225
+ const { uri, contents } = normalizeSource(source);
1226
+ if (typeof expr !== "string") {
1227
+ throw new PklError("Expression must be a string.", "invalid-argument");
1228
+ }
1229
+ return this._runSync(callOptions, (t) =>
1230
+ this._native.evaluateExpressionSync(uri, contents, expr, t),
1231
+ );
1232
+ }
1233
+
1234
+ async evaluateExpressionValue(source, expr, callOptions = undefined) {
1235
+ const { uri, contents } = normalizeSource(source);
1236
+ if (typeof expr !== "string") {
1237
+ throw new PklError("Expression must be a string.", "invalid-argument");
1238
+ }
1239
+ if (
1240
+ !this.isClosed &&
1241
+ !this._signal?.aborted &&
1242
+ !callOptions?.signal &&
1243
+ callOptions?.timeoutMs === undefined
1244
+ ) {
1245
+ if (expr === "module" || expr === "output.value") {
1246
+ const colBuf = this._native.tryEvaluateExpressionColumnarFast(uri, contents, expr);
1247
+ if (colBuf !== null && colBuf !== undefined) {
1248
+ const unpacked = unpackColumnarBuffer(colBuf);
1249
+ if (unpacked !== DECODE_FALLBACK) {
1250
+ return unpacked;
1251
+ }
1252
+ }
1253
+ }
1254
+ const fast = this._native.tryEvaluateExpressionPklBinaryFast(uri, contents, expr);
1255
+ if (fast !== null && fast !== undefined) {
1256
+ if (fast.__continueAsync) {
1257
+ const bytes = await this._runAsync(callOptions, (t, id) =>
1258
+ this._native.continuePendingFast(true, t, id),
1259
+ );
1260
+ return decodePklBinary(bytes);
1261
+ }
1262
+ return decodePklBinary(unwrapOutcome(fast));
1263
+ }
1264
+ }
1265
+ const bytes = await this._runAsync(callOptions, (t, id) =>
1266
+ this._native.evaluateExpressionPklBinary(uri, contents, expr, t, id),
1267
+ );
1268
+ return decodePklBinary(bytes);
1269
+ }
1270
+
1271
+ evaluateExpressionValueSync(source, expr, callOptions = undefined) {
1272
+ const bytes = this.evaluateExpressionPklBinarySync(source, expr, callOptions);
1273
+ return decodePklBinary(bytes);
1274
+ }
1275
+
1276
+ async evaluateExpressionPklBinary(source, expr, callOptions = undefined) {
1277
+ const { uri, contents } = normalizeSource(source);
1278
+ if (typeof expr !== "string") {
1279
+ throw new PklError("Expression must be a string.", "invalid-argument");
1280
+ }
1281
+ if (
1282
+ !this.isClosed &&
1283
+ !this._signal?.aborted &&
1284
+ !callOptions?.signal &&
1285
+ callOptions?.timeoutMs === undefined
1286
+ ) {
1287
+ const fast = this._native.tryEvaluateExpressionPklBinaryFast(uri, contents, expr);
1288
+ if (fast !== null && fast !== undefined) {
1289
+ if (fast.__continueAsync) {
1290
+ return this._runAsync(callOptions, (t, id) =>
1291
+ this._native.continuePendingFast(true, t, id),
1292
+ );
1293
+ }
1294
+ const buf = unwrapOutcome(fast);
1295
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
1296
+ }
1297
+ }
1298
+ return this._runAsync(callOptions, (t, id) =>
1299
+ this._native.evaluateExpressionPklBinary(uri, contents, expr, t, id),
1300
+ );
1301
+ }
1302
+
1303
+ evaluateExpressionPklBinarySync(source, expr, callOptions = undefined) {
1304
+ const { uri, contents } = normalizeSource(source);
1305
+ if (typeof expr !== "string") {
1306
+ throw new PklError("Expression must be a string.", "invalid-argument");
1307
+ }
1308
+ return this._runSync(callOptions, (t) =>
1309
+ this._native.evaluateExpressionPklBinarySync(uri, contents, expr, t),
1310
+ );
1311
+ }
1312
+
1313
+ async evaluateSchema(source, callOptions = undefined) {
1314
+ const { uri, contents } = normalizeSource(source);
1315
+ const schema = await this._runAsync(callOptions, (t, id) =>
1316
+ this._native.evaluateSchema(uri, contents, t, id),
1317
+ );
1318
+ return hydrateSchema(schema);
1319
+ }
1320
+
1321
+ evaluateSchemaSync(source, callOptions = undefined) {
1322
+ const { uri, contents } = normalizeSource(source);
1323
+ const schema = this._runSync(callOptions, (t) =>
1324
+ this._native.evaluateSchemaSync(uri, contents, t),
1325
+ );
1326
+ return hydrateSchema(schema);
1327
+ }
1328
+
1329
+ async evaluateTest(source, testOptions = undefined) {
1330
+ const { uri, contents } = normalizeSource(source);
1331
+ const overwrite = Boolean(testOptions?.overwrite);
1332
+ const reporter = testOptions?.reporter ?? "spec";
1333
+ return this._runAsync(testOptions, (t, id) =>
1334
+ this._native.evaluateTest(uri, contents, overwrite, reporter, t, id),
1335
+ );
1336
+ }
1337
+
1338
+ evaluateTestSync(source, testOptions = undefined) {
1339
+ const { uri, contents } = normalizeSource(source);
1340
+ const overwrite = Boolean(testOptions?.overwrite);
1341
+ const reporter = testOptions?.reporter ?? "spec";
1342
+ return this._runSync(testOptions, (t) =>
1343
+ this._native.evaluateTestSync(uri, contents, overwrite, reporter, t),
1344
+ );
1345
+ }
1346
+ }
1347
+
1348
+ function createEvaluatorSync(options = undefined) {
1349
+ const { nativeOpts, nativeProject, bridgeCallback, setBridgeTarget, signal } =
1350
+ buildNativeOptions(options);
1351
+ const nativeEval = unwrapOutcome(
1352
+ native.NativeEvaluator.create(nativeOpts, nativeProject, bridgeCallback),
1353
+ );
1354
+ setBridgeTarget(nativeEval);
1355
+ return new Evaluator(nativeEval, signal);
1356
+ }
1357
+
1358
+ async function createEvaluator(options = undefined) {
1359
+ return createEvaluatorSync(options);
1360
+ }
1361
+
1362
+ class ReplSession {
1363
+ constructor(nativeRepl, signal = undefined) {
1364
+ this._native = nativeRepl;
1365
+ this._closed = false;
1366
+ this._closePromise = null;
1367
+ this._signal = signal || null;
1368
+ this._onAbort = null;
1369
+ if (this._signal && !this._signal.aborted) {
1370
+ this._onAbort = () => {
1371
+ this._native.cancel();
1372
+ };
1373
+ this._signal.addEventListener("abort", this._onAbort, { once: true });
1374
+ }
1375
+ }
1376
+
1377
+ get isClosed() {
1378
+ return this._closed || this._native.isClosed;
1379
+ }
1380
+
1381
+ _checkOpen() {
1382
+ if (this.isClosed) {
1383
+ throw new PklError("REPL session has been closed.", "closed");
1384
+ }
1385
+ if (this._signal?.aborted) {
1386
+ throw new PklError("Evaluation was cancelled.", "cancelled");
1387
+ }
1388
+ }
1389
+
1390
+ async eval(input, options = undefined) {
1391
+ this._checkOpen();
1392
+ if (typeof input !== "string") {
1393
+ throw new PklError("ReplSession.eval input must be a string.", "invalid-argument");
1394
+ }
1395
+ const force = Boolean(options?.force);
1396
+ const id = options?.id !== undefined ? String(options.id) : undefined;
1397
+ return unwrapOutcome(await this._native.eval(input, force, id));
1398
+ }
1399
+
1400
+ async load(uriOrSource, options = undefined) {
1401
+ this._checkOpen();
1402
+ let uri;
1403
+ if (typeof uriOrSource === "string") {
1404
+ uri = uriOrSource;
1405
+ } else if (uriOrSource && typeof uriOrSource === "object" && typeof uriOrSource.uri === "string") {
1406
+ uri = uriOrSource.uri;
1407
+ } else {
1408
+ throw new PklError(
1409
+ "ReplSession.load requires a URI string or ModuleSource.",
1410
+ "invalid-argument",
1411
+ );
1412
+ }
1413
+ const id = options?.id !== undefined ? String(options.id) : undefined;
1414
+ return unwrapOutcome(await this._native.load(uri, id));
1415
+ }
1416
+
1417
+ async complete(prefix, options = undefined) {
1418
+ this._checkOpen();
1419
+ if (typeof prefix !== "string") {
1420
+ throw new PklError("ReplSession.complete prefix must be a string.", "invalid-argument");
1421
+ }
1422
+ const id = options?.id !== undefined ? String(options.id) : undefined;
1423
+ return unwrapOutcome(await this._native.complete(prefix, id));
1424
+ }
1425
+
1426
+ async reset(options = undefined) {
1427
+ this._checkOpen();
1428
+ const id = options?.id !== undefined ? String(options.id) : undefined;
1429
+ unwrapOutcome(await this._native.reset(id));
1430
+ }
1431
+
1432
+ close() {
1433
+ if (this._closed) {
1434
+ return this._closePromise || Promise.resolve();
1435
+ }
1436
+ this._closed = true;
1437
+ if (this._signal && this._onAbort) {
1438
+ this._signal.removeEventListener("abort", this._onAbort);
1439
+ this._onAbort = null;
1440
+ }
1441
+ if (this._native.close()) {
1442
+ this._closePromise = Promise.resolve();
1443
+ return this._closePromise;
1444
+ }
1445
+ this._closePromise = this._native.closeAsync();
1446
+ return this._closePromise;
1447
+ }
1448
+ }
1449
+
1450
+ async function createRepl(options = undefined) {
1451
+ const { nativeOpts, nativeProject, bridgeCallback, setBridgeTarget, signal } =
1452
+ buildNativeOptions(options);
1453
+ const nativeRepl = unwrapOutcome(
1454
+ native.NativeReplSession.create(nativeOpts, nativeProject, bridgeCallback),
1455
+ );
1456
+ setBridgeTarget(nativeRepl);
1457
+ return new ReplSession(nativeRepl, signal);
1458
+ }
1459
+
1460
+ async function analyzeImportGraph(uris, options = undefined) {
1461
+ if (!Array.isArray(uris)) {
1462
+ throw new PklError("analyzeImportGraph uris must be an array.", "invalid-argument");
1463
+ }
1464
+ const normalized = uris.map((item) => {
1465
+ if (typeof item === "string") return item;
1466
+ if (item && typeof item === "object" && typeof item.uri === "string") return item.uri;
1467
+ throw new PklError(
1468
+ "analyzeImportGraph entries must be URI strings or ModuleSource instances.",
1469
+ "invalid-argument",
1470
+ );
1471
+ });
1472
+ const { nativeOpts, nativeProject, bridgeCallback, setBridgeTarget, signal } =
1473
+ buildNativeOptions(options);
1474
+ if (signal?.aborted) {
1475
+ throw new PklError("Import graph analysis was cancelled.", "cancelled");
1476
+ }
1477
+ const analyzer = unwrapOutcome(
1478
+ native.NativeAnalyzer.create(nativeOpts, nativeProject, bridgeCallback),
1479
+ );
1480
+ setBridgeTarget(analyzer);
1481
+ let onAbort = null;
1482
+ if (signal) {
1483
+ onAbort = () => analyzer.cancel();
1484
+ signal.addEventListener("abort", onAbort, { once: true });
1485
+ }
1486
+ try {
1487
+ return unwrapOutcome(await analyzer.importGraph(normalized));
1488
+ } finally {
1489
+ if (signal && onAbort) {
1490
+ signal.removeEventListener("abort", onAbort);
1491
+ }
1492
+ }
1493
+ }
1494
+
1495
+ function format(source, options = undefined) {
1496
+ if (typeof source !== "string") {
1497
+ throw new PklError("format source must be a string.", "invalid-argument");
1498
+ }
1499
+ const grammarVersion = options?.grammarVersion;
1500
+ if (grammarVersion !== undefined && grammarVersion !== 1 && grammarVersion !== 2) {
1501
+ throw new PklError(
1502
+ `Invalid grammarVersion "${grammarVersion}". Expected 1 or 2.`,
1503
+ "invalid-argument",
1504
+ );
1505
+ }
1506
+ return unwrapOutcome(native.productFormat(source, grammarVersion));
1507
+ }
1508
+
1509
+ const DECODE_STATE = new Int32Array(1);
1510
+ const INTERN_OFF = new Int32Array(64);
1511
+ const INTERN_LEN = new Int32Array(64);
1512
+ const INTERN_STR = new Array(64);
1513
+ const KEY_CACHE = new Map();
1514
+
1515
+ function internPropKey(s) {
1516
+ let k = KEY_CACHE.get(s);
1517
+ if (k !== undefined) return k;
1518
+ const tmp = { [s]: 0 };
1519
+ k = Object.keys(tmp)[0];
1520
+ if (KEY_CACHE.size < 256) KEY_CACHE.set(k, k);
1521
+ return k;
1522
+ }
1523
+
1524
+ const SHORT_UTF8_CODES = new Uint16Array(64);
1525
+
1526
+ function fastDecodeShortUtf8(bytes, pos, end) {
1527
+ let outLen = 0;
1528
+ let i = pos;
1529
+ while (i < end) {
1530
+ const b0 = bytes[i++];
1531
+ if (b0 < 0x80) {
1532
+ SHORT_UTF8_CODES[outLen++] = b0;
1533
+ } else if (b0 >= 0xc2 && b0 <= 0xdf) {
1534
+ if (i >= end) return DECODE_FALLBACK;
1535
+ const b1 = bytes[i++];
1536
+ if ((b1 & 0xc0) !== 0x80) return DECODE_FALLBACK;
1537
+ SHORT_UTF8_CODES[outLen++] = ((b0 & 0x1f) << 6) | (b1 & 0x3f);
1538
+ } else if (b0 >= 0xe0 && b0 <= 0xef) {
1539
+ if (i + 1 >= end) return DECODE_FALLBACK;
1540
+ const b1 = bytes[i++];
1541
+ const b2 = bytes[i++];
1542
+ if ((b1 & 0xc0) !== 0x80 || (b2 & 0xc0) !== 0x80) return DECODE_FALLBACK;
1543
+ if (b0 === 0xe0 && b1 < 0xa0) return DECODE_FALLBACK;
1544
+ if (b0 === 0xed && b1 >= 0xa0) return DECODE_FALLBACK;
1545
+ SHORT_UTF8_CODES[outLen++] = ((b0 & 0x0f) << 12) | ((b1 & 0x3f) << 6) | (b2 & 0x3f);
1546
+ } else if (b0 >= 0xf0 && b0 <= 0xf4) {
1547
+ if (i + 2 >= end) return DECODE_FALLBACK;
1548
+ const b1 = bytes[i++];
1549
+ const b2 = bytes[i++];
1550
+ const b3 = bytes[i++];
1551
+ if ((b1 & 0xc0) !== 0x80 || (b2 & 0xc0) !== 0x80 || (b3 & 0xc0) !== 0x80) {
1552
+ return DECODE_FALLBACK;
1553
+ }
1554
+ if (b0 === 0xf0 && b1 < 0x90) return DECODE_FALLBACK;
1555
+ if (b0 === 0xf4 && b1 > 0x8f) return DECODE_FALLBACK;
1556
+ const cp =
1557
+ (((b0 & 0x07) << 18) | ((b1 & 0x3f) << 12) | ((b2 & 0x3f) << 6) | (b3 & 0x3f)) -
1558
+ 0x10000;
1559
+ SHORT_UTF8_CODES[outLen++] = 0xd800 | (cp >> 10);
1560
+ SHORT_UTF8_CODES[outLen++] = 0xdc00 | (cp & 0x3ff);
1561
+ } else {
1562
+ return DECODE_FALLBACK;
1563
+ }
1564
+ }
1565
+ return String.fromCharCode.apply(null, SHORT_UTF8_CODES.subarray(0, outLen));
1566
+ }
1567
+
1568
+ function fastReadStr(bytes, view, len, pos, asKey) {
1569
+ if (pos >= len) return DECODE_FALLBACK;
1570
+ const b = bytes[pos++];
1571
+ let n;
1572
+ if (b >= 0xa0 && b <= 0xbf) {
1573
+ n = b & 0x1f;
1574
+ } else if (b === 0xd9) {
1575
+ if (pos >= len) return DECODE_FALLBACK;
1576
+ n = bytes[pos++];
1577
+ } else if (b === 0xda) {
1578
+ if (pos + 2 > len) return DECODE_FALLBACK;
1579
+ n = view.getUint16(pos, false);
1580
+ pos += 2;
1581
+ } else if (b === 0xdb) {
1582
+ if (pos + 4 > len) return DECODE_FALLBACK;
1583
+ n = view.getUint32(pos, false);
1584
+ pos += 4;
1585
+ } else {
1586
+ return DECODE_FALLBACK;
1587
+ }
1588
+ const end = pos + n;
1589
+ if (end > len) return DECODE_FALLBACK;
1590
+ DECODE_STATE[0] = end;
1591
+ if (n === 0) return "";
1592
+ if (n <= 24) {
1593
+ const slot = (bytes[pos] * 31 + bytes[end - 1] * 17 + n * 7) & 63;
1594
+ if (INTERN_LEN[slot] === n) {
1595
+ const prev = INTERN_OFF[slot];
1596
+ let eq = true;
1597
+ for (let k = 0; k < n; k += 1) {
1598
+ if (bytes[prev + k] !== bytes[pos + k]) {
1599
+ eq = false;
1600
+ break;
1601
+ }
1602
+ }
1603
+ if (eq) return INTERN_STR[slot];
1604
+ }
1605
+ let ascii = true;
1606
+ for (let i = pos; i < end; i += 1) {
1607
+ if (bytes[i] >= 0x80) {
1608
+ ascii = false;
1609
+ break;
1610
+ }
1611
+ }
1612
+ if (ascii) {
1613
+ let s;
1614
+ if (n === 1) s = String.fromCharCode(bytes[pos]);
1615
+ else if (n === 2) s = String.fromCharCode(bytes[pos], bytes[pos + 1]);
1616
+ else if (n === 3) s = String.fromCharCode(bytes[pos], bytes[pos + 1], bytes[pos + 2]);
1617
+ else if (n === 4) {
1618
+ s = String.fromCharCode(bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]);
1619
+ } else if (n === 5) {
1620
+ s = String.fromCharCode(
1621
+ bytes[pos],
1622
+ bytes[pos + 1],
1623
+ bytes[pos + 2],
1624
+ bytes[pos + 3],
1625
+ bytes[pos + 4],
1626
+ );
1627
+ } else if (n === 6) {
1628
+ s = String.fromCharCode(
1629
+ bytes[pos],
1630
+ bytes[pos + 1],
1631
+ bytes[pos + 2],
1632
+ bytes[pos + 3],
1633
+ bytes[pos + 4],
1634
+ bytes[pos + 5],
1635
+ );
1636
+ } else if (n === 7) {
1637
+ s = String.fromCharCode(
1638
+ bytes[pos],
1639
+ bytes[pos + 1],
1640
+ bytes[pos + 2],
1641
+ bytes[pos + 3],
1642
+ bytes[pos + 4],
1643
+ bytes[pos + 5],
1644
+ bytes[pos + 6],
1645
+ );
1646
+ } else if (n === 8) {
1647
+ s = String.fromCharCode(
1648
+ bytes[pos],
1649
+ bytes[pos + 1],
1650
+ bytes[pos + 2],
1651
+ bytes[pos + 3],
1652
+ bytes[pos + 4],
1653
+ bytes[pos + 5],
1654
+ bytes[pos + 6],
1655
+ bytes[pos + 7],
1656
+ );
1657
+ } else {
1658
+ s = "";
1659
+ for (let i = pos; i < end; i += 1) s += String.fromCharCode(bytes[i]);
1660
+ }
1661
+ if (asKey) s = internPropKey(s);
1662
+ INTERN_OFF[slot] = pos;
1663
+ INTERN_LEN[slot] = n;
1664
+ INTERN_STR[slot] = s;
1665
+ return s;
1666
+ }
1667
+ }
1668
+ if (n <= 64) {
1669
+ const decoded = fastDecodeShortUtf8(bytes, pos, end);
1670
+ if (decoded === DECODE_FALLBACK) return DECODE_FALLBACK;
1671
+ return asKey ? internPropKey(decoded) : decoded;
1672
+ }
1673
+ try {
1674
+ return FAST_UTF8_DECODER.decode(bytes.subarray(pos, end));
1675
+ } catch {
1676
+ return DECODE_FALLBACK;
1677
+ }
1678
+ }
1679
+
1680
+ function fastReadArrayLen(bytes, view, len, pos) {
1681
+ if (pos >= len) return -1;
1682
+ const b = bytes[pos++];
1683
+ if (b >= 0x90 && b <= 0x9f) {
1684
+ DECODE_STATE[0] = pos;
1685
+ return b & 0x0f;
1686
+ }
1687
+ if (b === 0xdc) {
1688
+ if (pos + 2 > len) return -1;
1689
+ DECODE_STATE[0] = pos + 2;
1690
+ return view.getUint16(pos, false);
1691
+ }
1692
+ if (b === 0xdd) {
1693
+ if (pos + 4 > len) return -1;
1694
+ DECODE_STATE[0] = pos + 4;
1695
+ return view.getUint32(pos, false);
1696
+ }
1697
+ return -1;
1698
+ }
1699
+
1700
+ function fastReadMapLen(bytes, view, len, pos) {
1701
+ if (pos >= len) return -1;
1702
+ const b = bytes[pos++];
1703
+ if (b >= 0x80 && b <= 0x8f) {
1704
+ DECODE_STATE[0] = pos;
1705
+ return b & 0x0f;
1706
+ }
1707
+ if (b === 0xde) {
1708
+ if (pos + 2 > len) return -1;
1709
+ DECODE_STATE[0] = pos + 2;
1710
+ return view.getUint16(pos, false);
1711
+ }
1712
+ if (b === 0xdf) {
1713
+ if (pos + 4 > len) return -1;
1714
+ DECODE_STATE[0] = pos + 4;
1715
+ return view.getUint32(pos, false);
1716
+ }
1717
+ return -1;
1718
+ }
1719
+
1720
+ function fastReadInt64(bytes, view, len, pos) {
1721
+ if (pos >= len) return DECODE_FALLBACK;
1722
+ const b = bytes[pos++];
1723
+ if (b <= 0x7f) {
1724
+ DECODE_STATE[0] = pos;
1725
+ return BigInt(b);
1726
+ }
1727
+ if (b >= 0xe0) {
1728
+ DECODE_STATE[0] = pos;
1729
+ return BigInt(b - 256);
1730
+ }
1731
+ if (b === 0xcc) {
1732
+ if (pos >= len) return DECODE_FALLBACK;
1733
+ DECODE_STATE[0] = pos + 1;
1734
+ return BigInt(bytes[pos]);
1735
+ }
1736
+ if (b === 0xcd) {
1737
+ if (pos + 2 > len) return DECODE_FALLBACK;
1738
+ DECODE_STATE[0] = pos + 2;
1739
+ return BigInt(view.getUint16(pos, false));
1740
+ }
1741
+ if (b === 0xce) {
1742
+ if (pos + 4 > len) return DECODE_FALLBACK;
1743
+ DECODE_STATE[0] = pos + 4;
1744
+ return BigInt(view.getUint32(pos, false));
1745
+ }
1746
+ if (b === 0xcf) {
1747
+ if (pos + 8 > len) return DECODE_FALLBACK;
1748
+ const v = view.getBigUint64(pos, false);
1749
+ if (v > MAX_I64) return DECODE_FALLBACK;
1750
+ DECODE_STATE[0] = pos + 8;
1751
+ return v;
1752
+ }
1753
+ if (b === 0xd0) {
1754
+ if (pos >= len) return DECODE_FALLBACK;
1755
+ DECODE_STATE[0] = pos + 1;
1756
+ return BigInt(view.getInt8(pos));
1757
+ }
1758
+ if (b === 0xd1) {
1759
+ if (pos + 2 > len) return DECODE_FALLBACK;
1760
+ DECODE_STATE[0] = pos + 2;
1761
+ return BigInt(view.getInt16(pos, false));
1762
+ }
1763
+ if (b === 0xd2) {
1764
+ if (pos + 4 > len) return DECODE_FALLBACK;
1765
+ DECODE_STATE[0] = pos + 4;
1766
+ return BigInt(view.getInt32(pos, false));
1767
+ }
1768
+ if (b === 0xd3) {
1769
+ if (pos + 8 > len) return DECODE_FALLBACK;
1770
+ DECODE_STATE[0] = pos + 8;
1771
+ return view.getBigInt64(pos, false);
1772
+ }
1773
+ return DECODE_FALLBACK;
1774
+ }
1775
+
1776
+ function fastReadFloat(bytes, view, len, pos) {
1777
+ if (pos >= len) return DECODE_FALLBACK;
1778
+ const b = bytes[pos++];
1779
+ if (b === 0xca) {
1780
+ if (pos + 4 > len) return DECODE_FALLBACK;
1781
+ DECODE_STATE[0] = pos + 4;
1782
+ return view.getFloat32(pos, false);
1783
+ }
1784
+ if (b === 0xcb) {
1785
+ if (pos + 8 > len) return DECODE_FALLBACK;
1786
+ DECODE_STATE[0] = pos + 8;
1787
+ return view.getFloat64(pos, false);
1788
+ }
1789
+ return DECODE_FALLBACK;
1790
+ }
1791
+
1792
+ function fastDecodeVal(bytes, view, len, depth) {
1793
+ let pos = DECODE_STATE[0];
1794
+ if (depth > 64 || pos >= len) return DECODE_FALLBACK;
1795
+ const b = bytes[pos];
1796
+ if (b <= 0x7f) {
1797
+ DECODE_STATE[0] = pos + 1;
1798
+ return BigInt(b);
1799
+ }
1800
+ if (b >= 0xe0) {
1801
+ DECODE_STATE[0] = pos + 1;
1802
+ return BigInt(b - 256);
1803
+ }
1804
+ if (b >= 0xa0 && b <= 0xbf) {
1805
+ return fastReadStr(bytes, view, len, pos, false);
1806
+ }
1807
+ if (b === 0xc0) {
1808
+ DECODE_STATE[0] = pos + 1;
1809
+ return null;
1810
+ }
1811
+ if (b === 0xc2) {
1812
+ DECODE_STATE[0] = pos + 1;
1813
+ return false;
1814
+ }
1815
+ if (b === 0xc3) {
1816
+ DECODE_STATE[0] = pos + 1;
1817
+ return true;
1818
+ }
1819
+ if (b === 0xca || b === 0xcb) {
1820
+ return fastReadFloat(bytes, view, len, pos);
1821
+ }
1822
+ if (b >= 0xcc && b <= 0xd3) {
1823
+ return fastReadInt64(bytes, view, len, pos);
1824
+ }
1825
+ if (b === 0xd9 || b === 0xda || b === 0xdb) {
1826
+ return fastReadStr(bytes, view, len, pos, false);
1827
+ }
1828
+ if ((b >= 0x90 && b <= 0x9f) || b === 0xdc || b === 0xdd) {
1829
+ const alen = fastReadArrayLen(bytes, view, len, pos);
1830
+ pos = DECODE_STATE[0];
1831
+ if (alen < 1 || pos >= len) return DECODE_FALLBACK;
1832
+ const code = bytes[pos++];
1833
+ if (code > 0x7f) return DECODE_FALLBACK;
1834
+
1835
+ if (code === 0x01) {
1836
+ if (alen !== 4) return DECODE_FALLBACK;
1837
+ const className = fastReadStr(bytes, view, len, pos, false);
1838
+ if (
1839
+ className === DECODE_FALLBACK ||
1840
+ className.length === 0 ||
1841
+ (className.charCodeAt(0) <= 0x20 && BLANK_OR_CTRL_RE.test(className))
1842
+ ) {
1843
+ return DECODE_FALLBACK;
1844
+ }
1845
+ pos = DECODE_STATE[0];
1846
+ const moduleUri = fastReadStr(bytes, view, len, pos, false);
1847
+ if (
1848
+ moduleUri === DECODE_FALLBACK ||
1849
+ moduleUri.length === 0 ||
1850
+ (moduleUri.charCodeAt(0) <= 0x20 && BLANK_OR_CTRL_RE.test(moduleUri))
1851
+ ) {
1852
+ return DECODE_FALLBACK;
1853
+ }
1854
+ pos = DECODE_STATE[0];
1855
+ const mcount = fastReadArrayLen(bytes, view, len, pos);
1856
+ if (mcount < 0) return DECODE_FALLBACK;
1857
+ pos = DECODE_STATE[0];
1858
+ const props = {};
1859
+ const entries = new Map();
1860
+ const elements = [];
1861
+ const nextDepth = depth + 1;
1862
+ for (let i = 0; i < mcount; i += 1) {
1863
+ if (pos + 2 > len) return DECODE_FALLBACK;
1864
+ if (bytes[pos++] !== 0x93) return DECODE_FALLBACK;
1865
+ const mcode = bytes[pos++];
1866
+ if (mcode === 0x10) {
1867
+ const k = fastReadStr(bytes, view, len, pos, true);
1868
+ if (k === DECODE_FALLBACK) return DECODE_FALLBACK;
1869
+ pos = DECODE_STATE[0];
1870
+ if (pos >= len) return DECODE_FALLBACK;
1871
+ const vb = bytes[pos];
1872
+ let v;
1873
+ if (vb === 0xd3) {
1874
+ if (pos + 9 > len) return DECODE_FALLBACK;
1875
+ v = view.getBigInt64(pos + 1, false);
1876
+ pos += 9;
1877
+ } else if (vb === 0xcf) {
1878
+ if (pos + 9 > len) return DECODE_FALLBACK;
1879
+ v = view.getBigUint64(pos + 1, false);
1880
+ if (v > MAX_I64) return DECODE_FALLBACK;
1881
+ pos += 9;
1882
+ } else if (vb === 0xc2) {
1883
+ v = false;
1884
+ pos += 1;
1885
+ } else if (vb === 0xc3) {
1886
+ v = true;
1887
+ pos += 1;
1888
+ } else if (vb === 0xc0) {
1889
+ v = null;
1890
+ pos += 1;
1891
+ } else if (vb <= 0x7f) {
1892
+ v = BigInt(vb);
1893
+ pos += 1;
1894
+ } else if (vb >= 0xe0) {
1895
+ v = BigInt(vb - 256);
1896
+ pos += 1;
1897
+ } else if (vb >= 0xa0 && vb <= 0xbf) {
1898
+ v = fastReadStr(bytes, view, len, pos, false);
1899
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
1900
+ pos = DECODE_STATE[0];
1901
+ } else if (
1902
+ pos + 4 <= len &&
1903
+ vb === 0x92 &&
1904
+ bytes[pos + 1] === 0x0f &&
1905
+ bytes[pos + 2] === 0xc4
1906
+ ) {
1907
+ const blen = bytes[pos + 3];
1908
+ const p = pos + 4;
1909
+ if (p + blen > len) return DECODE_FALLBACK;
1910
+ if (blen <= 16) {
1911
+ v = new Uint8Array(blen);
1912
+ for (let j = 0; j < blen; j += 1) v[j] = bytes[p + j];
1913
+ } else {
1914
+ v = bytes.slice(p, p + blen);
1915
+ }
1916
+ pos = p + blen;
1917
+ } else {
1918
+ DECODE_STATE[0] = pos;
1919
+ v = fastDecodeVal(bytes, view, len, nextDepth);
1920
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
1921
+ pos = DECODE_STATE[0];
1922
+ }
1923
+ if (k === "__proto__") {
1924
+ Object.defineProperty(props, k, {
1925
+ value: v,
1926
+ enumerable: true,
1927
+ writable: true,
1928
+ configurable: true,
1929
+ });
1930
+ } else {
1931
+ props[k] = v;
1932
+ }
1933
+ } else if (mcode === 0x11) {
1934
+ DECODE_STATE[0] = pos;
1935
+ const k = fastDecodeVal(bytes, view, len, nextDepth);
1936
+ if (k === DECODE_FALLBACK) return DECODE_FALLBACK;
1937
+ const v = fastDecodeVal(bytes, view, len, nextDepth);
1938
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
1939
+ pos = DECODE_STATE[0];
1940
+ entries.set(k, v);
1941
+ } else if (mcode === 0x12) {
1942
+ const idx = fastReadInt64(bytes, view, len, pos);
1943
+ if (idx === DECODE_FALLBACK) return DECODE_FALLBACK;
1944
+ const v = fastDecodeVal(bytes, view, len, nextDepth);
1945
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
1946
+ pos = DECODE_STATE[0];
1947
+ elements.push(v);
1948
+ } else {
1949
+ return DECODE_FALLBACK;
1950
+ }
1951
+ }
1952
+ DECODE_STATE[0] = pos;
1953
+ return new PklObject(className, moduleUri, props, entries, elements);
1954
+ }
1955
+
1956
+ if (code === 0x04 || code === 0x05) {
1957
+ if (alen !== 2) return DECODE_FALLBACK;
1958
+ const count = fastReadArrayLen(bytes, view, len, pos);
1959
+ if (count < 0) return DECODE_FALLBACK;
1960
+ const out = new Array(count);
1961
+ const nextDepth = depth + 1;
1962
+ for (let i = 0; i < count; i += 1) {
1963
+ const item = fastDecodeVal(bytes, view, len, nextDepth);
1964
+ if (item === DECODE_FALLBACK) return DECODE_FALLBACK;
1965
+ out[i] = item;
1966
+ }
1967
+ return out;
1968
+ }
1969
+
1970
+ if (code === 0x02 || code === 0x03) {
1971
+ if (alen !== 2) return DECODE_FALLBACK;
1972
+ const count = fastReadMapLen(bytes, view, len, pos);
1973
+ if (count < 0) return DECODE_FALLBACK;
1974
+ const out = new Map();
1975
+ const nextDepth = depth + 1;
1976
+ for (let i = 0; i < count; i += 1) {
1977
+ const k = fastDecodeVal(bytes, view, len, nextDepth);
1978
+ if (k === DECODE_FALLBACK) return DECODE_FALLBACK;
1979
+ const v = fastDecodeVal(bytes, view, len, nextDepth);
1980
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
1981
+ out.set(k, v);
1982
+ }
1983
+ return out;
1984
+ }
1985
+
1986
+ if (code === 0x06) {
1987
+ if (alen !== 2) return DECODE_FALLBACK;
1988
+ const count = fastReadArrayLen(bytes, view, len, pos);
1989
+ if (count < 0) return DECODE_FALLBACK;
1990
+ const out = new Set();
1991
+ const nextDepth = depth + 1;
1992
+ for (let i = 0; i < count; i += 1) {
1993
+ const item = fastDecodeVal(bytes, view, len, nextDepth);
1994
+ if (item === DECODE_FALLBACK) return DECODE_FALLBACK;
1995
+ out.add(item);
1996
+ }
1997
+ return out;
1998
+ }
1999
+
2000
+ if (code === 0x0f) {
2001
+ if (alen !== 2 || pos >= len) return DECODE_FALLBACK;
2002
+ const bb = bytes[pos++];
2003
+ let blen;
2004
+ if (bb === 0xc4) {
2005
+ if (pos >= len) return DECODE_FALLBACK;
2006
+ blen = bytes[pos++];
2007
+ } else if (bb === 0xc5) {
2008
+ if (pos + 2 > len) return DECODE_FALLBACK;
2009
+ blen = view.getUint16(pos, false);
2010
+ pos += 2;
2011
+ } else if (bb === 0xc6) {
2012
+ if (pos + 4 > len) return DECODE_FALLBACK;
2013
+ blen = view.getUint32(pos, false);
2014
+ pos += 4;
2015
+ } else {
2016
+ return DECODE_FALLBACK;
2017
+ }
2018
+ if (pos + blen > len) return DECODE_FALLBACK;
2019
+ let owned;
2020
+ if (blen <= 16) {
2021
+ owned = new Uint8Array(blen);
2022
+ for (let j = 0; j < blen; j += 1) owned[j] = bytes[pos + j];
2023
+ } else {
2024
+ owned = bytes.slice(pos, pos + blen);
2025
+ }
2026
+ DECODE_STATE[0] = pos + blen;
2027
+ return owned;
2028
+ }
2029
+
2030
+ if (code === 0x07) {
2031
+ if (alen !== 3) return DECODE_FALLBACK;
2032
+ const val = fastReadFloat(bytes, view, len, pos);
2033
+ if (val === DECODE_FALLBACK) return DECODE_FALLBACK;
2034
+ const unit = fastReadStr(bytes, view, len, DECODE_STATE[0], false);
2035
+ if (unit === DECODE_FALLBACK || !VALID_DURATION_UNITS.has(unit)) {
2036
+ return DECODE_FALLBACK;
2037
+ }
2038
+ return new PklDuration(val, unit);
2039
+ }
2040
+
2041
+ if (code === 0x08) {
2042
+ if (alen !== 3) return DECODE_FALLBACK;
2043
+ const val = fastReadFloat(bytes, view, len, pos);
2044
+ if (val === DECODE_FALLBACK) return DECODE_FALLBACK;
2045
+ const unit = fastReadStr(bytes, view, len, DECODE_STATE[0], false);
2046
+ if (unit === DECODE_FALLBACK || !VALID_DATA_SIZE_UNITS.has(unit)) {
2047
+ return DECODE_FALLBACK;
2048
+ }
2049
+ return new PklDataSize(val, unit);
2050
+ }
2051
+
2052
+ if (code === 0x09) {
2053
+ if (alen !== 3) return DECODE_FALLBACK;
2054
+ DECODE_STATE[0] = pos;
2055
+ const nextDepth = depth + 1;
2056
+ const first = fastDecodeVal(bytes, view, len, nextDepth);
2057
+ if (first === DECODE_FALLBACK) return DECODE_FALLBACK;
2058
+ const second = fastDecodeVal(bytes, view, len, nextDepth);
2059
+ if (second === DECODE_FALLBACK) return DECODE_FALLBACK;
2060
+ return new PklPair(first, second);
2061
+ }
2062
+
2063
+ return DECODE_FALLBACK;
2064
+ }
2065
+ return DECODE_FALLBACK;
2066
+ }
2067
+
2068
+ function tryDecodePklBinaryFast(bytes) {
2069
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) {
2070
+ return DECODE_FALLBACK;
2071
+ }
2072
+ const len = bytes.byteLength;
2073
+ const view = new DataView(bytes.buffer, bytes.byteOffset, len);
2074
+ DECODE_STATE[0] = 0;
2075
+ INTERN_LEN.fill(-1);
2076
+ const out = fastDecodeVal(bytes, view, len, 0);
2077
+ if (out === DECODE_FALLBACK || DECODE_STATE[0] !== len) {
2078
+ return DECODE_FALLBACK;
2079
+ }
2080
+ return out;
2081
+ }
2082
+
2083
+ const COLUMNAR_MAGIC = 0x504b4c01;
2084
+ const IS_LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
2085
+ let canUseNewFunction = true;
2086
+ const SHAPE_PROPS_FACTORIES = new Map();
2087
+ const COLUMNAR_TABLE_READERS = new Map();
2088
+ let columnarAlignBuf = null;
2089
+ const COL_STATE = new Int32Array(7);
2090
+
2091
+ function getShapePropsFactory(keys) {
2092
+ if (!canUseNewFunction || keys.length === 0 || keys.length > 32) return null;
2093
+ for (let i = 0; i < keys.length; i += 1) {
2094
+ if (keys[i] === "__proto__") return null;
2095
+ }
2096
+ const sig = keys.join("\0");
2097
+ let fn = SHAPE_PROPS_FACTORIES.get(sig);
2098
+ if (fn !== undefined) return fn;
2099
+ try {
2100
+ const params = new Array(keys.length);
2101
+ const fields = new Array(keys.length);
2102
+ for (let i = 0; i < keys.length; i += 1) {
2103
+ params[i] = `v${i}`;
2104
+ fields[i] = `${JSON.stringify(keys[i])}:v${i}`;
2105
+ }
2106
+ fn = new Function(params.join(","), `return {${fields.join(",")}};`);
2107
+ } catch {
2108
+ canUseNewFunction = false;
2109
+ return null;
2110
+ }
2111
+ if (SHAPE_PROPS_FACTORIES.size < 256) SHAPE_PROPS_FACTORIES.set(sig, fn);
2112
+ return fn;
2113
+ }
2114
+
2115
+ function getColumnarTableReader(keys, colTypes) {
2116
+ if (!canUseNewFunction || keys.length === 0 || keys.length > 32) return null;
2117
+ for (let i = 0; i < keys.length; i += 1) {
2118
+ if (keys[i] === "__proto__") return null;
2119
+ }
2120
+ const sig = `${keys.join("\0")}|${colTypes.join(",")}`;
2121
+ let fn = COLUMNAR_TABLE_READERS.get(sig);
2122
+ if (fn !== undefined) return fn;
2123
+ try {
2124
+ const lines = [
2125
+ "const out = new Array(count);",
2126
+ "let bi = st[0], si = st[1], soff = st[2], bo = st[3], bli = st[4], fli = st[5], bbi = st[6];",
2127
+ "for (let i = 0; i < count; i += 1) {",
2128
+ ];
2129
+ const propExprs = new Array(keys.length);
2130
+ for (let c = 0; c < keys.length; c += 1) {
2131
+ const t = colTypes[c];
2132
+ const k = JSON.stringify(keys[c]);
2133
+ if (t === 1) {
2134
+ propExprs[c] = `${k}: bigs[bi++]`;
2135
+ } else if (t === 2) {
2136
+ propExprs[c] = `${k}: bools[bbi++] !== 0`;
2137
+ } else if (t === 3) {
2138
+ lines.push(
2139
+ ` const l${c} = lens[si++]; const s${c} = bigStr.slice(soff, soff + l${c}); soff += l${c};`,
2140
+ );
2141
+ propExprs[c] = `${k}: s${c}`;
2142
+ } else if (t === 4) {
2143
+ lines.push(
2144
+ ` const bn${c} = binLens[bli++]; let u${c}; if (bn${c} <= 16) { u${c} = new Uint8Array(bn${c}); for (let j = 0; j < bn${c}; j += 1) u${c}[j] = bins[bo + j]; } else { u${c} = bins.slice(bo, bo + bn${c}); } bo += bn${c};`,
2145
+ );
2146
+ propExprs[c] = `${k}: u${c}`;
2147
+ } else if (t === 5) {
2148
+ propExprs[c] = `${k}: floats[fli++]`;
2149
+ } else if (t === 6) {
2150
+ propExprs[c] = `${k}: null`;
2151
+ } else {
2152
+ return null;
2153
+ }
2154
+ }
2155
+ lines.push(
2156
+ ` out[i] = new PklObject(cls, uri, {${propExprs.join(",")}}, new Map(), []);`,
2157
+ );
2158
+ lines.push("}");
2159
+ lines.push(
2160
+ "st[0] = bi; st[1] = si; st[2] = soff; st[3] = bo; st[4] = bli; st[5] = fli; st[6] = bbi;",
2161
+ );
2162
+ lines.push("return out;");
2163
+ fn = new Function(
2164
+ "PklObject",
2165
+ "cls",
2166
+ "uri",
2167
+ "count",
2168
+ "bigs",
2169
+ "bools",
2170
+ "floats",
2171
+ "lens",
2172
+ "bigStr",
2173
+ "bins",
2174
+ "binLens",
2175
+ "st",
2176
+ lines.join("\n"),
2177
+ );
2178
+ } catch {
2179
+ canUseNewFunction = false;
2180
+ return null;
2181
+ }
2182
+ if (COLUMNAR_TABLE_READERS.size < 256) COLUMNAR_TABLE_READERS.set(sig, fn);
2183
+ return fn;
2184
+ }
2185
+
2186
+ function unpackColumnarBuffer(bytes) {
2187
+ if (!IS_LITTLE_ENDIAN || !(bytes instanceof Uint8Array) || bytes.byteLength < 80) {
2188
+ return DECODE_FALLBACK;
2189
+ }
2190
+ let src = bytes;
2191
+ let alignedCopyOversized = false;
2192
+ if ((bytes.byteOffset & 7) !== 0) {
2193
+ const need = bytes.byteLength;
2194
+ if (columnarAlignBuf === null || columnarAlignBuf.byteLength < need) {
2195
+ columnarAlignBuf = new Uint8Array(Math.max(need, 4096));
2196
+ }
2197
+ columnarAlignBuf.set(bytes, 0);
2198
+ src = columnarAlignBuf.subarray(0, need);
2199
+ alignedCopyOversized = columnarAlignBuf.byteLength > 262144;
2200
+ }
2201
+ const ab = src.buffer;
2202
+ const base = src.byteOffset;
2203
+ const header = new Uint32Array(ab, base, 20);
2204
+ if (header[0] !== COLUMNAR_MAGIC) {
2205
+ return DECODE_FALLBACK;
2206
+ }
2207
+ const ops = new Int32Array(ab, base + header[1], header[2]);
2208
+ const bigs = new BigInt64Array(ab, base + header[3], header[4]);
2209
+ const floats = new Float64Array(ab, base + header[5], header[6]);
2210
+ const bools = new Uint8Array(ab, base + header[7], header[8]);
2211
+ const strLens = new Uint32Array(ab, base + header[9], header[10]);
2212
+ const strUtf8 = new Uint8Array(ab, base + header[11], header[12]);
2213
+ const binLens = new Uint32Array(ab, base + header[13], header[14]);
2214
+ const binBytes = new Uint8Array(ab, base + header[15], header[16]);
2215
+ const shapeCount = header[17];
2216
+ const shapeStrCount = header[18];
2217
+
2218
+ let bigStr;
2219
+ if (strUtf8.byteLength === 0) {
2220
+ bigStr = "";
2221
+ } else {
2222
+ try {
2223
+ bigStr = FAST_UTF8_DECODER.decode(strUtf8);
2224
+ } catch {
2225
+ return DECODE_FALLBACK;
2226
+ }
2227
+ }
2228
+
2229
+ let soff = 0;
2230
+ const shapeStrs = new Array(shapeStrCount);
2231
+ for (let i = 0; i < shapeStrCount; i += 1) {
2232
+ const l = strLens[i];
2233
+ shapeStrs[i] = bigStr.slice(soff, soff + l);
2234
+ soff += l;
2235
+ }
2236
+
2237
+ let op = 0;
2238
+ const shapes = new Array(shapeCount);
2239
+ for (let s = 0; s < shapeCount; s += 1) {
2240
+ const cls = shapeStrs[ops[op++]];
2241
+ const uri = shapeStrs[ops[op++]];
2242
+ const klen = ops[op++];
2243
+ const keys = new Array(klen);
2244
+ for (let k = 0; k < klen; k += 1) {
2245
+ keys[k] = shapeStrs[ops[op++]];
2246
+ }
2247
+ shapes[s] = { cls, uri, keys, fn: getShapePropsFactory(keys) };
2248
+ }
2249
+
2250
+ let bi = 0;
2251
+ let fli = 0;
2252
+ let bbi = 0;
2253
+ let si = shapeStrCount;
2254
+ let bli = 0;
2255
+ let bo = 0;
2256
+
2257
+ function readVal() {
2258
+ const tag = ops[op++];
2259
+ if (tag === 0) return null;
2260
+ if (tag === 1) return bigs[bi++];
2261
+ if (tag === 2) return floats[fli++];
2262
+ if (tag === 3) return false;
2263
+ if (tag === 4) return true;
2264
+ if (tag === 5) {
2265
+ const l = strLens[si++];
2266
+ const s = bigStr.slice(soff, soff + l);
2267
+ soff += l;
2268
+ return s;
2269
+ }
2270
+ if (tag === 6) {
2271
+ const n = binLens[bli++];
2272
+ let owned;
2273
+ if (n <= 16) {
2274
+ owned = new Uint8Array(n);
2275
+ for (let j = 0; j < n; j += 1) owned[j] = binBytes[bo + j];
2276
+ } else {
2277
+ owned = binBytes.slice(bo, bo + n);
2278
+ }
2279
+ bo += n;
2280
+ return owned;
2281
+ }
2282
+ if (tag === 7) {
2283
+ const n = ops[op++];
2284
+ const arr = new Array(n);
2285
+ for (let i = 0; i < n; i += 1) {
2286
+ const item = readVal();
2287
+ if (item === DECODE_FALLBACK) return DECODE_FALLBACK;
2288
+ arr[i] = item;
2289
+ }
2290
+ return arr;
2291
+ }
2292
+ if (tag === 10) {
2293
+ const sh = shapes[ops[op++]];
2294
+ const keys = sh.keys;
2295
+ const klen = keys.length;
2296
+ let props;
2297
+ if (sh.fn !== null) {
2298
+ if (klen === 4) {
2299
+ const a0 = readVal();
2300
+ const a1 = readVal();
2301
+ const a2 = readVal();
2302
+ const a3 = readVal();
2303
+ if (
2304
+ a0 === DECODE_FALLBACK ||
2305
+ a1 === DECODE_FALLBACK ||
2306
+ a2 === DECODE_FALLBACK ||
2307
+ a3 === DECODE_FALLBACK
2308
+ ) {
2309
+ return DECODE_FALLBACK;
2310
+ }
2311
+ props = sh.fn(a0, a1, a2, a3);
2312
+ } else if (klen === 5) {
2313
+ const a0 = readVal();
2314
+ const a1 = readVal();
2315
+ const a2 = readVal();
2316
+ const a3 = readVal();
2317
+ const a4 = readVal();
2318
+ if (
2319
+ a0 === DECODE_FALLBACK ||
2320
+ a1 === DECODE_FALLBACK ||
2321
+ a2 === DECODE_FALLBACK ||
2322
+ a3 === DECODE_FALLBACK ||
2323
+ a4 === DECODE_FALLBACK
2324
+ ) {
2325
+ return DECODE_FALLBACK;
2326
+ }
2327
+ props = sh.fn(a0, a1, a2, a3, a4);
2328
+ } else {
2329
+ const vals = new Array(klen);
2330
+ for (let i = 0; i < klen; i += 1) {
2331
+ const v = readVal();
2332
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2333
+ vals[i] = v;
2334
+ }
2335
+ props = sh.fn.apply(null, vals);
2336
+ }
2337
+ } else {
2338
+ props = {};
2339
+ for (let i = 0; i < klen; i += 1) {
2340
+ const v = readVal();
2341
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2342
+ const k = keys[i];
2343
+ if (k === "__proto__") {
2344
+ definePropSafe(props, k, v);
2345
+ } else {
2346
+ props[k] = v;
2347
+ }
2348
+ }
2349
+ }
2350
+ return new PklObject(sh.cls, sh.uri, props, new Map(), []);
2351
+ }
2352
+ if (tag === 12) {
2353
+ const sh = shapes[ops[op++]];
2354
+ const count = ops[op++];
2355
+ const keys = sh.keys;
2356
+ const klen = keys.length;
2357
+ const colTypes = new Array(klen);
2358
+ for (let c = 0; c < klen; c += 1) colTypes[c] = ops[op++];
2359
+ const reader = getColumnarTableReader(keys, colTypes);
2360
+ if (reader !== null) {
2361
+ COL_STATE[0] = bi;
2362
+ COL_STATE[1] = si;
2363
+ COL_STATE[2] = soff;
2364
+ COL_STATE[3] = bo;
2365
+ COL_STATE[4] = bli;
2366
+ COL_STATE[5] = fli;
2367
+ COL_STATE[6] = bbi;
2368
+ const out = reader(
2369
+ PklObject,
2370
+ sh.cls,
2371
+ sh.uri,
2372
+ count,
2373
+ bigs,
2374
+ bools,
2375
+ floats,
2376
+ strLens,
2377
+ bigStr,
2378
+ binBytes,
2379
+ binLens,
2380
+ COL_STATE,
2381
+ );
2382
+ bi = COL_STATE[0];
2383
+ si = COL_STATE[1];
2384
+ soff = COL_STATE[2];
2385
+ bo = COL_STATE[3];
2386
+ bli = COL_STATE[4];
2387
+ fli = COL_STATE[5];
2388
+ bbi = COL_STATE[6];
2389
+ return out;
2390
+ }
2391
+ const out = new Array(count);
2392
+ for (let i = 0; i < count; i += 1) {
2393
+ const props = {};
2394
+ for (let c = 0; c < klen; c += 1) {
2395
+ const t = colTypes[c];
2396
+ let v;
2397
+ if (t === 1) v = bigs[bi++];
2398
+ else if (t === 2) v = bools[bbi++] !== 0;
2399
+ else if (t === 3) {
2400
+ const l = strLens[si++];
2401
+ v = bigStr.slice(soff, soff + l);
2402
+ soff += l;
2403
+ } else if (t === 4) {
2404
+ const bn = binLens[bli++];
2405
+ if (bn <= 16) {
2406
+ v = new Uint8Array(bn);
2407
+ for (let j = 0; j < bn; j += 1) v[j] = binBytes[bo + j];
2408
+ } else {
2409
+ v = binBytes.slice(bo, bo + bn);
2410
+ }
2411
+ bo += bn;
2412
+ } else if (t === 5) v = floats[fli++];
2413
+ else if (t === 6) v = null;
2414
+ else return DECODE_FALLBACK;
2415
+ const k = keys[c];
2416
+ if (k === "__proto__") {
2417
+ definePropSafe(props, k, v);
2418
+ } else {
2419
+ props[k] = v;
2420
+ }
2421
+ }
2422
+ out[i] = new PklObject(sh.cls, sh.uri, props, new Map(), []);
2423
+ }
2424
+ return out;
2425
+ }
2426
+ if (tag === 13) {
2427
+ const val = floats[fli++];
2428
+ const l = strLens[si++];
2429
+ const unit = bigStr.slice(soff, soff + l);
2430
+ soff += l;
2431
+ return new PklDuration(val, unit);
2432
+ }
2433
+ if (tag === 14) {
2434
+ const val = floats[fli++];
2435
+ const l = strLens[si++];
2436
+ const unit = bigStr.slice(soff, soff + l);
2437
+ soff += l;
2438
+ return new PklDataSize(val, unit);
2439
+ }
2440
+ if (tag === 15) {
2441
+ const first = readVal();
2442
+ if (first === DECODE_FALLBACK) return DECODE_FALLBACK;
2443
+ const second = readVal();
2444
+ if (second === DECODE_FALLBACK) return DECODE_FALLBACK;
2445
+ return new PklPair(first, second);
2446
+ }
2447
+ if (tag === 16) {
2448
+ const l = strLens[si++];
2449
+ const pat = bigStr.slice(soff, soff + l);
2450
+ soff += l;
2451
+ return new PklRegex(pat);
2452
+ }
2453
+ if (tag === 17) {
2454
+ const start = bigs[bi++];
2455
+ const end = bigs[bi++];
2456
+ const step = bigs[bi++];
2457
+ return new PklIntSeq(start, end, step);
2458
+ }
2459
+ if (tag === 18) {
2460
+ return new PklFunction();
2461
+ }
2462
+ return DECODE_FALLBACK;
2463
+ }
2464
+
2465
+ const root = readVal();
2466
+ if (alignedCopyOversized) {
2467
+ columnarAlignBuf = null;
2468
+ }
2469
+ if (root === DECODE_FALLBACK || op !== ops.length) {
2470
+ return DECODE_FALLBACK;
2471
+ }
2472
+ return root;
2473
+ }
2474
+
2475
+ function decodePklBinary(bytes) {
2476
+ if (!(bytes instanceof Uint8Array)) {
2477
+ throw new PklError("decodePklBinary expects a Uint8Array.", "invalid-argument");
2478
+ }
2479
+ const fast = tryDecodePklBinaryFast(bytes);
2480
+ if (fast !== DECODE_FALLBACK) {
2481
+ return fast;
2482
+ }
2483
+ const raw = unwrapOutcome(
2484
+ native.productDecodePklBinary(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)),
2485
+ );
2486
+ return hydrateValue(raw);
2487
+ }
2488
+
2489
+ function monotonicClockMs() {
2490
+ return native.productMonotonicClockMs();
2491
+ }
2492
+
2493
+ function roundtripValue(val) {
2494
+ const dehydrated = dehydrateValue(val);
2495
+ const raw = unwrapOutcome(native.productRoundtripValue(dehydrated));
2496
+ return hydrateValue(raw);
2497
+ }
2498
+
2499
+ function roundtripInteger(val) {
2500
+ if (typeof val !== "bigint") {
2501
+ throw new PklError("roundtripInteger expects a BigInt.", "invalid-argument");
2502
+ }
2503
+ return unwrapOutcome(native.productRoundtripInteger(val));
2504
+ }
2505
+
2506
+ function roundtripBytes(val) {
2507
+ if (!(val instanceof Uint8Array)) {
2508
+ throw new PklError("roundtripBytes expects a Uint8Array.", "invalid-argument");
2509
+ }
2510
+ return native.roundtripBytes(new Uint8Array(val.buffer, val.byteOffset, val.byteLength));
2511
+ }
2512
+
2513
+ function roundtripString(val) {
2514
+ if (typeof val !== "string") {
2515
+ throw new PklError("roundtripString expects a string.", "invalid-argument");
2516
+ }
2517
+ return native.roundtripString(val);
2518
+ }
2519
+
2520
+ function defaultBenchmarkPayload() {
2521
+ return new PklObject(
2522
+ "Bench#Payload",
2523
+ "repl:bench",
2524
+ {
2525
+ intMin: MIN_I64,
2526
+ intMax: MAX_I64,
2527
+ floatVal: 3.141592653589793,
2528
+ text: "hello-pkl-🚀-utf16",
2529
+ bytes: new Uint8Array([0, 1, 2, 127, 128, 255]),
2530
+ duration: new PklDuration(5, "s"),
2531
+ dataSize: new PklDataSize(16, "mib"),
2532
+ pair: new PklPair("left", 42n),
2533
+ list: [1n, 2n, 3n, true, null],
2534
+ set: new Set(["a", "b", "c"]),
2535
+ map: new Map([
2536
+ ["k1", 100n],
2537
+ ["k2", "v2"],
2538
+ ]),
2539
+ },
2540
+ new Map(),
2541
+ [],
2542
+ );
2543
+ }
2544
+
2545
+ function measureConversion(valOrIterations = 1000, maybeIterations = undefined) {
2546
+ let value;
2547
+ let iterations;
2548
+ if (typeof valOrIterations === "number" && maybeIterations === undefined) {
2549
+ value = defaultBenchmarkPayload();
2550
+ iterations = valOrIterations;
2551
+ } else {
2552
+ value = valOrIterations;
2553
+ iterations = maybeIterations === undefined ? 1000 : maybeIterations;
2554
+ }
2555
+ if (!Number.isInteger(iterations) || iterations < 1 || iterations > 1_000_000) {
2556
+ throw new PklError(
2557
+ `iterations must be an integer between 1 and 1000000, got ${iterations}.`,
2558
+ "invalid-argument",
2559
+ );
2560
+ }
2561
+ const dehydrated = dehydrateValue(value);
2562
+ const startNs = process.hrtime.bigint();
2563
+ const nativeStats = unwrapOutcome(native.productMeasureConversion(dehydrated, iterations));
2564
+ const hydrated = hydrateValue(nativeStats.lastValue);
2565
+ const totalElapsedMs = Number(process.hrtime.bigint() - startNs) / 1e6;
2566
+ return {
2567
+ iterations: nativeStats.iterations,
2568
+ elapsedMs: totalElapsedMs,
2569
+ nativeElapsedMs: nativeStats.elapsedMs,
2570
+ perIterationUs: (totalElapsedMs * 1000) / nativeStats.iterations,
2571
+ nativePerIterationUs: nativeStats.perIterationUs,
2572
+ lastValue: hydrated,
2573
+ };
2574
+ }
2575
+
2576
+ module.exports = {
2577
+ PKL_VERSION,
2578
+ capabilities,
2579
+ PklError,
2580
+ ModuleSource,
2581
+ PklDuration,
2582
+ PklDataSize,
2583
+ PklPair,
2584
+ PklRegex,
2585
+ PklObject,
2586
+ PklClass,
2587
+ PklTypeAlias,
2588
+ PklIntSeq,
2589
+ PklFunction,
2590
+ PklReference,
2591
+ Evaluator,
2592
+ Project,
2593
+ ReplSession,
2594
+ createEvaluator,
2595
+ createEvaluatorSync,
2596
+ createRepl,
2597
+ analyzeImportGraph,
2598
+ format,
2599
+ decodePklBinary,
2600
+ monotonicClockMs,
2601
+ roundtripValue,
2602
+ roundtripInteger,
2603
+ roundtripBytes,
2604
+ roundtripString,
2605
+ measureConversion,
2606
+ };