@crewhaus/tool-table 0.7.0 → 0.8.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ CrewHaus Factory
2
+ Copyright 2026 Max Meier
3
+
4
+ This product includes software developed by Max Meier
5
+ (operating as StudioMax — https://studiomax.io) and contributors.
6
+
7
+ The CrewHaus name and logo are trademarks of Max Meier. See
8
+ https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
9
+ use-of-marks policy.
package/dist/index.js CHANGED
@@ -15,15 +15,22 @@
15
15
  * repository would disagree about quoting and embedded newlines on the same
16
16
  * file, in different tools, which is the worst way to disagree.
17
17
  */
18
- import { readFileSync, statSync } from "node:fs";
19
18
  import { buildTool } from "@crewhaus/tool-builder";
20
19
  import { parseCsv } from "@crewhaus/tool-data";
20
+ import { openForReadSync } from "@crewhaus/tool-safety/fs";
21
21
  import { z } from "zod";
22
22
  import { DriftError, compareDrift } from "./lib/drift";
23
23
  import { profileTable } from "./lib/profile";
24
24
  import { FIELD_NORMALIZERS, diffTables, linkRecords, normalizeContact, } from "./lib/reconcile";
25
25
  import { parseFixedWidth, shardRows, toLong, toWide } from "./lib/reshape";
26
- import { resolveSafe } from "./paths";
26
+ import { resolveSafe, workspaceRoot } from "./paths";
27
+ /**
28
+ * A file's text as 0.7.0's `readFileSync(path, "utf8")` gave it: a leading
29
+ * byte-order mark kept. tool-safety's `text` drops one, which moved
30
+ * FixedWidthParse's columns by one on a file that starts with one (bounds
31
+ * review). A CSV's header is unaffected: parseCsv drops the mark itself.
32
+ */
33
+ const KEEP_BOM = new TextDecoder("utf-8", { ignoreBOM: true });
27
34
  const json = (value) => JSON.stringify(value);
28
35
  const LIMITS = {
29
36
  fileBytes: 512 * 1024 * 1024,
@@ -35,14 +42,36 @@ const LIMITS = {
35
42
  /** A stored profile is a summary; anything this big is the data by mistake. */
36
43
  profileBytes: 64 * 1024 * 1024,
37
44
  };
45
+ /**
46
+ * A workspace file's text, at most `maxBytes` of it.
47
+ *
48
+ * Opened without blocking, and only as a regular file: a FIFO with no writer
49
+ * blocks an ordinary open for ever, and these reads were synchronous, so a
50
+ * named pipe in the workspace stopped the whole harness (C074). The limit is
51
+ * enforced while reading; `overLimit` says the file holds more.
52
+ */
53
+ function readWorkspaceText(tool, file, maxBytes) {
54
+ const read = openForReadSync(workspaceRoot(), file, { maxBytes });
55
+ if (!read.ok)
56
+ throw new Error(`${tool}: ${read.reason}`);
57
+ return {
58
+ // Decoded only when asked for: a caller refuses a file over the limit unread.
59
+ get text() {
60
+ return KEEP_BOM.decode(read.bytes);
61
+ },
62
+ size: read.size,
63
+ overLimit: read.truncated,
64
+ };
65
+ }
38
66
  /** Read a delimited file into a header and rows of strings. */
39
67
  function readTable(tool, file, options) {
40
68
  const at = resolveSafe(tool, file);
41
- const bytes = statSync(at.real).size;
42
- if (bytes > LIMITS.fileBytes) {
69
+ const read = readWorkspaceText(tool, file, LIMITS.fileBytes);
70
+ const bytes = read.size;
71
+ if (read.overLimit) {
43
72
  throw new Error(`${at.rel} is ${bytes} bytes, over the ${LIMITS.fileBytes}-byte limit`);
44
73
  }
45
- const text = readFileSync(at.real, "utf-8");
74
+ const text = read.text;
46
75
  // `parseCsv` returns every row including the header; splitting it here
47
76
  // keeps one reader for the whole repository rather than two that disagree
48
77
  // about quoting on the same file.
@@ -164,13 +193,19 @@ export const tableProfile = buildTool({
164
193
  */
165
194
  function loadReferenceProfile(file) {
166
195
  const at = resolveSafe("DataDriftCheck", file);
167
- const bytes = statSync(at.real).size;
168
- if (bytes > LIMITS.profileBytes) {
169
- return `${at.rel} is ${bytes} bytes, far larger than any profile — this is probably not a stored TableProfile`;
196
+ let read;
197
+ try {
198
+ read = readWorkspaceText("DataDriftCheck", file, LIMITS.profileBytes);
199
+ }
200
+ catch (err) {
201
+ return err.message;
202
+ }
203
+ if (read.overLimit) {
204
+ return `${at.rel} is ${read.size} bytes, far larger than any profile — this is probably not a stored TableProfile`;
170
205
  }
171
206
  let parsed;
172
207
  try {
173
- parsed = JSON.parse(readFileSync(at.real, "utf-8"));
208
+ parsed = JSON.parse(read.text);
174
209
  }
175
210
  catch (err) {
176
211
  return `${at.rel} is not JSON: ${err.message}. referenceProfile takes a stored TableProfile result; for raw data use referenceFile`;
@@ -244,6 +279,13 @@ function columnProblem(value) {
244
279
  if (typeof counts !== "object" || counts === null || Array.isArray(counts)) {
245
280
  return `${label} has a categorical capture with no valueCounts map`;
246
281
  }
282
+ // A count the chi-square adds up. A hand-edited "50" would concatenate
283
+ // instead of adding, and the category would drop out of the test.
284
+ for (const [value, count] of Object.entries(counts)) {
285
+ if (typeof count !== "number" || !Number.isFinite(count) || count < 0) {
286
+ return `${label} has a non-numeric count for the value ${JSON.stringify(value)} in its valueCounts; it has been edited by hand and cannot be used as a baseline`;
287
+ }
288
+ }
247
289
  return null;
248
290
  }
249
291
  return `${label} has a drift capture of unknown kind ${JSON.stringify(capture["kind"])}`;
@@ -682,11 +724,11 @@ export const fixedWidthParse = buildTool({
682
724
  concurrencySafe: true,
683
725
  execute: async (input) => {
684
726
  const at = resolveSafe("FixedWidthParse", input.file);
685
- const bytes = statSync(at.real).size;
686
- if (bytes > LIMITS.fileBytes) {
687
- throw new Error(`${at.rel} is ${bytes} bytes, over the ${LIMITS.fileBytes}-byte limit`);
727
+ const read = readWorkspaceText("FixedWidthParse", input.file, LIMITS.fileBytes);
728
+ if (read.overLimit) {
729
+ throw new Error(`${at.rel} is ${read.size} bytes, over the ${LIMITS.fileBytes}-byte limit`);
688
730
  }
689
- const result = parseFixedWidth(readFileSync(at.real, "utf-8"), input.fields, {
731
+ const result = parseFixedWidth(read.text, input.fields, {
690
732
  skipLines: input.skipLines,
691
733
  });
692
734
  const limit = input.limit ?? 500;
package/dist/lib/drift.js CHANGED
@@ -127,17 +127,24 @@ export function chiSquareUpperTail(x, df) {
127
127
  * move a verdict. A caller gating on `p` should gate on this first.
128
128
  */
129
129
  export function chiSquareHomogeneity(reference, current) {
130
+ // Own properties only. The keys are CELL VALUES, and a stored profile comes
131
+ // back from JSON.parse as a plain object: `reference["constructor"]` on a
132
+ // reference that never saw that value is Object's constructor, a function,
133
+ // and `function + 80` is a string that compares false against 0 — so a
134
+ // brand-new category named "constructor", "toString" or "__proto__"
135
+ // vanished from the table and the test answered p = 1 on real drift.
136
+ const countOf = (counts, key) => Object.hasOwn(counts, key) ? counts[key] : 0;
130
137
  // A key recorded as zero on BOTH sides is dropped rather than counted: it
131
138
  // would make its column total zero, so both its expected counts would be
132
139
  // 0/0, and it would inflate df with a cell that holds no observation.
133
140
  const categories = [...new Set([...Object.keys(reference), ...Object.keys(current)])]
134
- .filter((key) => (reference[key] ?? 0) + (current[key] ?? 0) > 0)
141
+ .filter((key) => countOf(reference, key) + countOf(current, key) > 0)
135
142
  .sort();
136
143
  let referenceTotal = 0;
137
144
  let currentTotal = 0;
138
145
  for (const key of categories) {
139
- referenceTotal += reference[key] ?? 0;
140
- currentTotal += current[key] ?? 0;
146
+ referenceTotal += countOf(reference, key);
147
+ currentTotal += countOf(current, key);
141
148
  }
142
149
  const total = referenceTotal + currentTotal;
143
150
  const base = {
@@ -171,8 +178,8 @@ export function chiSquareHomogeneity(reference, current) {
171
178
  let cellsBelowFive = 0;
172
179
  let cellsBelowOne = 0;
173
180
  for (const key of categories) {
174
- const observedReference = reference[key] ?? 0;
175
- const observedCurrent = current[key] ?? 0;
181
+ const observedReference = countOf(reference, key);
182
+ const observedCurrent = countOf(current, key);
176
183
  const columnTotal = observedReference + observedCurrent;
177
184
  // A column total of zero cannot occur: the key is in the union because at
178
185
  // least one side counted it. So neither expectation below is 0/0.
@@ -314,7 +314,9 @@ function captureColumn(numericValues, ordered, nonNull, settings) {
314
314
  // `otherCount` still says zero, so the capture claims a complete category
315
315
  // list that is missing a category — and a value arriving for the first time
316
316
  // today is never named as new. A null prototype makes it an ordinary key,
317
- // and `JSON.stringify`/`JSON.parse` round-trip it intact.
317
+ // and `JSON.stringify`/`JSON.parse` round-trip the keys intact — though
318
+ // the parsed map is a plain object again, which is why the chi-square
319
+ // (drift.ts) reads own properties only.
318
320
  const valueCounts = Object.create(null);
319
321
  for (const { value, count } of kept)
320
322
  valueCounts[value] = count;
package/dist/paths.d.ts CHANGED
@@ -1,10 +1,29 @@
1
1
  import { CrewhausError } from "@crewhaus/errors";
2
- /** Raised when a caller-supplied path resolves outside the workspace root. */
2
+ /**
3
+ * The longest path this resolves, in UTF-16 code units; a longer one is
4
+ * refused before it is walked. Nothing that long can be opened or created:
5
+ * PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
6
+ * 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
7
+ * UTF-16 one. The limit is twice that because the part of a path that exists
8
+ * is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
9
+ * own: no spelling of the place reaches it, not even one through a symlink
10
+ * that shortens the part that exists.
11
+ */
12
+ export declare const MAX_PATH_CHARS: number;
13
+ /**
14
+ * Raised when a caller-supplied path resolves outside the workspace root, or
15
+ * is longer than any path can be.
16
+ */
3
17
  export declare class ToolPermissionError extends CrewhausError {
4
18
  readonly name = "ToolPermissionError";
5
19
  readonly toolName: string;
6
20
  readonly path: string;
7
- constructor(toolName: string, attemptedPath: string);
21
+ /**
22
+ * Why, when it is not that the location escapes the workspace root: a path
23
+ * longer than any path can be. A caller that rewords the refusal says this.
24
+ */
25
+ readonly reason: string | undefined;
26
+ constructor(toolName: string, attemptedPath: string, reason?: string);
8
27
  }
9
28
  /**
10
29
  * A validated path, in both forms the tools need.
package/dist/paths.js CHANGED
@@ -11,15 +11,45 @@
11
11
  import { lstatSync, readlinkSync, realpathSync } from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import { CrewhausError } from "@crewhaus/errors";
14
- /** Raised when a caller-supplied path resolves outside the workspace root. */
14
+ /**
15
+ * The longest path this resolves, in UTF-16 code units; a longer one is
16
+ * refused before it is walked. Nothing that long can be opened or created:
17
+ * PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
18
+ * 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
19
+ * UTF-16 one. The limit is twice that because the part of a path that exists
20
+ * is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
21
+ * own: no spelling of the place reaches it, not even one through a symlink
22
+ * that shortens the part that exists.
23
+ */
24
+ export const MAX_PATH_CHARS = 2 * (process.platform === "darwin" ? 1_024 : process.platform === "win32" ? 32_767 : 4_096);
25
+ /** A path as a refusal quotes it: whole, unless it is past {@link MAX_PATH_CHARS}. */
26
+ function shownPath(given) {
27
+ return given.length > MAX_PATH_CHARS ? `${given.slice(0, 64)}…` : given;
28
+ }
29
+ /** Why a path past {@link MAX_PATH_CHARS} is refused: its length and the limit. */
30
+ function tooLong(abs) {
31
+ return `it is ${abs.length} characters once resolved, over the ${MAX_PATH_CHARS}-character limit: no path that long can be opened or created`;
32
+ }
33
+ /**
34
+ * Raised when a caller-supplied path resolves outside the workspace root, or
35
+ * is longer than any path can be.
36
+ */
15
37
  export class ToolPermissionError extends CrewhausError {
16
38
  name = "ToolPermissionError";
17
39
  toolName;
18
40
  path;
19
- constructor(toolName, attemptedPath) {
20
- super("tool", `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`);
41
+ /**
42
+ * Why, when it is not that the location escapes the workspace root: a path
43
+ * longer than any path can be. A caller that rewords the refusal says this.
44
+ */
45
+ reason;
46
+ constructor(toolName, attemptedPath, reason) {
47
+ super("tool", reason === undefined
48
+ ? `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`
49
+ : `tool "${toolName}" rejected path "${shownPath(attemptedPath)}": ${reason}`);
21
50
  this.toolName = toolName;
22
51
  this.path = attemptedPath;
52
+ this.reason = reason;
23
53
  }
24
54
  }
25
55
  /** The workspace root, resolved. Every path is contained within it. */
@@ -67,15 +97,7 @@ function nameExists(p) {
67
97
  function resolveLocation(target, depth = 0) {
68
98
  if (depth > 40)
69
99
  throw new Error(`symlink chain at "${target}" is too long to resolve`);
70
- let probe = target;
71
- const tail = [];
72
- while (!nameExists(probe)) {
73
- tail.unshift(path.basename(probe));
74
- const parent = path.dirname(probe);
75
- if (parent === probe)
76
- break; // reached the filesystem root
77
- probe = parent;
78
- }
100
+ const { probe, tail } = deepestName(target);
79
101
  let probeReal;
80
102
  try {
81
103
  probeReal = realpathSync(probe);
@@ -97,7 +119,41 @@ function resolveLocation(target, depth = 0) {
97
119
  const base = realpathSync(path.dirname(probe));
98
120
  probeReal = resolveLocation(path.resolve(base, link), depth + 1);
99
121
  }
100
- return tail.length > 0 ? path.join(probeReal, ...tail) : probeReal;
122
+ // One string, not one argument per name: Bun's `path.join` keeps only
123
+ // (argument count mod 65,536) of its arguments.
124
+ return tail.length > 0 ? path.join(probeReal, tail) : probeReal;
125
+ }
126
+ /**
127
+ * `target`, an absolute path, split where its deepest prefix that exists as
128
+ * a NAME ends: that prefix, and the names below it, which do not exist, as
129
+ * one string ("" when `target` itself exists). This is `path.dirname` and
130
+ * `path.basename` worked by index on `target` itself: handing them each
131
+ * shorter prefix in turn copied the rest of the path once per missing name,
132
+ * the square of a count the caller picks.
133
+ */
134
+ function deepestName(target) {
135
+ const top = path.parse(target).root.length;
136
+ const isSep = (i) => target[i] === "/" || target[i] === path.sep;
137
+ let probe = target;
138
+ let start = target.length;
139
+ let stop = -1;
140
+ while (!nameExists(probe)) {
141
+ // `path.basename(probe)` is `target.slice(start, end)`, and
142
+ // `path.dirname(probe)` is `target.slice(0, up)`.
143
+ let end = probe.length;
144
+ while (end > top && isSep(end - 1))
145
+ end--;
146
+ if (stop < 0)
147
+ stop = end;
148
+ start = end;
149
+ while (start > top && !isSep(start - 1))
150
+ start--;
151
+ const up = start > top ? start - 1 : top;
152
+ if (up === probe.length)
153
+ break; // reached the filesystem root
154
+ probe = target.slice(0, up);
155
+ }
156
+ return { probe, tail: stop < 0 ? "" : target.slice(start, stop) };
101
157
  }
102
158
  export function resolveSafe(toolName, rel, root = workspaceRoot()) {
103
159
  const rootResolved = path.resolve(root);
@@ -107,6 +163,9 @@ export function resolveSafe(toolName, rel, root = workspaceRoot()) {
107
163
  if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
108
164
  throw new ToolPermissionError(toolName, rel);
109
165
  }
166
+ // Longer than any path can be: refused before the walk below reads it.
167
+ if (abs.length > MAX_PATH_CHARS)
168
+ throw new ToolPermissionError(toolName, rel, tooLong(abs));
110
169
  let real;
111
170
  try {
112
171
  const rootReal = realpathSync(rootResolved);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/tool-table",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "type": "module",
5
5
  "description": "Deterministic tabular tools: profiling, drift detection, keyed reconciliation, record linkage, contact normalization, reshaping, sharding and fixed-width parsing",
6
6
  "main": "dist/index.js",
@@ -8,18 +8,20 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
12
13
  }
13
14
  },
14
15
  "scripts": {
15
16
  "test": "bun test src"
16
17
  },
17
18
  "dependencies": {
18
- "@crewhaus/errors": "0.7.0",
19
- "@crewhaus/tool-builder": "0.7.0",
20
- "@crewhaus/tool-catalog": "0.7.0",
21
- "@crewhaus/tool-data": "0.7.0",
22
- "@crewhaus/tool-math": "0.7.0",
19
+ "@crewhaus/errors": "0.8.1",
20
+ "@crewhaus/tool-builder": "0.8.1",
21
+ "@crewhaus/tool-catalog": "0.8.1",
22
+ "@crewhaus/tool-data": "0.8.1",
23
+ "@crewhaus/tool-math": "0.8.1",
24
+ "@crewhaus/tool-safety": "0.8.1",
23
25
  "zod": "^3.23.8"
24
26
  },
25
27
  "devDependencies": {
@@ -43,5 +45,8 @@
43
45
  "publishConfig": {
44
46
  "access": "public"
45
47
  },
46
- "files": ["dist", "README.md", "LICENSE", "NOTICE"]
48
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"],
49
+ "engines": {
50
+ "bun": ">=1.3.14"
51
+ }
47
52
  }