nalloc 0.0.1 → 0.0.2

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.
Files changed (64) hide show
  1. package/README.md +124 -38
  2. package/build/index.cjs +12 -68
  3. package/build/index.cjs.map +1 -1
  4. package/build/index.d.ts +1 -4
  5. package/build/index.js +1 -3
  6. package/build/index.js.map +1 -1
  7. package/build/iter.cjs +105 -0
  8. package/build/iter.cjs.map +1 -0
  9. package/build/iter.d.ts +61 -0
  10. package/build/iter.js +78 -0
  11. package/build/iter.js.map +1 -0
  12. package/build/option.cjs +19 -5
  13. package/build/option.cjs.map +1 -1
  14. package/build/option.d.ts +22 -1
  15. package/build/option.js +14 -6
  16. package/build/option.js.map +1 -1
  17. package/build/result.cjs +125 -54
  18. package/build/result.cjs.map +1 -1
  19. package/build/result.d.ts +83 -53
  20. package/build/result.js +100 -38
  21. package/build/result.js.map +1 -1
  22. package/build/safe.cjs +34 -15
  23. package/build/safe.cjs.map +1 -1
  24. package/build/safe.d.ts +4 -27
  25. package/build/safe.js +3 -14
  26. package/build/safe.js.map +1 -1
  27. package/build/types.cjs +38 -7
  28. package/build/types.cjs.map +1 -1
  29. package/build/types.d.ts +26 -4
  30. package/build/types.js +23 -7
  31. package/build/types.js.map +1 -1
  32. package/build/unsafe.cjs +14 -61
  33. package/build/unsafe.cjs.map +1 -1
  34. package/build/unsafe.d.ts +2 -27
  35. package/build/unsafe.js +2 -9
  36. package/build/unsafe.js.map +1 -1
  37. package/package.json +13 -16
  38. package/src/__tests__/index.ts +42 -0
  39. package/src/__tests__/iter.ts +218 -0
  40. package/src/__tests__/option.ts +48 -19
  41. package/src/__tests__/result.ts +286 -91
  42. package/src/__tests__/result.types.ts +3 -22
  43. package/src/__tests__/safe.ts +9 -15
  44. package/src/__tests__/unsafe.ts +11 -12
  45. package/src/index.ts +1 -18
  46. package/src/iter.ts +129 -0
  47. package/src/option.ts +36 -7
  48. package/src/result.ts +216 -113
  49. package/src/safe.ts +5 -42
  50. package/src/types.ts +52 -14
  51. package/src/unsafe.ts +2 -47
  52. package/build/devtools.cjs +0 -79
  53. package/build/devtools.cjs.map +0 -1
  54. package/build/devtools.d.ts +0 -82
  55. package/build/devtools.js +0 -43
  56. package/build/devtools.js.map +0 -1
  57. package/build/testing.cjs +0 -111
  58. package/build/testing.cjs.map +0 -1
  59. package/build/testing.d.ts +0 -85
  60. package/build/testing.js +0 -81
  61. package/build/testing.js.map +0 -1
  62. package/src/__tests__/tooling.ts +0 -86
  63. package/src/devtools.ts +0 -97
  64. package/src/testing.ts +0 -159
package/src/types.ts CHANGED
@@ -31,6 +31,9 @@ export type None = NoneValueType & { readonly [SOME_BRAND]: false };
31
31
  /** Constant representing None. Use this instead of null/undefined for clarity. */
32
32
  export const NONE = undefined as None;
33
33
 
34
+ /** Shared frozen empty array to avoid allocations. */
35
+ export const EMPTY: readonly unknown[] = Object.freeze([]);
36
+
34
37
  /** A value that may or may not be present. Some(T) is the value itself; None is null/undefined. */
35
38
  export type Option<T> = Some<ValueType<T>> | None;
36
39
 
@@ -91,15 +94,23 @@ export function optionOf<T>(value: T): Option<T> {
91
94
  return isNone(value as Option<T>) ? NONE : (value as Some<T>);
92
95
  }
93
96
 
97
+ export function someUnchecked<T>(value: T): Some<ValueType<T>> {
98
+ return value as Some<ValueType<T>>;
99
+ }
100
+
94
101
  /**
95
- * Creates a Some value. Does not validate - use safe.some() for validation.
96
- * @param value - The value to wrap (must be non-null)
102
+ * Creates a Some value with runtime validation.
103
+ * @param value - The value to wrap
97
104
  * @returns The value typed as Some
105
+ * @throws TypeError if value is null or undefined
98
106
  * @example
99
107
  * some(42) // Some(42)
100
108
  */
101
109
  export function some<T>(value: ValueType<T>): Some<ValueType<T>> {
102
- return value as Some<ValueType<T>>;
110
+ if (value === null || value === undefined) {
111
+ throw new TypeError('some() requires a non-nullable value');
112
+ }
113
+ return someUnchecked(value);
103
114
  }
104
115
 
105
116
  /** Constant representing None. Alias for NONE. */
@@ -125,10 +136,6 @@ function ResultErrorCtor<E>(this: ResultErrorShape<E>, error: E): void {
125
136
  /** The error wrapper type used internally. */
126
137
  export type ResultError<E> = ResultErrorShape<E>;
127
138
 
128
- function hasErrBrand(value: unknown): value is ResultError<unknown> {
129
- return (value as Record<symbol, unknown>)?.[ERR_BRAND] === true;
130
- }
131
-
132
139
  /** Represents a failed Result containing an error. */
133
140
  export type Err<E> = ResultError<E>;
134
141
 
@@ -158,8 +165,9 @@ export type InferErr<T> = T extends Err<infer TError> ? Err<TError> : never;
158
165
  export function isOk<T>(result: Ok<T>): true;
159
166
  export function isOk<E>(result: Err<E>): false;
160
167
  export function isOk<T, E>(result: Result<T, E>): result is Ok<T>;
161
- export function isOk<T, E>(result: Result<T, E>): boolean {
162
- return !hasErrBrand(result);
168
+ export function isOk(result: unknown): boolean;
169
+ export function isOk(result: unknown): boolean {
170
+ return !(result as Record<symbol, unknown>)?.[ERR_BRAND];
163
171
  }
164
172
 
165
173
  /**
@@ -171,21 +179,30 @@ export function isOk<T, E>(result: Result<T, E>): boolean {
171
179
  * isErr(42) // false (Ok value)
172
180
  */
173
181
  export function isErr<E>(result: Err<E>): true;
174
- export function isErr(result: Ok<any>): false;
182
+ export function isErr(result: Ok<unknown>): false;
175
183
  export function isErr<T, E>(result: Result<T, E>): result is Err<E>;
176
- export function isErr<T, E>(result: Result<T, E>): boolean {
177
- return hasErrBrand(result);
184
+ export function isErr(result: unknown): result is Err<unknown>;
185
+ export function isErr(result: unknown): boolean {
186
+ return (result as Record<symbol, unknown>)?.[ERR_BRAND] === true;
187
+ }
188
+
189
+ export function okUnchecked<T>(value: T): Ok<T> {
190
+ return value as Ok<T>;
178
191
  }
179
192
 
180
193
  /**
181
- * Creates an Ok value. Does not validate - use safe.ok() for validation.
194
+ * Creates an Ok value with runtime validation.
182
195
  * @param value - The success value
183
196
  * @returns The value typed as Ok
197
+ * @throws TypeError if value is an Err
184
198
  * @example
185
199
  * ok(42) // Ok(42)
186
200
  */
187
201
  export function ok<T>(value: T): Ok<T> {
188
- return value as Ok<T>;
202
+ if (isErr(value)) {
203
+ throw new TypeError('ok() cannot wrap an Err value');
204
+ }
205
+ return okUnchecked(value);
189
206
  }
190
207
 
191
208
  /**
@@ -199,3 +216,24 @@ export function ok<T>(value: T): Ok<T> {
199
216
  export function err<E>(error: E): Err<E> {
200
217
  return new (ResultErrorCtor as unknown as new (error: E) => Err<E>)(error);
201
218
  }
219
+
220
+ /** A value that may or may not be a Promise. */
221
+ export type MaybePromise<T> = T | Promise<T> | PromiseLike<T>;
222
+
223
+ /**
224
+ * Checks if a value is a thenable (has a .then method).
225
+ * @param value - The value to check
226
+ * @returns true if value is a PromiseLike
227
+ */
228
+ export function isThenable<T>(value: MaybePromise<T>): value is PromiseLike<T> {
229
+ return typeof (value as PromiseLike<T>)?.then === 'function';
230
+ }
231
+
232
+ /**
233
+ * Checks if a value is synchronous (not a thenable).
234
+ * @param value - The value to check
235
+ * @returns true if value is not a PromiseLike
236
+ */
237
+ export function isSync<T>(value: MaybePromise<T>): value is T {
238
+ return typeof (value as PromiseLike<T>)?.then !== 'function';
239
+ }
package/src/unsafe.ts CHANGED
@@ -1,47 +1,2 @@
1
- import type { Some, Ok } from './types.js';
2
- export { none, err } from './types.js';
3
- export type {
4
- Some,
5
- None,
6
- Ok,
7
- Err,
8
- Option as OptionType,
9
- OptionValue,
10
- IsOption,
11
- InferSome,
12
- Result as ResultType,
13
- ResultValue,
14
- ResultErrorType,
15
- IsResult,
16
- InferErr,
17
- } from './types.js';
18
- export * as Option from './option.js';
19
- export * as Result from './result.js';
20
-
21
- /**
22
- * Creates a Some value without runtime validation.
23
- * Use when you are certain the value is non-nullable.
24
- * For validated creation, use safe.some() instead.
25
- * @param value - The value to wrap (assumed non-nullable)
26
- * @returns The value typed as Some
27
- * @example
28
- * some(42) // Some(42)
29
- * some(null) // Some(null) - no validation, may cause issues
30
- */
31
- export function some<T>(value: T): Some<T> {
32
- return value as unknown as Some<T>;
33
- }
34
-
35
- /**
36
- * Creates an Ok value without runtime validation.
37
- * Use when you are certain the value is not an Err.
38
- * For validated creation, use safe.ok() instead.
39
- * @param value - The success value (assumed not an Err)
40
- * @returns The value typed as Ok
41
- * @example
42
- * ok(42) // Ok(42)
43
- * ok(err('fail')) // Ok(Err) - no validation, may cause issues
44
- */
45
- export function ok<T>(value: T): Ok<T> {
46
- return value as Ok<T>;
47
- }
1
+ export * from './safe.js';
2
+ export { someUnchecked as some, okUnchecked as ok } from './types.js';
@@ -1,79 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: Object.getOwnPropertyDescriptor(all, name).get
9
- });
10
- }
11
- _export(exports, {
12
- get formatOption () {
13
- return formatOption;
14
- },
15
- get formatResult () {
16
- return formatResult;
17
- },
18
- get inspectOption () {
19
- return inspectOption;
20
- },
21
- get inspectResult () {
22
- return inspectResult;
23
- },
24
- get logOption () {
25
- return logOption;
26
- },
27
- get logResult () {
28
- return logResult;
29
- },
30
- get toJSONOption () {
31
- return toJSONOption;
32
- },
33
- get toJSONResult () {
34
- return toJSONResult;
35
- }
36
- });
37
- const _typescjs = require("./types.cjs");
38
- function formatOption(opt) {
39
- return (0, _typescjs.isSome)(opt) ? `Some(${String(opt)})` : 'None';
40
- }
41
- function formatResult(result) {
42
- if ((0, _typescjs.isOk)(result)) {
43
- return `Ok(${String(result)})`;
44
- }
45
- const error = result.error;
46
- return `Err(${error instanceof Error ? error.message : String(error)})`;
47
- }
48
- function inspectOption(opt) {
49
- return (0, _typescjs.isSome)(opt) ? {
50
- kind: 'some',
51
- value: opt
52
- } : {
53
- kind: 'none'
54
- };
55
- }
56
- function inspectResult(result) {
57
- return (0, _typescjs.isOk)(result) ? {
58
- status: 'ok',
59
- value: result
60
- } : {
61
- status: 'err',
62
- error: result.error
63
- };
64
- }
65
- function logOption(opt, logger = console.log) {
66
- logger(formatOption(opt));
67
- }
68
- function logResult(result, logger = console.log) {
69
- const tagged = inspectResult(result);
70
- if (tagged.status === 'ok') {
71
- logger(`Ok`, tagged.value);
72
- return;
73
- }
74
- logger(`Err`, tagged.error);
75
- }
76
- const toJSONOption = inspectOption;
77
- const toJSONResult = inspectResult;
78
-
79
- //# sourceMappingURL=devtools.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/devtools.ts"],"sourcesContent":["import { Option, Result, isSome, isOk } from './types.js';\n\n/** Logger function signature for custom logging. */\ntype Logger = (message: string, ...args: unknown[]) => void;\n\n/**\n * Formats an Option as a human-readable string.\n * @param opt - The Option to format\n * @returns \"Some(value)\" or \"None\"\n * @example\n * formatOption(42) // \"Some(42)\"\n * formatOption(null) // \"None\"\n * formatOption(undefined) // \"None\"\n */\nexport function formatOption<T>(opt: Option<T>): string {\n return isSome(opt) ? `Some(${String(opt)})` : 'None';\n}\n\n/**\n * Formats a Result as a human-readable string.\n * For Err containing an Error, displays the error message.\n * @param result - The Result to format\n * @returns \"Ok(value)\" or \"Err(error)\"\n * @example\n * formatResult(42) // \"Ok(42)\"\n * formatResult(err('fail')) // \"Err(fail)\"\n * formatResult(err(new Error('oops'))) // \"Err(oops)\"\n */\nexport function formatResult<T, E>(result: Result<T, E>): string {\n if (isOk(result)) {\n return `Ok(${String(result)})`;\n }\n const error = (result as { error: E }).error;\n return `Err(${error instanceof Error ? error.message : String(error)})`;\n}\n\n/**\n * Inspects an Option, returning a tagged object for debugging or serialization.\n * @param opt - The Option to inspect\n * @returns `{ kind: 'some', value: T }` or `{ kind: 'none' }`\n * @example\n * inspectOption(42) // { kind: 'some', value: 42 }\n * inspectOption(null) // { kind: 'none' }\n */\nexport function inspectOption<T>(opt: Option<T>) {\n return isSome(opt) ? { kind: 'some' as const, value: opt } : { kind: 'none' as const };\n}\n\n/**\n * Inspects a Result, returning a tagged object for debugging or serialization.\n * @param result - The Result to inspect\n * @returns `{ status: 'ok', value: T }` or `{ status: 'err', error: E }`\n * @example\n * inspectResult(42) // { status: 'ok', value: 42 }\n * inspectResult(err('fail')) // { status: 'err', error: 'fail' }\n */\nexport function inspectResult<T, E>(result: Result<T, E>) {\n return isOk(result) ? { status: 'ok' as const, value: result } : { status: 'err' as const, error: (result as { error: E }).error };\n}\n\n/**\n * Logs an Option using the provided logger (defaults to console.log).\n * @param opt - The Option to log\n * @param logger - The logging function to use\n * @example\n * logOption(42) // logs \"Some(42)\"\n * logOption(null) // logs \"None\"\n * logOption(42, console.warn) // logs \"Some(42)\" as warning\n */\nexport function logOption<T>(opt: Option<T>, logger: Logger = console.log): void {\n logger(formatOption(opt));\n}\n\n/**\n * Logs a Result using the provided logger (defaults to console.log).\n * Logs \"Ok\" with the value or \"Err\" with the error.\n * @param result - The Result to log\n * @param logger - The logging function to use\n * @example\n * logResult(42) // logs \"Ok\", 42\n * logResult(err('fail')) // logs \"Err\", \"fail\"\n * logResult(42, console.warn) // logs \"Ok\", 42 as warning\n */\nexport function logResult<T, E>(result: Result<T, E>, logger: Logger = console.log): void {\n const tagged = inspectResult(result);\n if (tagged.status === 'ok') {\n logger(`Ok`, tagged.value);\n return;\n }\n logger(`Err`, tagged.error);\n}\n\n/** Alias for inspectOption. Returns a JSON-serializable representation. */\nexport const toJSONOption = inspectOption;\n\n/** Alias for inspectResult. Returns a JSON-serializable representation. */\nexport const toJSONResult = inspectResult;\n"],"names":["formatOption","formatResult","inspectOption","inspectResult","logOption","logResult","toJSONOption","toJSONResult","opt","isSome","String","result","isOk","error","Error","message","kind","value","status","logger","console","log","tagged"],"mappings":";;;;;;;;;;;QAcgBA;eAAAA;;QAcAC;eAAAA;;QAgBAC;eAAAA;;QAYAC;eAAAA;;QAaAC;eAAAA;;QAcAC;eAAAA;;QAUHC;eAAAA;;QAGAC;eAAAA;;;0BAhGgC;AActC,SAASP,aAAgBQ,GAAc;IAC5C,OAAOC,IAAAA,gBAAM,EAACD,OAAO,CAAC,KAAK,EAAEE,OAAOF,KAAK,CAAC,CAAC,GAAG;AAChD;AAYO,SAASP,aAAmBU,MAAoB;IACrD,IAAIC,IAAAA,cAAI,EAACD,SAAS;QAChB,OAAO,CAAC,GAAG,EAAED,OAAOC,QAAQ,CAAC,CAAC;IAChC;IACA,MAAME,QAAQ,AAACF,OAAwBE,KAAK;IAC5C,OAAO,CAAC,IAAI,EAAEA,iBAAiBC,QAAQD,MAAME,OAAO,GAAGL,OAAOG,OAAO,CAAC,CAAC;AACzE;AAUO,SAASX,cAAiBM,GAAc;IAC7C,OAAOC,IAAAA,gBAAM,EAACD,OAAO;QAAEQ,MAAM;QAAiBC,OAAOT;IAAI,IAAI;QAAEQ,MAAM;IAAgB;AACvF;AAUO,SAASb,cAAoBQ,MAAoB;IACtD,OAAOC,IAAAA,cAAI,EAACD,UAAU;QAAEO,QAAQ;QAAeD,OAAON;IAAO,IAAI;QAAEO,QAAQ;QAAgBL,OAAO,AAACF,OAAwBE,KAAK;IAAC;AACnI;AAWO,SAAST,UAAaI,GAAc,EAAEW,SAAiBC,QAAQC,GAAG;IACvEF,OAAOnB,aAAaQ;AACtB;AAYO,SAASH,UAAgBM,MAAoB,EAAEQ,SAAiBC,QAAQC,GAAG;IAChF,MAAMC,SAASnB,cAAcQ;IAC7B,IAAIW,OAAOJ,MAAM,KAAK,MAAM;QAC1BC,OAAO,CAAC,EAAE,CAAC,EAAEG,OAAOL,KAAK;QACzB;IACF;IACAE,OAAO,CAAC,GAAG,CAAC,EAAEG,OAAOT,KAAK;AAC5B;AAGO,MAAMP,eAAeJ;AAGrB,MAAMK,eAAeJ"}
@@ -1,82 +0,0 @@
1
- import { Option, Result } from './types.js';
2
- /** Logger function signature for custom logging. */
3
- type Logger = (message: string, ...args: unknown[]) => void;
4
- /**
5
- * Formats an Option as a human-readable string.
6
- * @param opt - The Option to format
7
- * @returns "Some(value)" or "None"
8
- * @example
9
- * formatOption(42) // "Some(42)"
10
- * formatOption(null) // "None"
11
- * formatOption(undefined) // "None"
12
- */
13
- export declare function formatOption<T>(opt: Option<T>): string;
14
- /**
15
- * Formats a Result as a human-readable string.
16
- * For Err containing an Error, displays the error message.
17
- * @param result - The Result to format
18
- * @returns "Ok(value)" or "Err(error)"
19
- * @example
20
- * formatResult(42) // "Ok(42)"
21
- * formatResult(err('fail')) // "Err(fail)"
22
- * formatResult(err(new Error('oops'))) // "Err(oops)"
23
- */
24
- export declare function formatResult<T, E>(result: Result<T, E>): string;
25
- /**
26
- * Inspects an Option, returning a tagged object for debugging or serialization.
27
- * @param opt - The Option to inspect
28
- * @returns `{ kind: 'some', value: T }` or `{ kind: 'none' }`
29
- * @example
30
- * inspectOption(42) // { kind: 'some', value: 42 }
31
- * inspectOption(null) // { kind: 'none' }
32
- */
33
- export declare function inspectOption<T>(opt: Option<T>): {
34
- kind: "some";
35
- value: import("./types.js").Some<Exclude<T, import("./types.js").NoneValueType>>;
36
- } | {
37
- kind: "none";
38
- value?: undefined;
39
- };
40
- /**
41
- * Inspects a Result, returning a tagged object for debugging or serialization.
42
- * @param result - The Result to inspect
43
- * @returns `{ status: 'ok', value: T }` or `{ status: 'err', error: E }`
44
- * @example
45
- * inspectResult(42) // { status: 'ok', value: 42 }
46
- * inspectResult(err('fail')) // { status: 'err', error: 'fail' }
47
- */
48
- export declare function inspectResult<T, E>(result: Result<T, E>): {
49
- status: "ok";
50
- value: import("./types.js").Ok<T>;
51
- error?: undefined;
52
- } | {
53
- status: "err";
54
- error: E;
55
- value?: undefined;
56
- };
57
- /**
58
- * Logs an Option using the provided logger (defaults to console.log).
59
- * @param opt - The Option to log
60
- * @param logger - The logging function to use
61
- * @example
62
- * logOption(42) // logs "Some(42)"
63
- * logOption(null) // logs "None"
64
- * logOption(42, console.warn) // logs "Some(42)" as warning
65
- */
66
- export declare function logOption<T>(opt: Option<T>, logger?: Logger): void;
67
- /**
68
- * Logs a Result using the provided logger (defaults to console.log).
69
- * Logs "Ok" with the value or "Err" with the error.
70
- * @param result - The Result to log
71
- * @param logger - The logging function to use
72
- * @example
73
- * logResult(42) // logs "Ok", 42
74
- * logResult(err('fail')) // logs "Err", "fail"
75
- * logResult(42, console.warn) // logs "Ok", 42 as warning
76
- */
77
- export declare function logResult<T, E>(result: Result<T, E>, logger?: Logger): void;
78
- /** Alias for inspectOption. Returns a JSON-serializable representation. */
79
- export declare const toJSONOption: typeof inspectOption;
80
- /** Alias for inspectResult. Returns a JSON-serializable representation. */
81
- export declare const toJSONResult: typeof inspectResult;
82
- export {};
package/build/devtools.js DELETED
@@ -1,43 +0,0 @@
1
- import { isSome, isOk } from "./types.js";
2
- export function formatOption(opt) {
3
- return isSome(opt) ? `Some(${String(opt)})` : 'None';
4
- }
5
- export function formatResult(result) {
6
- if (isOk(result)) {
7
- return `Ok(${String(result)})`;
8
- }
9
- const error = result.error;
10
- return `Err(${error instanceof Error ? error.message : String(error)})`;
11
- }
12
- export function inspectOption(opt) {
13
- return isSome(opt) ? {
14
- kind: 'some',
15
- value: opt
16
- } : {
17
- kind: 'none'
18
- };
19
- }
20
- export function inspectResult(result) {
21
- return isOk(result) ? {
22
- status: 'ok',
23
- value: result
24
- } : {
25
- status: 'err',
26
- error: result.error
27
- };
28
- }
29
- export function logOption(opt, logger = console.log) {
30
- logger(formatOption(opt));
31
- }
32
- export function logResult(result, logger = console.log) {
33
- const tagged = inspectResult(result);
34
- if (tagged.status === 'ok') {
35
- logger(`Ok`, tagged.value);
36
- return;
37
- }
38
- logger(`Err`, tagged.error);
39
- }
40
- export const toJSONOption = inspectOption;
41
- export const toJSONResult = inspectResult;
42
-
43
- //# sourceMappingURL=devtools.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/devtools.ts"],"sourcesContent":["import { Option, Result, isSome, isOk } from './types.js';\n\n/** Logger function signature for custom logging. */\ntype Logger = (message: string, ...args: unknown[]) => void;\n\n/**\n * Formats an Option as a human-readable string.\n * @param opt - The Option to format\n * @returns \"Some(value)\" or \"None\"\n * @example\n * formatOption(42) // \"Some(42)\"\n * formatOption(null) // \"None\"\n * formatOption(undefined) // \"None\"\n */\nexport function formatOption<T>(opt: Option<T>): string {\n return isSome(opt) ? `Some(${String(opt)})` : 'None';\n}\n\n/**\n * Formats a Result as a human-readable string.\n * For Err containing an Error, displays the error message.\n * @param result - The Result to format\n * @returns \"Ok(value)\" or \"Err(error)\"\n * @example\n * formatResult(42) // \"Ok(42)\"\n * formatResult(err('fail')) // \"Err(fail)\"\n * formatResult(err(new Error('oops'))) // \"Err(oops)\"\n */\nexport function formatResult<T, E>(result: Result<T, E>): string {\n if (isOk(result)) {\n return `Ok(${String(result)})`;\n }\n const error = (result as { error: E }).error;\n return `Err(${error instanceof Error ? error.message : String(error)})`;\n}\n\n/**\n * Inspects an Option, returning a tagged object for debugging or serialization.\n * @param opt - The Option to inspect\n * @returns `{ kind: 'some', value: T }` or `{ kind: 'none' }`\n * @example\n * inspectOption(42) // { kind: 'some', value: 42 }\n * inspectOption(null) // { kind: 'none' }\n */\nexport function inspectOption<T>(opt: Option<T>) {\n return isSome(opt) ? { kind: 'some' as const, value: opt } : { kind: 'none' as const };\n}\n\n/**\n * Inspects a Result, returning a tagged object for debugging or serialization.\n * @param result - The Result to inspect\n * @returns `{ status: 'ok', value: T }` or `{ status: 'err', error: E }`\n * @example\n * inspectResult(42) // { status: 'ok', value: 42 }\n * inspectResult(err('fail')) // { status: 'err', error: 'fail' }\n */\nexport function inspectResult<T, E>(result: Result<T, E>) {\n return isOk(result) ? { status: 'ok' as const, value: result } : { status: 'err' as const, error: (result as { error: E }).error };\n}\n\n/**\n * Logs an Option using the provided logger (defaults to console.log).\n * @param opt - The Option to log\n * @param logger - The logging function to use\n * @example\n * logOption(42) // logs \"Some(42)\"\n * logOption(null) // logs \"None\"\n * logOption(42, console.warn) // logs \"Some(42)\" as warning\n */\nexport function logOption<T>(opt: Option<T>, logger: Logger = console.log): void {\n logger(formatOption(opt));\n}\n\n/**\n * Logs a Result using the provided logger (defaults to console.log).\n * Logs \"Ok\" with the value or \"Err\" with the error.\n * @param result - The Result to log\n * @param logger - The logging function to use\n * @example\n * logResult(42) // logs \"Ok\", 42\n * logResult(err('fail')) // logs \"Err\", \"fail\"\n * logResult(42, console.warn) // logs \"Ok\", 42 as warning\n */\nexport function logResult<T, E>(result: Result<T, E>, logger: Logger = console.log): void {\n const tagged = inspectResult(result);\n if (tagged.status === 'ok') {\n logger(`Ok`, tagged.value);\n return;\n }\n logger(`Err`, tagged.error);\n}\n\n/** Alias for inspectOption. Returns a JSON-serializable representation. */\nexport const toJSONOption = inspectOption;\n\n/** Alias for inspectResult. Returns a JSON-serializable representation. */\nexport const toJSONResult = inspectResult;\n"],"names":["isSome","isOk","formatOption","opt","String","formatResult","result","error","Error","message","inspectOption","kind","value","inspectResult","status","logOption","logger","console","log","logResult","tagged","toJSONOption","toJSONResult"],"mappings":"AAAA,SAAyBA,MAAM,EAAEC,IAAI,QAAQ,aAAa;AAc1D,OAAO,SAASC,aAAgBC,GAAc;IAC5C,OAAOH,OAAOG,OAAO,CAAC,KAAK,EAAEC,OAAOD,KAAK,CAAC,CAAC,GAAG;AAChD;AAYA,OAAO,SAASE,aAAmBC,MAAoB;IACrD,IAAIL,KAAKK,SAAS;QAChB,OAAO,CAAC,GAAG,EAAEF,OAAOE,QAAQ,CAAC,CAAC;IAChC;IACA,MAAMC,QAAQ,AAACD,OAAwBC,KAAK;IAC5C,OAAO,CAAC,IAAI,EAAEA,iBAAiBC,QAAQD,MAAME,OAAO,GAAGL,OAAOG,OAAO,CAAC,CAAC;AACzE;AAUA,OAAO,SAASG,cAAiBP,GAAc;IAC7C,OAAOH,OAAOG,OAAO;QAAEQ,MAAM;QAAiBC,OAAOT;IAAI,IAAI;QAAEQ,MAAM;IAAgB;AACvF;AAUA,OAAO,SAASE,cAAoBP,MAAoB;IACtD,OAAOL,KAAKK,UAAU;QAAEQ,QAAQ;QAAeF,OAAON;IAAO,IAAI;QAAEQ,QAAQ;QAAgBP,OAAO,AAACD,OAAwBC,KAAK;IAAC;AACnI;AAWA,OAAO,SAASQ,UAAaZ,GAAc,EAAEa,SAAiBC,QAAQC,GAAG;IACvEF,OAAOd,aAAaC;AACtB;AAYA,OAAO,SAASgB,UAAgBb,MAAoB,EAAEU,SAAiBC,QAAQC,GAAG;IAChF,MAAME,SAASP,cAAcP;IAC7B,IAAIc,OAAON,MAAM,KAAK,MAAM;QAC1BE,OAAO,CAAC,EAAE,CAAC,EAAEI,OAAOR,KAAK;QACzB;IACF;IACAI,OAAO,CAAC,GAAG,CAAC,EAAEI,OAAOb,KAAK;AAC5B;AAGA,OAAO,MAAMc,eAAeX,cAAc;AAG1C,OAAO,MAAMY,eAAeT,cAAc"}
package/build/testing.cjs DELETED
@@ -1,111 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: Object.getOwnPropertyDescriptor(all, name).get
9
- });
10
- }
11
- _export(exports, {
12
- get expectErr () {
13
- return expectErr;
14
- },
15
- get expectNone () {
16
- return expectNone;
17
- },
18
- get expectOk () {
19
- return expectOk;
20
- },
21
- get expectSome () {
22
- return expectSome;
23
- },
24
- get extendExpect () {
25
- return extendExpect;
26
- },
27
- get matchers () {
28
- return matchers;
29
- }
30
- });
31
- const _typescjs = require("./types.cjs");
32
- const _devtoolscjs = require("./devtools.cjs");
33
- function expectOk(result, message) {
34
- if ((0, _typescjs.isOk)(result)) {
35
- return result;
36
- }
37
- const fallback = message ?? `Expected Ok(...) but received ${(0, _devtoolscjs.formatResult)(result)}`;
38
- throw new Error(fallback);
39
- }
40
- function expectErr(result, message) {
41
- if ((0, _typescjs.isErr)(result)) {
42
- return result.error;
43
- }
44
- const fallback = message ?? `Expected Err(...) but received ${(0, _devtoolscjs.formatResult)(result)}`;
45
- throw new Error(fallback);
46
- }
47
- function expectSome(opt, message) {
48
- if ((0, _typescjs.isSome)(opt)) {
49
- return opt;
50
- }
51
- const fallback = message ?? `Expected Some(...) but received ${(0, _devtoolscjs.formatOption)(opt)}`;
52
- throw new Error(fallback);
53
- }
54
- function expectNone(opt, message) {
55
- if ((0, _typescjs.isNone)(opt)) {
56
- return;
57
- }
58
- const fallback = message ?? `Expected None but received ${(0, _devtoolscjs.formatOption)(opt)}`;
59
- throw new Error(fallback);
60
- }
61
- const resultMatchers = {
62
- toBeOk (received) {
63
- const pass = (0, _typescjs.isOk)(received);
64
- return {
65
- pass,
66
- message: ()=>pass ? 'Result is Ok as expected.' : `Expected Ok(...) but received ${(0, _devtoolscjs.formatResult)(received)}`
67
- };
68
- },
69
- toBeErr (received) {
70
- const pass = (0, _typescjs.isErr)(received);
71
- return {
72
- pass,
73
- message: ()=>pass ? 'Result is Err as expected.' : `Expected Err(...) but received ${(0, _devtoolscjs.formatResult)(received)}`
74
- };
75
- },
76
- toContainErr (received, expected) {
77
- const pass = (0, _typescjs.isErr)(received) && received.error === expected;
78
- return {
79
- pass,
80
- message: ()=>{
81
- if (pass) return `Err matched expected value ${String(expected)}.`;
82
- return `Expected Err(${String(expected)}) but received ${(0, _devtoolscjs.formatResult)(received)}`;
83
- }
84
- };
85
- }
86
- };
87
- const optionMatchers = {
88
- toBeSome (received) {
89
- const pass = (0, _typescjs.isSome)(received);
90
- return {
91
- pass,
92
- message: ()=>pass ? 'Option is Some as expected.' : `Expected Some(...) but received ${(0, _devtoolscjs.formatOption)(received)}`
93
- };
94
- },
95
- toBeNone (received) {
96
- const pass = (0, _typescjs.isNone)(received);
97
- return {
98
- pass,
99
- message: ()=>pass ? 'Option is None as expected.' : `Expected None but received ${(0, _devtoolscjs.formatOption)(received)}`
100
- };
101
- }
102
- };
103
- const matchers = {
104
- ...resultMatchers,
105
- ...optionMatchers
106
- };
107
- function extendExpect(expectLike) {
108
- expectLike.extend(matchers);
109
- }
110
-
111
- //# sourceMappingURL=testing.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/testing.ts"],"sourcesContent":["import { isOk, isErr, isSome, isNone, Result, Err, Option } from './types.js';\nimport { formatOption, formatResult } from './devtools.js';\n\n/** Result shape returned by custom matchers. */\ntype MatcherResult = { pass: boolean; message(): string };\n\n/**\n * Asserts that a Result is Ok and returns the value.\n * Throws if the Result is Err.\n * @param result - The Result to check\n * @param message - Optional custom error message\n * @returns The Ok value\n * @throws {Error} If the Result is Err\n * @example\n * expectOk(ok(42)) // returns 42\n * expectOk(err('fail')) // throws Error\n */\nexport function expectOk<T, E>(result: Result<T, E>, message?: string): T {\n if (isOk(result)) {\n return result;\n }\n\n const fallback = message ?? `Expected Ok(...) but received ${formatResult(result)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that a Result is Err and returns the error.\n * Throws if the Result is Ok.\n * @param result - The Result to check\n * @param message - Optional custom error message\n * @returns The error value\n * @throws {Error} If the Result is Ok\n * @example\n * expectErr(err('fail')) // returns 'fail'\n * expectErr(ok(42)) // throws Error\n */\nexport function expectErr<T, E>(result: Result<T, E>, message?: string): E {\n if (isErr(result)) {\n return (result as Err<E>).error;\n }\n\n const fallback = message ?? `Expected Err(...) but received ${formatResult(result)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that an Option is Some and returns the value.\n * Throws if the Option is None.\n * @param opt - The Option to check\n * @param message - Optional custom error message\n * @returns The Some value\n * @throws {Error} If the Option is None\n * @example\n * expectSome(42) // returns 42\n * expectSome(null) // throws Error\n */\nexport function expectSome<T>(opt: Option<T>, message?: string): T {\n if (isSome(opt)) {\n return opt;\n }\n const fallback = message ?? `Expected Some(...) but received ${formatOption(opt)}`;\n throw new Error(fallback);\n}\n\n/**\n * Asserts that an Option is None.\n * Throws if the Option is Some.\n * @param opt - The Option to check\n * @param message - Optional custom error message\n * @throws {Error} If the Option is Some\n * @example\n * expectNone(null) // succeeds\n * expectNone(42) // throws Error\n */\nexport function expectNone<T>(opt: Option<T>, message?: string): void {\n if (isNone(opt)) {\n return;\n }\n const fallback = message ?? `Expected None but received ${formatOption(opt)}`;\n throw new Error(fallback);\n}\n\nconst resultMatchers = {\n toBeOk(this: unknown, received: Result<unknown, unknown>): MatcherResult {\n const pass = isOk(received);\n return {\n pass,\n message: () => (pass ? 'Result is Ok as expected.' : `Expected Ok(...) but received ${formatResult(received)}`),\n };\n },\n toBeErr(this: unknown, received: Result<unknown, unknown>): MatcherResult {\n const pass = isErr(received);\n return {\n pass,\n message: () => (pass ? 'Result is Err as expected.' : `Expected Err(...) but received ${formatResult(received)}`),\n };\n },\n toContainErr(this: unknown, received: Result<unknown, unknown>, expected: unknown): MatcherResult {\n const pass = isErr(received) && (received as Err<unknown>).error === expected;\n return {\n pass,\n message: () => {\n if (pass) return `Err matched expected value ${String(expected)}.`;\n return `Expected Err(${String(expected)}) but received ${formatResult(received)}`;\n },\n };\n },\n};\n\nconst optionMatchers = {\n toBeSome(this: unknown, received: Option<unknown>): MatcherResult {\n const pass = isSome(received);\n return {\n pass,\n message: () => (pass ? 'Option is Some as expected.' : `Expected Some(...) but received ${formatOption(received)}`),\n };\n },\n toBeNone(this: unknown, received: Option<unknown>): MatcherResult {\n const pass = isNone(received);\n return {\n pass,\n message: () => (pass ? 'Option is None as expected.' : `Expected None but received ${formatOption(received)}`),\n };\n },\n};\n\n/**\n * Custom matchers for Jest/Vitest.\n * Includes toBeOk, toBeErr, toContainErr, toBeSome, toBeNone.\n * Use with expect.extend(matchers) or extendExpect(expect).\n */\nexport const matchers = {\n ...resultMatchers,\n ...optionMatchers,\n};\n\n/** Interface for test frameworks with an extend method (Jest, Vitest). */\nexport type ExpectLike = {\n extend(matchers: Record<string, (...args: any[]) => MatcherResult>): void;\n};\n\n/**\n * Extends a test framework's expect with Option and Result matchers.\n * @param expectLike - The expect object to extend (Jest/Vitest)\n * @example\n * import { expect } from 'vitest';\n * import { extendExpect } from 'nalloc/testing';\n * extendExpect(expect);\n *\n * // Now you can use:\n * expect(result).toBeOk();\n * expect(result).toBeErr();\n * expect(option).toBeSome();\n * expect(option).toBeNone();\n */\nexport function extendExpect(expectLike: ExpectLike): void {\n expectLike.extend(matchers);\n}\n"],"names":["expectErr","expectNone","expectOk","expectSome","extendExpect","matchers","result","message","isOk","fallback","formatResult","Error","isErr","error","opt","isSome","formatOption","isNone","resultMatchers","toBeOk","received","pass","toBeErr","toContainErr","expected","String","optionMatchers","toBeSome","toBeNone","expectLike","extend"],"mappings":";;;;;;;;;;;QAqCgBA;eAAAA;;QAsCAC;eAAAA;;QA1DAC;eAAAA;;QAwCAC;eAAAA;;QAmGAC;eAAAA;;QAxBHC;eAAAA;;;0BApIoD;6BACtB;AAgBpC,SAASH,SAAeI,MAAoB,EAAEC,OAAgB;IACnE,IAAIC,IAAAA,cAAI,EAACF,SAAS;QAChB,OAAOA;IACT;IAEA,MAAMG,WAAWF,WAAW,CAAC,8BAA8B,EAAEG,IAAAA,yBAAY,EAACJ,SAAS;IACnF,MAAM,IAAIK,MAAMF;AAClB;AAaO,SAAST,UAAgBM,MAAoB,EAAEC,OAAgB;IACpE,IAAIK,IAAAA,eAAK,EAACN,SAAS;QACjB,OAAO,AAACA,OAAkBO,KAAK;IACjC;IAEA,MAAMJ,WAAWF,WAAW,CAAC,+BAA+B,EAAEG,IAAAA,yBAAY,EAACJ,SAAS;IACpF,MAAM,IAAIK,MAAMF;AAClB;AAaO,SAASN,WAAcW,GAAc,EAAEP,OAAgB;IAC5D,IAAIQ,IAAAA,gBAAM,EAACD,MAAM;QACf,OAAOA;IACT;IACA,MAAML,WAAWF,WAAW,CAAC,gCAAgC,EAAES,IAAAA,yBAAY,EAACF,MAAM;IAClF,MAAM,IAAIH,MAAMF;AAClB;AAYO,SAASR,WAAca,GAAc,EAAEP,OAAgB;IAC5D,IAAIU,IAAAA,gBAAM,EAACH,MAAM;QACf;IACF;IACA,MAAML,WAAWF,WAAW,CAAC,2BAA2B,EAAES,IAAAA,yBAAY,EAACF,MAAM;IAC7E,MAAM,IAAIH,MAAMF;AAClB;AAEA,MAAMS,iBAAiB;IACrBC,QAAsBC,QAAkC;QACtD,MAAMC,OAAOb,IAAAA,cAAI,EAACY;QAClB,OAAO;YACLC;YACAd,SAAS,IAAOc,OAAO,8BAA8B,CAAC,8BAA8B,EAAEX,IAAAA,yBAAY,EAACU,WAAW;QAChH;IACF;IACAE,SAAuBF,QAAkC;QACvD,MAAMC,OAAOT,IAAAA,eAAK,EAACQ;QACnB,OAAO;YACLC;YACAd,SAAS,IAAOc,OAAO,+BAA+B,CAAC,+BAA+B,EAAEX,IAAAA,yBAAY,EAACU,WAAW;QAClH;IACF;IACAG,cAA4BH,QAAkC,EAAEI,QAAiB;QAC/E,MAAMH,OAAOT,IAAAA,eAAK,EAACQ,aAAa,AAACA,SAA0BP,KAAK,KAAKW;QACrE,OAAO;YACLH;YACAd,SAAS;gBACP,IAAIc,MAAM,OAAO,CAAC,2BAA2B,EAAEI,OAAOD,UAAU,CAAC,CAAC;gBAClE,OAAO,CAAC,aAAa,EAAEC,OAAOD,UAAU,eAAe,EAAEd,IAAAA,yBAAY,EAACU,WAAW;YACnF;QACF;IACF;AACF;AAEA,MAAMM,iBAAiB;IACrBC,UAAwBP,QAAyB;QAC/C,MAAMC,OAAON,IAAAA,gBAAM,EAACK;QACpB,OAAO;YACLC;YACAd,SAAS,IAAOc,OAAO,gCAAgC,CAAC,gCAAgC,EAAEL,IAAAA,yBAAY,EAACI,WAAW;QACpH;IACF;IACAQ,UAAwBR,QAAyB;QAC/C,MAAMC,OAAOJ,IAAAA,gBAAM,EAACG;QACpB,OAAO;YACLC;YACAd,SAAS,IAAOc,OAAO,gCAAgC,CAAC,2BAA2B,EAAEL,IAAAA,yBAAY,EAACI,WAAW;QAC/G;IACF;AACF;AAOO,MAAMf,WAAW;IACtB,GAAGa,cAAc;IACjB,GAAGQ,cAAc;AACnB;AAqBO,SAAStB,aAAayB,UAAsB;IACjDA,WAAWC,MAAM,CAACzB;AACpB"}
@@ -1,85 +0,0 @@
1
- import { Result, Option } from './types.js';
2
- /** Result shape returned by custom matchers. */
3
- type MatcherResult = {
4
- pass: boolean;
5
- message(): string;
6
- };
7
- /**
8
- * Asserts that a Result is Ok and returns the value.
9
- * Throws if the Result is Err.
10
- * @param result - The Result to check
11
- * @param message - Optional custom error message
12
- * @returns The Ok value
13
- * @throws {Error} If the Result is Err
14
- * @example
15
- * expectOk(ok(42)) // returns 42
16
- * expectOk(err('fail')) // throws Error
17
- */
18
- export declare function expectOk<T, E>(result: Result<T, E>, message?: string): T;
19
- /**
20
- * Asserts that a Result is Err and returns the error.
21
- * Throws if the Result is Ok.
22
- * @param result - The Result to check
23
- * @param message - Optional custom error message
24
- * @returns The error value
25
- * @throws {Error} If the Result is Ok
26
- * @example
27
- * expectErr(err('fail')) // returns 'fail'
28
- * expectErr(ok(42)) // throws Error
29
- */
30
- export declare function expectErr<T, E>(result: Result<T, E>, message?: string): E;
31
- /**
32
- * Asserts that an Option is Some and returns the value.
33
- * Throws if the Option is None.
34
- * @param opt - The Option to check
35
- * @param message - Optional custom error message
36
- * @returns The Some value
37
- * @throws {Error} If the Option is None
38
- * @example
39
- * expectSome(42) // returns 42
40
- * expectSome(null) // throws Error
41
- */
42
- export declare function expectSome<T>(opt: Option<T>, message?: string): T;
43
- /**
44
- * Asserts that an Option is None.
45
- * Throws if the Option is Some.
46
- * @param opt - The Option to check
47
- * @param message - Optional custom error message
48
- * @throws {Error} If the Option is Some
49
- * @example
50
- * expectNone(null) // succeeds
51
- * expectNone(42) // throws Error
52
- */
53
- export declare function expectNone<T>(opt: Option<T>, message?: string): void;
54
- /**
55
- * Custom matchers for Jest/Vitest.
56
- * Includes toBeOk, toBeErr, toContainErr, toBeSome, toBeNone.
57
- * Use with expect.extend(matchers) or extendExpect(expect).
58
- */
59
- export declare const matchers: {
60
- toBeSome(this: unknown, received: Option<unknown>): MatcherResult;
61
- toBeNone(this: unknown, received: Option<unknown>): MatcherResult;
62
- toBeOk(this: unknown, received: Result<unknown, unknown>): MatcherResult;
63
- toBeErr(this: unknown, received: Result<unknown, unknown>): MatcherResult;
64
- toContainErr(this: unknown, received: Result<unknown, unknown>, expected: unknown): MatcherResult;
65
- };
66
- /** Interface for test frameworks with an extend method (Jest, Vitest). */
67
- export type ExpectLike = {
68
- extend(matchers: Record<string, (...args: any[]) => MatcherResult>): void;
69
- };
70
- /**
71
- * Extends a test framework's expect with Option and Result matchers.
72
- * @param expectLike - The expect object to extend (Jest/Vitest)
73
- * @example
74
- * import { expect } from 'vitest';
75
- * import { extendExpect } from 'nalloc/testing';
76
- * extendExpect(expect);
77
- *
78
- * // Now you can use:
79
- * expect(result).toBeOk();
80
- * expect(result).toBeErr();
81
- * expect(option).toBeSome();
82
- * expect(option).toBeNone();
83
- */
84
- export declare function extendExpect(expectLike: ExpectLike): void;
85
- export {};