@ydant/async 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 cwd-k2
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 ADDED
@@ -0,0 +1,109 @@
1
+ # @ydant/async
2
+
3
+ Async components for Ydant: Suspense, ErrorBoundary, and Resource.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @ydant/async
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Suspense
14
+
15
+ ```typescript
16
+ import { div, text, type Component } from "@ydant/core";
17
+ import { Suspense, createResource } from "@ydant/async";
18
+
19
+ // Create async resource
20
+ const userResource = createResource(() => fetch("/api/user").then((r) => r.json()));
21
+
22
+ // Component using resource
23
+ const UserProfile: Component = () =>
24
+ div(function* () {
25
+ const user = userResource();
26
+ yield* text(`Name: ${user.name}`);
27
+ });
28
+
29
+ // Wrap with Suspense
30
+ const App: Component = () =>
31
+ Suspense({
32
+ fallback: () => text("Loading..."),
33
+ children: UserProfile,
34
+ });
35
+ ```
36
+
37
+ ### ErrorBoundary
38
+
39
+ ```typescript
40
+ import { ErrorBoundary } from "@ydant/async";
41
+
42
+ const App: Component = () =>
43
+ ErrorBoundary({
44
+ fallback: (error) => text(`Error: ${error.message}`),
45
+ children: () => RiskyComponent(),
46
+ });
47
+ ```
48
+
49
+ ### Combined Usage
50
+
51
+ ```typescript
52
+ const App: Component = () =>
53
+ ErrorBoundary({
54
+ fallback: (error) => text(`Error: ${error.message}`),
55
+ children: () =>
56
+ Suspense({
57
+ fallback: () => text("Loading..."),
58
+ children: AsyncContent,
59
+ }),
60
+ });
61
+ ```
62
+
63
+ ## API
64
+
65
+ ### Suspense
66
+
67
+ ```typescript
68
+ function Suspense(props: SuspenseProps): ElementGenerator;
69
+
70
+ interface SuspenseProps {
71
+ fallback: () => Render;
72
+ children: Component;
73
+ }
74
+ ```
75
+
76
+ Shows fallback while async content is loading.
77
+
78
+ ### ErrorBoundary
79
+
80
+ ```typescript
81
+ function ErrorBoundary(props: ErrorBoundaryProps): ElementGenerator;
82
+
83
+ interface ErrorBoundaryProps {
84
+ fallback: (error: Error) => Render;
85
+ children: () => ElementGenerator;
86
+ }
87
+ ```
88
+
89
+ Catches errors in child components and shows fallback.
90
+
91
+ ### createResource
92
+
93
+ ```typescript
94
+ function createResource<T>(fetcher: () => Promise<T>): Resource<T>;
95
+
96
+ interface Resource<T> {
97
+ (): T; // Throws promise if pending, error if failed
98
+ refetch(): void;
99
+ state: "pending" | "ready" | "error";
100
+ }
101
+ ```
102
+
103
+ Creates a resource that suspends while loading.
104
+
105
+ ## Module Structure
106
+
107
+ - `suspense.ts` - Suspense component
108
+ - `error-boundary.ts` - ErrorBoundary component
109
+ - `resource.ts` - createResource
@@ -0,0 +1,16 @@
1
+ import { ChildContent, Render } from '@ydant/core';
2
+ /** ErrorBoundary コンポーネントの props */
3
+ export interface ErrorBoundaryProps {
4
+ /** エラー発生時に表示するコンポーネント */
5
+ fallback: (error: Error, reset: () => void) => Render;
6
+ /** 子コンポーネント */
7
+ children: () => ChildContent;
8
+ }
9
+ /**
10
+ * ErrorBoundary コンポーネント
11
+ *
12
+ * 注意: JavaScript のジェネレータでは、yield で throw されたエラーを
13
+ * キャッチするには特別な対応が必要です。
14
+ * この実装は同期エラーのみをキャッチします。
15
+ */
16
+ export declare function ErrorBoundary(props: ErrorBoundaryProps): Render;
@@ -0,0 +1,36 @@
1
+ import { ChildContent, Render } from '@ydant/core';
2
+ /** Suspense コンポーネントの props */
3
+ export interface SuspenseProps {
4
+ /** ローディング中に表示するコンポーネント */
5
+ fallback: () => Render;
6
+ /** 子コンポーネント */
7
+ children: () => ChildContent;
8
+ }
9
+ /**
10
+ * Suspense コンポーネント
11
+ *
12
+ * 注意: 現在の実装では、ジェネレータベースの DSL と
13
+ * Promise throw パターンの組み合わせに制限があります。
14
+ * 代替として、Resource の loading/error プロパティを使った
15
+ * 明示的なローディング状態管理を推奨します。
16
+ */
17
+ export declare function Suspense(props: SuspenseProps): Render;
18
+ /**
19
+ * 明示的なローディング状態を使った代替パターン
20
+ *
21
+ * Resource の loading プロパティを使って条件分岐する。
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * import { createResource } from "@ydant/async";
26
+ * import { show } from "@ydant/core";
27
+ *
28
+ * const dataResource = createResource(fetchData, { initialValue: null });
29
+ *
30
+ * yield* show(
31
+ * dataResource.loading,
32
+ * () => div(() => [text("Loading...")]),
33
+ * () => div(() => [text(dataResource()?.message ?? "")])
34
+ * );
35
+ * ```
36
+ */
@@ -0,0 +1,6 @@
1
+ export type { Resource } from './resource';
2
+ export type { SuspenseProps } from './Suspense';
3
+ export type { ErrorBoundaryProps } from './ErrorBoundary';
4
+ export { createResource } from './resource';
5
+ export { Suspense } from './Suspense';
6
+ export { ErrorBoundary } from './ErrorBoundary';
@@ -0,0 +1,103 @@
1
+ import { div as a } from "@ydant/base";
2
+ function l(c, i) {
3
+ let e;
4
+ if (i?.initialValue !== void 0)
5
+ e = { status: "resolved", data: i.initialValue };
6
+ else {
7
+ const n = c();
8
+ e = { status: "pending", promise: n }, n.then((r) => {
9
+ e = { status: "resolved", data: r };
10
+ }).catch((r) => {
11
+ e = { status: "rejected", error: r };
12
+ });
13
+ }
14
+ const t = (() => {
15
+ switch (e.status) {
16
+ case "pending":
17
+ throw e.promise;
18
+ case "rejected":
19
+ throw e.error;
20
+ case "resolved":
21
+ return e.data;
22
+ }
23
+ });
24
+ Object.defineProperty(t, "loading", {
25
+ get: () => e.status === "pending"
26
+ }), Object.defineProperty(t, "error", {
27
+ get: () => e.status === "rejected" ? e.error : null
28
+ }), t.peek = () => {
29
+ switch (e.status) {
30
+ case "pending":
31
+ throw new Error("Resource is still loading");
32
+ case "rejected":
33
+ throw e.error;
34
+ case "resolved":
35
+ return e.data;
36
+ }
37
+ }, t.refetch = async () => {
38
+ const n = c();
39
+ e = { status: "pending", promise: n };
40
+ try {
41
+ e = { status: "resolved", data: await n };
42
+ } catch (r) {
43
+ e = { status: "rejected", error: r };
44
+ }
45
+ };
46
+ let s = null;
47
+ return i?.refetchInterval && (s = setInterval(() => {
48
+ t.refetch();
49
+ }, i.refetchInterval)), t.dispose = () => {
50
+ s !== null && (clearInterval(s), s = null);
51
+ }, t;
52
+ }
53
+ function* d(c) {
54
+ const { fallback: i, children: e } = c, t = yield* a(function* () {
55
+ let s = !1, n = null;
56
+ try {
57
+ yield* e();
58
+ } catch (r) {
59
+ if (r instanceof Promise)
60
+ s = !0, n = r;
61
+ else
62
+ throw r;
63
+ }
64
+ s && n && (yield* i(), n.then(() => {
65
+ t.refresh(function* () {
66
+ yield* e();
67
+ });
68
+ }).catch(() => {
69
+ t.refresh(function* () {
70
+ yield* e();
71
+ });
72
+ }));
73
+ });
74
+ return t;
75
+ }
76
+ function* u(c) {
77
+ const { fallback: i, children: e } = c, t = yield* a(function* () {
78
+ try {
79
+ yield* e();
80
+ } catch (s) {
81
+ if (s instanceof Promise)
82
+ throw s;
83
+ const n = () => {
84
+ t.refresh(function* () {
85
+ try {
86
+ yield* e();
87
+ } catch (r) {
88
+ if (r instanceof Promise)
89
+ throw r;
90
+ yield* i(r, n);
91
+ }
92
+ });
93
+ };
94
+ yield* i(s, n);
95
+ }
96
+ });
97
+ return t;
98
+ }
99
+ export {
100
+ u as ErrorBoundary,
101
+ d as Suspense,
102
+ l as createResource
103
+ };
@@ -0,0 +1 @@
1
+ (function(i,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@ydant/base")):typeof define=="function"&&define.amd?define(["exports","@ydant/base"],a):(i=typeof globalThis<"u"?globalThis:i||self,a(i.YdantAsync={},i.YdantBase))})(this,(function(i,a){"use strict";function d(c,o){let e;if(o?.initialValue!==void 0)e={status:"resolved",data:o.initialValue};else{const n=c();e={status:"pending",promise:n},n.then(r=>{e={status:"resolved",data:r}}).catch(r=>{e={status:"rejected",error:r}})}const t=(()=>{switch(e.status){case"pending":throw e.promise;case"rejected":throw e.error;case"resolved":return e.data}});Object.defineProperty(t,"loading",{get:()=>e.status==="pending"}),Object.defineProperty(t,"error",{get:()=>e.status==="rejected"?e.error:null}),t.peek=()=>{switch(e.status){case"pending":throw new Error("Resource is still loading");case"rejected":throw e.error;case"resolved":return e.data}},t.refetch=async()=>{const n=c();e={status:"pending",promise:n};try{e={status:"resolved",data:await n}}catch(r){e={status:"rejected",error:r}}};let s=null;return o?.refetchInterval&&(s=setInterval(()=>{t.refetch()},o.refetchInterval)),t.dispose=()=>{s!==null&&(clearInterval(s),s=null)},t}function*l(c){const{fallback:o,children:e}=c,t=yield*a.div(function*(){let s=!1,n=null;try{yield*e()}catch(r){if(r instanceof Promise)s=!0,n=r;else throw r}s&&n&&(yield*o(),n.then(()=>{t.refresh(function*(){yield*e()})}).catch(()=>{t.refresh(function*(){yield*e()})}))});return t}function*u(c){const{fallback:o,children:e}=c,t=yield*a.div(function*(){try{yield*e()}catch(s){if(s instanceof Promise)throw s;const n=()=>{t.refresh(function*(){try{yield*e()}catch(r){if(r instanceof Promise)throw r;yield*o(r,n)}})};yield*o(s,n)}});return t}i.ErrorBoundary=u,i.Suspense=l,i.createResource=d,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})}));
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Resource
3
+ *
4
+ * 非同期データフェッチングを管理するリソース。
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * const userResource = createResource(() => fetch("/api/user").then(r => r.json()));
9
+ *
10
+ * // コンポーネント内で使用
11
+ * yield* Suspense({
12
+ * fallback: () => div(() => [text("Loading...")]),
13
+ * children: function* () {
14
+ * const user = userResource(); // データが準備できるまで suspend
15
+ * yield* h1(() => [text(`Hello, ${user.name}`)]);
16
+ * },
17
+ * });
18
+ * ```
19
+ */
20
+ /** Resource インターフェース */
21
+ export interface Resource<T> {
22
+ /** データを読み取る(ペンディング中は suspend) */
23
+ (): T;
24
+ /** 現在の値を取得(購読なし、ペンディング/エラー中は throw) */
25
+ peek(): T;
26
+ /** ローディング中かどうか */
27
+ readonly loading: boolean;
28
+ /** エラーがあれば Error、なければ null */
29
+ readonly error: Error | null;
30
+ /** 再フェッチ */
31
+ refetch(): Promise<void>;
32
+ /** リソースを破棄(自動再フェッチを停止) */
33
+ dispose(): void;
34
+ }
35
+ /**
36
+ * 非同期リソースを作成
37
+ *
38
+ * @param fetcher - データをフェッチする非同期関数
39
+ * @param options - オプション(初期値、再フェッチ間隔など)
40
+ */
41
+ export declare function createResource<T>(fetcher: () => Promise<T>, options?: {
42
+ /** 初期値 */
43
+ initialValue?: T;
44
+ /** 自動再フェッチ間隔(ミリ秒) */
45
+ refetchInterval?: number;
46
+ }): Resource<T>;
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@ydant/async",
3
+ "version": "0.1.0",
4
+ "description": "Async components (Suspense, ErrorBoundary) for Ydant",
5
+ "keywords": [
6
+ "async",
7
+ "error-boundary",
8
+ "suspense",
9
+ "ydant"
10
+ ],
11
+ "homepage": "https://github.com/cwd-k2/ydant#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/cwd-k2/ydant/issues"
14
+ },
15
+ "license": "MIT",
16
+ "author": "cwd-k2",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/cwd-k2/ydant.git",
20
+ "directory": "packages/async"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "LICENSE",
25
+ "README.md"
26
+ ],
27
+ "main": "./dist/index.umd.js",
28
+ "module": "./dist/index.es.js",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "@ydant/dev": {
34
+ "types": "./src/index.ts",
35
+ "default": "./src/index.ts"
36
+ },
37
+ "import": "./dist/index.es.js",
38
+ "require": "./dist/index.umd.js"
39
+ }
40
+ },
41
+ "peerDependencies": {
42
+ "@ydant/base": "0.1.0",
43
+ "@ydant/core": "0.1.0"
44
+ },
45
+ "scripts": {
46
+ "build": "vite build",
47
+ "typecheck": "tsc --noEmit"
48
+ }
49
+ }