as-free 0.0.0 → 0.0.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +98 -1
- package/dist/class-constructor-Cl1RwNAF.mjs +13 -0
- package/dist/index.d.mts +168 -0
- package/dist/index.mjs +219 -0
- package/dist/runtime.d.mts +3 -0
- package/dist/runtime.mjs +1 -0
- package/package.json +32 -6
- package/index.js +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 9wick / Kohei Kido
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1 +1,98 @@
|
|
|
1
|
-
|
|
1
|
+
# as-free
|
|
2
|
+
|
|
3
|
+
このパッケージは **「型安全だとわかっているのに、言語機能が足りなくて安全にできない」** 場合に使うものです。
|
|
4
|
+
必要な型アサーションをユーティリティの中に閉じ込め、アプリは `as` を書かずに精密な型を受け取れます。
|
|
5
|
+
|
|
6
|
+
典型例:
|
|
7
|
+
|
|
8
|
+
- `Object.entries()` / `Object.fromEntries()` すると型が消える
|
|
9
|
+
- `JSON.parse()` の戻り値が `unknown` になる
|
|
10
|
+
- DI コンテナが返す値の型パラメータが消える
|
|
11
|
+
|
|
12
|
+
### 1. 何の保証もない `as`
|
|
13
|
+
|
|
14
|
+
型が合わないのでとりあえず黙らせるキャスト。最も危険。
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
const value = someFunction() as MyType; // 根拠なし
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
### 2. 信頼境界の `as`
|
|
21
|
+
|
|
22
|
+
外部入力(API レスポンス、JSON など)にバリデーション付きで型を与えるキャスト。
|
|
23
|
+
バリデーションの正しさに依存する。
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
const parsed = schema.parse(JSON.parse(raw)) as Config;
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### 3. 言語機能不足を補う `as`
|
|
30
|
+
|
|
31
|
+
ランタイムでは正しいことが保証されているが、TypeScript の型システムが表現できないキャスト。
|
|
32
|
+
**このパッケージが対象とするスコープ。**
|
|
33
|
+
|
|
34
|
+
いくつかの小分類がある:
|
|
35
|
+
|
|
36
|
+
#### 3a. 型推論の限界
|
|
37
|
+
|
|
38
|
+
ジェネリクスや高階型の推論が追いつかないケース。
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
// Object.entries() はキーを string に拡げてしまう
|
|
42
|
+
const entries = Object.entries(record) as [keyof T, T[keyof T]][];
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
#### 3b. ナローイング補助
|
|
46
|
+
|
|
47
|
+
型ガードや discriminated union で絞り込んだ後、コンパイラが推論しきれないケース。
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
// switch で全ケースを網羅しているが、コンパイラが絞りきれない末端
|
|
51
|
+
function handle(action: Action) {
|
|
52
|
+
switch (action.type) {
|
|
53
|
+
case "create":
|
|
54
|
+
return processCreate(action as CreateAction);
|
|
55
|
+
// ...
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
> **推奨:** このケースは `ts-pattern` の `match().exhaustive()` を使えば `as` なしで型安全にナローイングできる。標準の `switch` 構文の制約であり、言語機能自体の不足ではないため、`as` ではなく `ts-pattern` の利用を推奨する。
|
|
61
|
+
|
|
62
|
+
### 4. テストモックの `as`
|
|
63
|
+
|
|
64
|
+
テストでオブジェクトの一部だけ用意するためのキャスト。プロダクションコードには入らない。
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const mockUser = { name: "test" } as User;
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### 5. ライブラリ型定義の不備を回避する `as`
|
|
71
|
+
|
|
72
|
+
サードパーティの `@types` が不正確・古い場合に正しい型へ矯正するキャスト。
|
|
73
|
+
外部要因に依存するため、型定義の更新で不要になることがある。
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
// @types/xxx が返り値を string としているが、実際は string | null
|
|
77
|
+
const result = lib.getValue() as string | null;
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
**このパッケージは分類 3(言語機能不足を補う `as`)のみを対象とする。** それ以外の `as` は、それぞれ適切な場所(バリデーション層、テストユーティリティなど)で管理すべきである。
|
|
83
|
+
|
|
84
|
+
## 採用基準
|
|
85
|
+
|
|
86
|
+
型アサーションを使うユーティリティには、以下のすべてが必要です。
|
|
87
|
+
|
|
88
|
+
1. 受け付ける入力の契約と実装から、宣言した戻り値型が実行時に成立することを説明できる。
|
|
89
|
+
2. TypeScript の型検査だけでは、その型の関係を保ったまま処理を書けない。
|
|
90
|
+
3. 型アサーションを関数内に閉じ込めることで、アプリは通常の型検査が効く呼び出しだけで使える。
|
|
91
|
+
|
|
92
|
+
## モジュール
|
|
93
|
+
|
|
94
|
+
- [keyed-value](src/keyed-value/README.md) は、キーと値の型の対応を保つ変換を扱います。
|
|
95
|
+
- [json](src/json/README.md) は、JSON にして保管した値を、同じ型で取り出します。
|
|
96
|
+
- [value-store](src/value-store/README.md) は、有効期間を持つ参照と、型付きキーでの保管を扱います。
|
|
97
|
+
- [callable](src/callable/README.md) は、オーバーロードを保ったまま関数の呼び出しを転送します。
|
|
98
|
+
- [runtime](src/runtime/README.md) は、コンストラクタの判定を扱います。
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// src/runtime/class-constructor.ts
|
|
2
|
+
const isConstructor = (value) => {
|
|
3
|
+
if (typeof value !== "function") return false;
|
|
4
|
+
const probe = new Proxy(value, { construct: () => ({}) });
|
|
5
|
+
try {
|
|
6
|
+
Reflect.construct(probe, []);
|
|
7
|
+
return true;
|
|
8
|
+
} catch (cause) {
|
|
9
|
+
if (!(cause instanceof TypeError)) throw cause;
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
export { isConstructor as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
type AnyFunction = (...args: never[]) => unknown;
|
|
2
|
+
type Overload = readonly [args: unknown, result: unknown];
|
|
3
|
+
type Slots<F> = F extends {
|
|
4
|
+
(...args: infer A1): infer R1;
|
|
5
|
+
(...args: infer A2): infer R2;
|
|
6
|
+
(...args: infer A3): infer R3;
|
|
7
|
+
(...args: infer A4): infer R4;
|
|
8
|
+
(...args: infer A5): infer R5;
|
|
9
|
+
} ? [[A1, R1], [A2, R2], [A3, R3], [A4, R4], [A5, R5]] : never;
|
|
10
|
+
type Same$1<X, Y> = (<V>() => V extends X ? 1 : 2) extends (<V>() => (V extends Y ? 1 : 2)) ? true : false;
|
|
11
|
+
type RepeatsLater<S> = S extends [infer Head, ...infer Rest] ? true extends { [K in keyof Rest]: Same$1<Head, Rest[K]>; }[number] ? true : false : false;
|
|
12
|
+
type Overloads<F> = F extends unknown ? RepeatsLater<Slots<F>> extends true ? Extract<Slots<F>[number], Overload> : never : never;
|
|
13
|
+
type FitsSlots<F> = F extends unknown ? ([Overloads<F>] extends [never] ? false : true) : never;
|
|
14
|
+
type OverloadArgs<F> = Overloads<F>[0];
|
|
15
|
+
type OverloadResult<F> = Overloads<F>[1];
|
|
16
|
+
type Intersect<U> = (U extends unknown ? (member: U) => void : never) extends ((member: infer I) => void) ? I : never;
|
|
17
|
+
declare const CALL: unique symbol;
|
|
18
|
+
type CallMark<Id> = {
|
|
19
|
+
readonly [CALL]: (id: Id) => Id;
|
|
20
|
+
};
|
|
21
|
+
type CallArgs<Id, Args> = Readonly<Args> & CallMark<Id>;
|
|
22
|
+
type Forwarded<Id> = CallMark<Id>;
|
|
23
|
+
type Forward<Id, Parts extends readonly AnyFunction[]> = <Part extends Parts[number]>(to: Part, args: CallArgs<Id, OverloadArgs<Part>>) => Forwarded<Id>;
|
|
24
|
+
type Parts = readonly [AnyFunction, ...AnyFunction[]];
|
|
25
|
+
type ForwarderBody<P extends Parts> = <Id>(args: CallArgs<Id, OverloadArgs<P[number]>>, forward: Forward<Id, P>) => Forwarded<Id> | ([undefined] extends [OverloadResult<P[number]>] ? undefined : never);
|
|
26
|
+
type CheckedBody<P extends Parts> = false extends FitsSlots<P[number]> ? never : ForwarderBody<P>;
|
|
27
|
+
export declare const defineForwarder: <P extends Parts>(body: CheckedBody<P>) => Intersect<P[number]>;
|
|
28
|
+
type At<Args, Index> = Index extends keyof Args ? Args[Index] : undefined;
|
|
29
|
+
type Primitive$1 = string | number | bigint | boolean | symbol | null | undefined;
|
|
30
|
+
type PairDisjoint<X, G> = [X & G] extends [never] ? true : [X] extends [Primitive$1] ? [G] extends [object] ? true : false : [X] extends [object] ? [G] extends [Primitive$1] ? true : false : false;
|
|
31
|
+
type Disjoint<X, G> = false extends (X extends unknown ? (G extends unknown ? PairDisjoint<X, G> : never) : never) ? false : true;
|
|
32
|
+
type Matching<Args, Index, G> = Args extends unknown ? Disjoint<At<Args, Index>, G> extends true ? never : Args : never;
|
|
33
|
+
type NotMatching<Args, Index, G> = Args extends unknown ? ([At<Args, Index>] extends [G] ? never : Args) : never;
|
|
34
|
+
type ArgMatch<Id, Args, Index, G> = {
|
|
35
|
+
readonly matched: true;
|
|
36
|
+
readonly args: CallArgs<Id, Matching<Args, Index, G>>;
|
|
37
|
+
} | {
|
|
38
|
+
readonly matched: false;
|
|
39
|
+
readonly args: CallArgs<Id, NotMatching<Args, Index, G>>;
|
|
40
|
+
};
|
|
41
|
+
export declare const whenArg: <Id, Args extends readonly unknown[], Index extends number, G>(args: CallArgs<Id, Args>, index: Index, guard: (value: unknown) => value is G) => ArgMatch<Id, Args, Index, G>;
|
|
42
|
+
export declare const isFunction: (value: unknown) => value is (...args: never[]) => unknown;
|
|
43
|
+
type Success<Value> = {
|
|
44
|
+
readonly type: "Success";
|
|
45
|
+
readonly value: Value;
|
|
46
|
+
};
|
|
47
|
+
type Failure<Error> = {
|
|
48
|
+
readonly type: "Failure";
|
|
49
|
+
readonly error: Error;
|
|
50
|
+
};
|
|
51
|
+
type Result$1<Value, Error> = Success<Value> | Failure<Error>;
|
|
52
|
+
type JsonRoundTrip<T> = 0 extends 1 & T ? never : T extends string | number | boolean | null ? T : T extends ((...args: never[]) => unknown) | (abstract new (...args: never[]) => unknown) ? never : T extends object ? [keyof T] extends [never] ? never : { [K in keyof T]: K extends symbol ? never : JsonRoundTrip<T[K]>; } : never;
|
|
53
|
+
type StringStorage = {
|
|
54
|
+
readonly readString: (key: string) => string | null | undefined | Promise<string | null | undefined>;
|
|
55
|
+
readonly writeString: (key: string, text: string) => unknown;
|
|
56
|
+
};
|
|
57
|
+
type JsonStoreOptions<T> = [T] extends [JsonRoundTrip<T>] ? StringStorage : {
|
|
58
|
+
readonly "createJsonStore needs a type that survives a JSON round trip"?: never;
|
|
59
|
+
};
|
|
60
|
+
type JsonStoreGetError = {
|
|
61
|
+
readonly kind: "not-found";
|
|
62
|
+
} | {
|
|
63
|
+
readonly kind: "invalid-json";
|
|
64
|
+
readonly cause: SyntaxError;
|
|
65
|
+
};
|
|
66
|
+
type JsonStoreSetError = {
|
|
67
|
+
readonly kind: "non-finite-number";
|
|
68
|
+
} | {
|
|
69
|
+
readonly kind: "not-serializable";
|
|
70
|
+
readonly cause: TypeError;
|
|
71
|
+
};
|
|
72
|
+
type JsonStore<T> = {
|
|
73
|
+
readonly get: (key: string) => Promise<Result$1<T, JsonStoreGetError>>;
|
|
74
|
+
readonly set: (key: string, value: T) => Promise<Result$1<undefined, JsonStoreSetError>>;
|
|
75
|
+
};
|
|
76
|
+
export declare const createJsonStore: <T>(options: JsonStoreOptions<T>) => JsonStore<T>;
|
|
77
|
+
type Key$1 = string | symbol;
|
|
78
|
+
type Flatten<T> = { [K in keyof T]: T[K]; };
|
|
79
|
+
type IsUnion<T, All = T> = T extends All ? ([All] extends [T] ? false : true) : never;
|
|
80
|
+
type SingleKey<K extends Key$1> = true extends IsUnion<K> ? never : {} extends Record<K, never> ? never : K;
|
|
81
|
+
type Pair = readonly [Key$1, unknown];
|
|
82
|
+
type HasUnsureKey<Pairs extends readonly Pair[]> = true extends { [Index in keyof Pairs]: [SingleKey<Pairs[Index][0]>] extends [never] ? true : false; }[number] ? true : false;
|
|
83
|
+
type FromPairs<Pairs extends readonly Pair[], Values = {}> = Pairs extends readonly [infer First extends Pair, ...infer Rest extends Pair[]] ? FromPairs<Rest, Omit<Values, First[0]> & Record<First[0], First[1]>> : Readonly<Flatten<Values>>;
|
|
84
|
+
type FromEntries<Pairs extends readonly Pair[]> = number extends Pairs["length"] ? {
|
|
85
|
+
readonly "fromEntries needs a fixed-length tuple"?: never;
|
|
86
|
+
} : [Extract<Pairs[number], unknown[]>] extends [never] ? HasUnsureKey<Pairs> extends true ? {
|
|
87
|
+
readonly "fromEntries needs one literal key per pair"?: never;
|
|
88
|
+
} : FromPairs<Pairs> : {
|
|
89
|
+
readonly "fromEntries needs readonly pairs"?: never;
|
|
90
|
+
};
|
|
91
|
+
export declare const fromEntries: <const Pairs extends readonly Pair[]>(pairs: Pairs) => FromEntries<Pairs>;
|
|
92
|
+
declare const origin: unique symbol;
|
|
93
|
+
declare const site: unique symbol;
|
|
94
|
+
declare const sealed: unique symbol;
|
|
95
|
+
type Same<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => (T extends B ? 1 : 2)) ? true : false;
|
|
96
|
+
type Primitive = string | number | bigint | boolean | symbol;
|
|
97
|
+
type Missing = null | undefined;
|
|
98
|
+
type Sealed = {
|
|
99
|
+
readonly [sealed]: true;
|
|
100
|
+
};
|
|
101
|
+
type Traced<Scope, Path, Member> = {
|
|
102
|
+
readonly [origin]: readonly [(scope: Scope) => Scope, Path, Member];
|
|
103
|
+
};
|
|
104
|
+
type Brand<Scope, Path, Member, Op> = Traced<Scope, Path, Member> & {
|
|
105
|
+
readonly [site]?: Op;
|
|
106
|
+
};
|
|
107
|
+
type Prop<Key, Owner, Fallback> = {
|
|
108
|
+
readonly prop: Key;
|
|
109
|
+
readonly owner: Owner;
|
|
110
|
+
readonly fallback: Fallback;
|
|
111
|
+
};
|
|
112
|
+
type Call$1<Owner, Fallback> = {
|
|
113
|
+
readonly call: Owner;
|
|
114
|
+
readonly fallback: Fallback;
|
|
115
|
+
};
|
|
116
|
+
type Wait<Owner> = {
|
|
117
|
+
readonly wait: Owner;
|
|
118
|
+
};
|
|
119
|
+
type Then = {
|
|
120
|
+
readonly then: true;
|
|
121
|
+
};
|
|
122
|
+
type IsSingleCall<Fn> = Fn extends ((...args: infer Args) => infer Result) ? [(...args: Args) => Result] extends [Fn] ? true : false : false;
|
|
123
|
+
type Lens<Value, Scope, Path extends readonly unknown[], Op> = Value extends unknown ? unknown extends Value ? Op extends Sealed ? unknown : Traced<Scope, Path, unknown> & PromiseLike<Traced<Scope, [...Path, Wait<unknown>], unknown>> : Value extends Missing ? Op extends Sealed ? Value : never : Value extends Primitive ? Value & Brand<Scope, Path, Value, Op> : Value extends PromiseLike<infer Inner> ? PromiseLike<Lens<Inner, Scope, [...Path, Wait<Value>], Op>> & Brand<Scope, [...Path, Then], Value, Op> : Value extends ((...args: infer Args) => infer Result) ? IsSingleCall<Value> extends true ? ((...args: Args) => Lens<Result, Scope, [...Path, Call$1<Value, Result>], Op>) & Brand<Scope, Path, Value, Op> : Value & Brand<Scope, Path, Value, Op> : { readonly [Field in keyof Value]: Lens<Value[Field], Scope, [...Path, Prop<Field, Value, Value[Field]>], Op>; } & Brand<Scope, Path, Value, Op> : never;
|
|
124
|
+
type Follow<Value, Path> = Path extends readonly [infer Step, ...infer Rest] ? Step extends Prop<infer Key, infer Owner, infer Fallback> ? Value extends Owner ? Key extends keyof Value ? Follow<Value[Key], Rest> : Follow<Fallback, Rest> : never : Step extends Call$1<infer Owner, infer Fallback> ? Value extends Owner ? IsSingleCall<Value> extends true ? Value extends ((...args: never) => infer Result) ? Follow<Result, Rest> : never : Follow<Fallback, Rest> : never : Step extends Wait<infer Owner> ? Value extends Owner ? Follow<Awaited<Value>, Rest> : never : Follow<Value, Rest> : Value;
|
|
125
|
+
type Last<Path> = Path extends readonly [...unknown[], infer Step] ? Step : never;
|
|
126
|
+
type Kept<Found, Path, Member> = Found extends Member | Missing ? unknown extends Member ? Found : Last<Path> extends Wait<unknown> | Then ? Found : Found extends PromiseLike<unknown> ? Found | Awaited<Found> : Found : never;
|
|
127
|
+
type Settle<Result, Scope, Value> = Result extends Traced<infer Slot, infer Path, infer Member> ? Same<Slot, Scope> extends true ? Kept<Follow<Value, Path>, Path, Member> : Result : Same<Result, Date> extends true ? Result : Result extends Promise<infer Inner> ? Promise<Settle<Inner, Scope, Value>> : Result extends ((...args: infer Args) => infer Returned) ? (...args: { [Index in keyof Args]: Settle<Args[Index], Scope, Value>; }) => Settle<Returned, Scope, Value> : Result extends object ? { readonly [Field in keyof Result]: Settle<Result[Field], Scope, Value>; } : Result;
|
|
128
|
+
type Marks<Result, Scope, Own> = Result extends Traced<infer Slot, unknown, unknown> ? Own extends true ? Same<Slot, Scope> : true : Result extends Promise<infer Inner> ? readonly [Marks<Inner, Scope, Own>] : Result extends ((...args: infer Args) => infer Returned) ? readonly [{ [Index in keyof Args]: Marks<Args[Index], Scope, Own>; }, Marks<Returned, Scope, Own>] : Result extends object ? { readonly [Field in keyof Result]: Marks<Result[Field], Scope, Own>; } : true;
|
|
129
|
+
type Proof<Result, Scope> = [Marks<Result, Scope, false>] extends [Marks<Result, Scope, true>] ? [] : ["mapValues cannot return a value that an outer mapValues passed to its mapper"];
|
|
130
|
+
type Position<In> = Exclude<keyof In, keyof (readonly unknown[])>;
|
|
131
|
+
type KeyOf<In> = In extends readonly unknown[] ? Position<In> : keyof In;
|
|
132
|
+
type ValueOf<In> = In extends readonly unknown[] ? In[number] : In[keyof In];
|
|
133
|
+
type Known<Shape> = { readonly [Key in keyof Shape]: Shape[Key]; };
|
|
134
|
+
type Mapper<Shape, Keys> = <K extends Keys, Op>(value: Lens<ValueOf<Shape>, K, [], Op>, key: K) => unknown;
|
|
135
|
+
type Returned<Fn, Shape, Keys> = Fn extends ((value: Lens<ValueOf<Shape>, Keys, [], unknown>, key: Keys) => infer Result) ? Result : never;
|
|
136
|
+
type Covered<In, Shape> = Shape extends readonly unknown[] ? true : string extends keyof Shape ? true : [Exclude<keyof In, keyof Shape>] extends [never] ? true : false;
|
|
137
|
+
type Checked<In, Shape, Result, Scope> = Covered<In, Shape> extends true ? Proof<Result, Scope> : ["mapValues needs every key of the source to be known"];
|
|
138
|
+
export declare function mapValues<const In extends object, Shape, Fn extends Mapper<Shape, KeyOf<In>>>(source: In & Known<Shape>, mapper: Fn, ...proof: Checked<In, Shape, Returned<Fn, Shape, KeyOf<In>>, KeyOf<In>>): { readonly [K in keyof In]: Settle<Returned<Fn, Shape, KeyOf<In>>, KeyOf<In>, In[K]>; };
|
|
139
|
+
export declare class ValueKey<Value> {
|
|
140
|
+
private readonly valueType;
|
|
141
|
+
}
|
|
142
|
+
export declare class KeyedValueStore {
|
|
143
|
+
#private;
|
|
144
|
+
set<Value>(key: ValueKey<Value>, value: NoInfer<Value>): void;
|
|
145
|
+
get<Value>(key: ValueKey<Value>): Value | undefined;
|
|
146
|
+
}
|
|
147
|
+
type Result$2<Value, Error> = {
|
|
148
|
+
readonly ok: true;
|
|
149
|
+
readonly value: Value;
|
|
150
|
+
} | {
|
|
151
|
+
readonly ok: false;
|
|
152
|
+
readonly error: Error;
|
|
153
|
+
};
|
|
154
|
+
type MemberValues<Value> = { [Key in keyof Value]: GuardedValue<Value[Key]>; };
|
|
155
|
+
type DataKeys<Value> = { [Key in keyof Value]-?: [Extract<Value[Key], object>] extends [never] ? Key : never; }[keyof Value];
|
|
156
|
+
type Members<Value> = Value extends readonly unknown[] ? Readonly<MemberValues<Value>> : { [Key in keyof (Pick<MemberValues<Value>, DataKeys<Value>> & Readonly<Omit<MemberValues<Value>, DataKeys<Value>>>)]: (Pick<MemberValues<Value>, DataKeys<Value>> & Readonly<Omit<MemberValues<Value>, DataKeys<Value>>>)[Key]; };
|
|
157
|
+
type Construct<Value> = Value extends (new (...args: infer Args) => infer Instance) ? new (...args: Args) => Instance : Value extends (abstract new (...args: infer Args) => infer Instance) ? abstract new (...args: Args) => Instance : unknown;
|
|
158
|
+
type Call<Value, Args extends unknown[], Result> = (this: ThisParameterType<Value>, ...args: Args) => Result;
|
|
159
|
+
type GuardedValue<Value> = Value extends ((...args: infer Args) => infer Result) ? keyof Value extends never ? Value : Call<Value, Args, Result$2> & Construct<Value> & Pick<Value, keyof Value> extends Value ? Call<Value, Args, Result$2> & Construct<Value> & Members<Value> : Members<Value> : Value extends object ? Construct<Value> & Pick<Value, keyof Value> extends Value ? Construct<Value> & Members<Value> : Members<Value> : Value;
|
|
160
|
+
/**
|
|
161
|
+
* Guard properties recursively while preserving aliases, cycles and method receivers.
|
|
162
|
+
* Operation results retain their own resource lifetime rather than being proxied.
|
|
163
|
+
*/
|
|
164
|
+
export declare const createKeyedValueView: (source: () => object) => Readonly<{
|
|
165
|
+
readonly handle: object;
|
|
166
|
+
bind<Value>(value: Value): Result$2<GuardedValue<Value>, "different-source">;
|
|
167
|
+
}>;
|
|
168
|
+
export type { Failure, FromEntries, GuardedValue, JsonStore, JsonStoreGetError, JsonStoreOptions, JsonStoreSetError, Result$1 as Result, Success };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { t as isConstructor } from "./class-constructor-Cl1RwNAF.mjs";
|
|
2
|
+
// src/callable/forwarder.ts
|
|
3
|
+
const defineForwarder = (body) => {
|
|
4
|
+
const run = body;
|
|
5
|
+
function forwarder(...args) {
|
|
6
|
+
return run(args, (to, forwarded) => Reflect.apply(to, this, forwarded));
|
|
7
|
+
}
|
|
8
|
+
return forwarder;
|
|
9
|
+
};
|
|
10
|
+
const whenArg = (args, index, guard) => {
|
|
11
|
+
return {
|
|
12
|
+
matched: guard(args[index]),
|
|
13
|
+
args
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
// src/callable/is-function.ts
|
|
17
|
+
const isFunction = (value) => typeof value === "function";
|
|
18
|
+
// src/json/result.ts
|
|
19
|
+
const success = (value) => ({
|
|
20
|
+
type: "Success",
|
|
21
|
+
value
|
|
22
|
+
});
|
|
23
|
+
const failure = (error) => ({
|
|
24
|
+
type: "Failure",
|
|
25
|
+
error
|
|
26
|
+
});
|
|
27
|
+
// src/json/json-store.ts
|
|
28
|
+
const stringify = (value) => {
|
|
29
|
+
const found = { nonFinite: false };
|
|
30
|
+
let text;
|
|
31
|
+
try {
|
|
32
|
+
text = JSON.stringify(value, (_key, item) => {
|
|
33
|
+
if (typeof item === "number" && !Number.isFinite(item)) found.nonFinite = true;
|
|
34
|
+
return item;
|
|
35
|
+
});
|
|
36
|
+
} catch (cause) {
|
|
37
|
+
if (!(cause instanceof TypeError)) throw cause;
|
|
38
|
+
return failure({
|
|
39
|
+
kind: "not-serializable",
|
|
40
|
+
cause
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return found.nonFinite ? failure({ kind: "non-finite-number" }) : success(text);
|
|
44
|
+
};
|
|
45
|
+
const createJsonStore = (options) => {
|
|
46
|
+
const { readString, writeString } = options;
|
|
47
|
+
return {
|
|
48
|
+
get: async (key) => {
|
|
49
|
+
const text = await readString(key);
|
|
50
|
+
if (text === null || text === void 0) return failure({ kind: "not-found" });
|
|
51
|
+
let value;
|
|
52
|
+
try {
|
|
53
|
+
value = JSON.parse(text);
|
|
54
|
+
} catch (cause) {
|
|
55
|
+
if (!(cause instanceof SyntaxError)) throw cause;
|
|
56
|
+
return failure({
|
|
57
|
+
kind: "invalid-json",
|
|
58
|
+
cause
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return success(value);
|
|
62
|
+
},
|
|
63
|
+
set: async (key, value) => {
|
|
64
|
+
const text = stringify(value);
|
|
65
|
+
if (text.type === "Failure") return text;
|
|
66
|
+
await writeString(key, text.value);
|
|
67
|
+
return success(void 0);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
// src/keyed-value/from-entries.ts
|
|
72
|
+
const freezeEntries = (pairs) => Object.freeze(Object.fromEntries(pairs));
|
|
73
|
+
const fromEntries = (pairs) => {
|
|
74
|
+
const snapshot = [];
|
|
75
|
+
for (let index = 0; index < pairs.length; index++) {
|
|
76
|
+
const pair = pairs[index];
|
|
77
|
+
if (pair === void 0) throw new TypeError("Missing entry at a tuple position");
|
|
78
|
+
snapshot.push([pair[0], pair[1]]);
|
|
79
|
+
}
|
|
80
|
+
return freezeEntries(snapshot);
|
|
81
|
+
};
|
|
82
|
+
// src/keyed-value/map-values.ts
|
|
83
|
+
function mapValues(source, mapper) {
|
|
84
|
+
if (Array.isArray(source)) {
|
|
85
|
+
const values = [];
|
|
86
|
+
for (let index = 0; index < source.length; index++) values.push(mapper(source[index], String(index)));
|
|
87
|
+
return Object.freeze(values);
|
|
88
|
+
}
|
|
89
|
+
const record = { ...source };
|
|
90
|
+
return Object.freeze(Object.fromEntries(Reflect.ownKeys(record).map((key) => [key, mapper(record[key], key)])));
|
|
91
|
+
}
|
|
92
|
+
// src/value-store/keyed-value-store.ts
|
|
93
|
+
var ValueKey = class {};
|
|
94
|
+
var KeyedValueStore = class {
|
|
95
|
+
#values = /* @__PURE__ */ new WeakMap();
|
|
96
|
+
set(key, value) {
|
|
97
|
+
this.#values.set(key, value);
|
|
98
|
+
}
|
|
99
|
+
get(key) {
|
|
100
|
+
return this.#values.get(key);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
// src/value-store/keyed-value-view.ts
|
|
104
|
+
const callableTarget = () => ((..._args) => void 0).bind(void 0);
|
|
105
|
+
const constructibleTarget = () => function() {}.bind(void 0);
|
|
106
|
+
const shadowFor = (value) => {
|
|
107
|
+
if (Array.isArray(value)) return [];
|
|
108
|
+
if (typeof value !== "function") return {};
|
|
109
|
+
return isConstructor(value) ? constructibleTarget() : callableTarget();
|
|
110
|
+
};
|
|
111
|
+
const hasSameKind = (left, right) => typeof left === typeof right && Array.isArray(left) === Array.isArray(right) && isConstructor(left) === isConstructor(right);
|
|
112
|
+
const unwrap = (context, value) => value !== null && (typeof value === "object" || typeof value === "function") ? context.sources.get(value) ?? value : value;
|
|
113
|
+
const invocationReceiver = (instance, method, handle) => typeof instance === "function" && (method === Function.prototype.call || method === Function.prototype.apply || method === Function.prototype.bind) ? handle : instance;
|
|
114
|
+
const readProperty = (context, read, handle, key) => {
|
|
115
|
+
const instance = read();
|
|
116
|
+
const value = Reflect.get(instance, key);
|
|
117
|
+
if (typeof value === "function") {
|
|
118
|
+
const receiver = invocationReceiver(instance, value, handle);
|
|
119
|
+
return createHandle(context, () => {
|
|
120
|
+
read();
|
|
121
|
+
return value;
|
|
122
|
+
}, shadowFor(value), receiver);
|
|
123
|
+
}
|
|
124
|
+
if (value === null || typeof value !== "object") return value;
|
|
125
|
+
const existing = context.handles.get(value);
|
|
126
|
+
if (existing) return existing;
|
|
127
|
+
const nested = createHandle(context, () => value, Array.isArray(value) ? [] : {});
|
|
128
|
+
context.handles.set(value, nested);
|
|
129
|
+
context.sources.set(nested, value);
|
|
130
|
+
return nested;
|
|
131
|
+
};
|
|
132
|
+
const propertyDescriptor = (context, read, handle, shadow, key) => {
|
|
133
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(read(), key);
|
|
134
|
+
if (!descriptor) return void 0;
|
|
135
|
+
const configurable = Reflect.getOwnPropertyDescriptor(shadow, key)?.configurable ?? true;
|
|
136
|
+
if (descriptor.writable !== void 0) return {
|
|
137
|
+
...descriptor,
|
|
138
|
+
configurable,
|
|
139
|
+
value: readProperty(context, read, handle, key)
|
|
140
|
+
};
|
|
141
|
+
return {
|
|
142
|
+
...descriptor,
|
|
143
|
+
configurable,
|
|
144
|
+
...descriptor.get ? { get: () => readProperty(context, read, handle, key) } : {},
|
|
145
|
+
...descriptor.set ? { set: (value) => {
|
|
146
|
+
Reflect.set(read(), key, unwrap(context, value));
|
|
147
|
+
} } : {}
|
|
148
|
+
};
|
|
149
|
+
};
|
|
150
|
+
const createHandle = (context, source, shadow, boundReceiver) => {
|
|
151
|
+
const read = () => {
|
|
152
|
+
context.checkLifetime();
|
|
153
|
+
const instance = source();
|
|
154
|
+
context.handles.set(instance, handle);
|
|
155
|
+
context.sources.set(handle, instance);
|
|
156
|
+
return instance;
|
|
157
|
+
};
|
|
158
|
+
const handle = new Proxy(shadow, {
|
|
159
|
+
apply: (_, receiver, args) => {
|
|
160
|
+
const instance = read();
|
|
161
|
+
if (typeof instance !== "function") throw new TypeError("The source is not callable");
|
|
162
|
+
const target = receiver === void 0 || receiver === boundReceiver ? boundReceiver : unwrap(context, receiver);
|
|
163
|
+
return Reflect.apply(instance, target, args.map((arg) => unwrap(context, arg)));
|
|
164
|
+
},
|
|
165
|
+
construct: (_, args, newTarget) => {
|
|
166
|
+
const instance = read();
|
|
167
|
+
if (!isConstructor(instance)) throw new TypeError("The source is not a constructor");
|
|
168
|
+
const parameters = args.map((arg) => unwrap(context, arg));
|
|
169
|
+
return Reflect.construct(instance, parameters, newTarget === handle ? instance : newTarget);
|
|
170
|
+
},
|
|
171
|
+
get: (_, key) => readProperty(context, read, handle, key),
|
|
172
|
+
set: (_, key, value) => {
|
|
173
|
+
const instance = read();
|
|
174
|
+
return Reflect.set(instance, key, unwrap(context, value), instance);
|
|
175
|
+
},
|
|
176
|
+
has: (_, key) => Reflect.has(read(), key),
|
|
177
|
+
ownKeys: () => Reflect.ownKeys(read()),
|
|
178
|
+
getPrototypeOf: () => Reflect.getPrototypeOf(read()),
|
|
179
|
+
getOwnPropertyDescriptor: (_, key) => propertyDescriptor(context, read, handle, shadow, key)
|
|
180
|
+
});
|
|
181
|
+
return handle;
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* Guard properties recursively while preserving aliases, cycles and method receivers.
|
|
185
|
+
* Operation results retain their own resource lifetime rather than being proxied.
|
|
186
|
+
*/
|
|
187
|
+
const createKeyedValueView = (source) => {
|
|
188
|
+
let bound;
|
|
189
|
+
let handle;
|
|
190
|
+
const read = () => {
|
|
191
|
+
const value = source();
|
|
192
|
+
if (bound !== void 0 && value !== bound) throw new TypeError("The source of a bound value view changed");
|
|
193
|
+
return value;
|
|
194
|
+
};
|
|
195
|
+
const context = {
|
|
196
|
+
checkLifetime: read,
|
|
197
|
+
handles: /* @__PURE__ */ new WeakMap(),
|
|
198
|
+
sources: /* @__PURE__ */ new WeakMap()
|
|
199
|
+
};
|
|
200
|
+
return Object.freeze({
|
|
201
|
+
get handle() {
|
|
202
|
+
return handle ??= createHandle(context, read, constructibleTarget());
|
|
203
|
+
},
|
|
204
|
+
bind(value) {
|
|
205
|
+
const current = source();
|
|
206
|
+
if (current !== value || bound !== void 0 && bound !== current) return {
|
|
207
|
+
ok: false,
|
|
208
|
+
error: "different-source"
|
|
209
|
+
};
|
|
210
|
+
bound = current;
|
|
211
|
+
if (handle === void 0 || !hasSameKind(handle, current)) handle = createHandle(context, read, shadowFor(current));
|
|
212
|
+
return {
|
|
213
|
+
ok: true,
|
|
214
|
+
value: handle
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
};
|
|
219
|
+
export { KeyedValueStore, ValueKey, createJsonStore, createKeyedValueView, defineForwarder, fromEntries, isFunction, mapValues, whenArg };
|
package/dist/runtime.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as isConstructor } from "./class-constructor-Cl1RwNAF.mjs";
|
package/package.json
CHANGED
|
@@ -1,10 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "as-free",
|
|
3
|
-
"version": "0.0.0",
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.1-beta.0",
|
|
4
|
+
"description": "Type-preserving utilities so your code needs no `as`.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/9wick/as-free.git"
|
|
9
|
+
},
|
|
6
10
|
"files": [
|
|
7
|
-
"
|
|
11
|
+
"dist"
|
|
8
12
|
],
|
|
9
|
-
"
|
|
10
|
-
|
|
13
|
+
"type": "module",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.mts",
|
|
17
|
+
"default": "./dist/index.mjs"
|
|
18
|
+
},
|
|
19
|
+
"./runtime": {
|
|
20
|
+
"types": "./dist/runtime.d.mts",
|
|
21
|
+
"default": "./dist/runtime.mjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"typescript": "7.0.2",
|
|
29
|
+
"vite-plus": "1.6.0"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "vp pack",
|
|
33
|
+
"check": "vp check",
|
|
34
|
+
"test": "node --test \"src/**/*.test.ts\""
|
|
35
|
+
}
|
|
36
|
+
}
|
package/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
throw new Error('This version is not intended for use.');
|