@cmtlyt/lingshu-toolkit 0.4.0 → 0.6.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.
Files changed (132) hide show
  1. package/README.md +10 -0
  2. package/dist/665.js +1 -0
  3. package/dist/893.js +1 -0
  4. package/dist/react/index.js +1 -205
  5. package/dist/react/use-boolean/index.d.ts +2 -1
  6. package/dist/react/use-boolean/index.js +1 -16
  7. package/dist/react/use-controllable-value/index.d.ts +3 -3
  8. package/dist/react/use-controllable-value/index.js +1 -32
  9. package/dist/react/use-counter/index.d.ts +2 -2
  10. package/dist/react/use-counter/index.js +1 -49
  11. package/dist/react/use-force-update/index.d.ts +2 -1
  12. package/dist/react/use-force-update/index.js +1 -6
  13. package/dist/react/use-mount/index.d.ts +2 -1
  14. package/dist/react/use-mount/index.js +1 -16
  15. package/dist/react/use-ref-state/index.d.ts +3 -2
  16. package/dist/react/use-ref-state/index.js +1 -33
  17. package/dist/react/use-storage/index.d.ts +2 -1
  18. package/dist/react/use-storage/index.js +1 -15
  19. package/dist/react/use-title/index.d.ts +2 -2
  20. package/dist/react/use-title/index.js +1 -24
  21. package/dist/react/use-toggle/index.d.ts +4 -4
  22. package/dist/react/use-toggle/index.js +1 -26
  23. package/dist/react/use-valid-data/index.d.ts +5 -4
  24. package/dist/react/use-valid-data/index.js +1 -14
  25. package/dist/shared/allx/index.d.ts +2 -1
  26. package/dist/shared/allx/index.js +1 -44
  27. package/dist/shared/allx/types.d.ts +6 -0
  28. package/dist/shared/allx/utils.d.ts +9 -7
  29. package/dist/shared/allx/utils.js +1 -94
  30. package/dist/shared/animation/index.d.ts +3 -2
  31. package/dist/shared/animation/index.js +1 -77
  32. package/dist/shared/animation/types.d.ts +8 -0
  33. package/dist/shared/animation/utils.d.ts +3 -10
  34. package/dist/shared/animation/utils.js +1 -134
  35. package/dist/shared/api-controller/create-api.d.ts +26 -0
  36. package/dist/shared/api-controller/create-api.js +1 -0
  37. package/dist/shared/api-controller/index.d.ts +3 -0
  38. package/dist/shared/api-controller/index.js +1 -0
  39. package/dist/shared/api-controller/request.d.ts +7 -0
  40. package/dist/shared/api-controller/request.js +1 -0
  41. package/dist/shared/api-controller/types.d.ts +140 -0
  42. package/dist/shared/api-controller/types.js +0 -0
  43. package/dist/shared/api-controller/utils.d.ts +13 -0
  44. package/dist/shared/api-controller/utils.js +1 -0
  45. package/dist/shared/condition-merge/index.d.ts +6 -6
  46. package/dist/shared/condition-merge/index.js +1 -30
  47. package/dist/shared/create-storage-handler/index.d.ts +4 -3
  48. package/dist/shared/create-storage-handler/index.js +1 -68
  49. package/dist/shared/data-handler/index.d.ts +4 -3
  50. package/dist/shared/data-handler/index.js +1 -77
  51. package/dist/shared/data-handler/tools.d.ts +6 -23
  52. package/dist/shared/data-handler/tools.js +1 -48
  53. package/dist/shared/data-handler/types.d.ts +20 -2
  54. package/dist/shared/data-mixed-manager/constants.js +1 -9
  55. package/dist/shared/data-mixed-manager/index.js +1 -226
  56. package/dist/shared/data-mixed-manager/types.d.ts +1 -2
  57. package/dist/shared/index.d.ts +3 -0
  58. package/dist/shared/index.js +1 -2
  59. package/dist/shared/logger/index.d.ts +5 -0
  60. package/dist/shared/logger/index.js +1 -9
  61. package/dist/shared/priority-queue/index.d.ts +45 -0
  62. package/dist/shared/priority-queue/index.js +1 -0
  63. package/dist/shared/priority-queue/types.d.ts +10 -0
  64. package/dist/shared/priority-queue/types.js +0 -0
  65. package/dist/shared/priority-queue/utils.d.ts +7 -0
  66. package/dist/shared/priority-queue/utils.js +1 -0
  67. package/dist/shared/throw-error/index.d.ts +4 -3
  68. package/dist/shared/throw-error/index.js +1 -10
  69. package/dist/shared/try-call/index.d.ts +22 -0
  70. package/dist/shared/try-call/index.js +1 -0
  71. package/dist/shared/types/base.d.ts +2 -0
  72. package/dist/shared/types/index.js +1 -2
  73. package/dist/shared/types/pack.d.ts +3 -3
  74. package/dist/shared/types/pack.js +1 -1
  75. package/dist/shared/utils/base.d.ts +1 -1
  76. package/dist/shared/utils/base.js +1 -6
  77. package/dist/shared/utils/index.js +1 -2
  78. package/dist/shared/utils/verify.d.ts +1 -1
  79. package/dist/shared/utils/verify.js +1 -67
  80. package/dist/shared/with-resolvers/index.d.ts +5 -3
  81. package/dist/shared/with-resolvers/index.js +1 -15
  82. package/dist/vue/index.js +1 -29
  83. package/dist/vue/use-title/index.d.ts +2 -2
  84. package/dist/vue/use-title/index.js +1 -29
  85. package/package.json +29 -26
  86. package/dist/607.js +0 -737
  87. package/dist/707.js +0 -141
  88. package/dist/react/use-boolean/index.test.d.ts +0 -1
  89. package/dist/react/use-controllable-value/index.test.d.ts +0 -1
  90. package/dist/react/use-counter/index.test.d.ts +0 -1
  91. package/dist/react/use-force-update/index.test.d.ts +0 -1
  92. package/dist/react/use-mount/index.test.d.ts +0 -1
  93. package/dist/react/use-ref-state/index.test.d.ts +0 -1
  94. package/dist/react/use-storage/index.test.d.ts +0 -1
  95. package/dist/react/use-title/index.test.d.ts +0 -1
  96. package/dist/react/use-toggle/index.test.d.ts +0 -1
  97. package/dist/react/use-valid-data/index.test.d.ts +0 -1
  98. package/dist/shared/allx/__test__/allsettled.test.d.ts +0 -1
  99. package/dist/shared/allx/__test__/basic.test.d.ts +0 -1
  100. package/dist/shared/allx/__test__/circular-dependency.test.d.ts +0 -1
  101. package/dist/shared/allx/__test__/dependency.test.d.ts +0 -1
  102. package/dist/shared/allx/__test__/edge-cases.test.d.ts +0 -1
  103. package/dist/shared/allx/__test__/error-handling.test.d.ts +0 -1
  104. package/dist/shared/allx/__test__/execution-order.test.d.ts +0 -1
  105. package/dist/shared/allx/__test__/falsy-values.test.d.ts +0 -1
  106. package/dist/shared/allx/__test__/performance.test.d.ts +0 -1
  107. package/dist/shared/allx/__test__/type-checking.test.d.ts +0 -1
  108. package/dist/shared/allx/__test__/use-cases.test.d.ts +0 -1
  109. package/dist/shared/animation/__test__/animation-pause-resume.test.d.ts +0 -1
  110. package/dist/shared/animation/__test__/animation.test.d.ts +0 -1
  111. package/dist/shared/animation/__test__/step-animation.test.d.ts +0 -1
  112. package/dist/shared/animation/__test__/utils.test.d.ts +0 -1
  113. package/dist/shared/condition-merge/index.test-d.js +0 -108
  114. package/dist/shared/condition-merge/index.test.d.ts +0 -1
  115. package/dist/shared/create-storage-handler/index.browser.test.d.ts +0 -1
  116. package/dist/shared/create-storage-handler/index.test.d.ts +0 -1
  117. package/dist/shared/data-handler/index.test.d.ts +0 -1
  118. package/dist/shared/data-mixed-manager/__test__/basic.test.d.ts +0 -1
  119. package/dist/shared/data-mixed-manager/__test__/build-options.test.d.ts +0 -1
  120. package/dist/shared/data-mixed-manager/__test__/constructor-options.test.d.ts +0 -1
  121. package/dist/shared/data-mixed-manager/__test__/data-management.test.d.ts +0 -1
  122. package/dist/shared/data-mixed-manager/__test__/edge-cases.test.d.ts +0 -1
  123. package/dist/shared/data-mixed-manager/__test__/events.browser.test.d.ts +0 -1
  124. package/dist/shared/data-mixed-manager/__test__/events.test.d.ts +0 -1
  125. package/dist/shared/data-mixed-manager/__test__/fixed-slots.test.d.ts +0 -1
  126. package/dist/shared/data-mixed-manager/__test__/insert-mode.test.d.ts +0 -1
  127. package/dist/shared/throw-error/index.test.d.ts +0 -1
  128. package/dist/shared/utils/__test__/base.test.d.ts +0 -1
  129. package/dist/shared/utils/__test__/verify.test.d.ts +0 -1
  130. package/dist/shared/with-resolvers/index.test.d.ts +0 -1
  131. package/dist/test/utils.d.ts +0 -13
  132. package/dist/vue/use-title/index.test.d.ts +0 -1
@@ -1,44 +1 @@
1
- import { $dt, $t, dataHandler } from "../data-handler/index.js";
2
- import { isFunction, isPromiseLike } from "../utils/verify.js";
3
- import { withResolvers } from "../with-resolvers/index.js";
4
- import { createDepProxy, getValueFormatFunc } from "./utils.js";
5
- const validInfo = $dt({
6
- allSettled: $t.boolean(false)
7
- });
8
- async function allx(tasks, options) {
9
- const validOptions = dataHandler(options || {}, validInfo, {
10
- unwrap: true
11
- });
12
- const { allSettled } = validOptions;
13
- const results = {};
14
- const depCtrl = createDepProxy(tasks, results, validOptions);
15
- const valueFormat = getValueFormatFunc(options);
16
- const promises = [];
17
- depCtrl.taskNameSet.forEach(async (taskName)=>{
18
- const taskFn = tasks[taskName];
19
- const context = {
20
- $: depCtrl.createContextFor(taskName)
21
- };
22
- const taskResolvers = withResolvers();
23
- taskResolvers.promise.then((value)=>{
24
- results[taskName] = valueFormat(value, 'fulfilled');
25
- depCtrl.resolveDepFor(taskName, value);
26
- return value;
27
- }, (error)=>{
28
- if (allSettled) results[taskName] = valueFormat(error, 'rejected');
29
- depCtrl.rejectDepFor(taskName, error);
30
- });
31
- promises.push(taskResolvers.promise);
32
- if (isPromiseLike(taskFn)) return void await taskFn.then(taskResolvers.resolve, taskResolvers.reject);
33
- if (!isFunction(taskFn)) return void taskResolvers.resolve(taskFn);
34
- try {
35
- const result = await taskFn.call(context);
36
- taskResolvers.resolve(result);
37
- } catch (error) {
38
- taskResolvers.reject(error);
39
- }
40
- });
41
- if (allSettled) return Promise.allSettled(promises).then(()=>results);
42
- return Promise.all(promises).then(()=>results);
43
- }
44
- export { allx };
1
+ import{$dt as e,$t as r,dataHandler as t}from"../data-handler/index.js";import{isFunction as o,isPromiseLike as l}from"../utils/verify.js";import{withResolvers as i}from"../with-resolvers/index.js";import{createDepProxy as a,getValueFormatFunc as s}from"./utils.js";let n=e({allSettled:r.boolean(!1)});async function m(e,r){let m=t(r||{},n,{unwrap:!0}),{allSettled:c}=m,f={},p=a(e,f,m),d=s(r),h=[];return(p.taskNameSet.forEach(async r=>{let t=e[r],a={$:p.createContextFor(r)},s=i();if(s.promise.then(e=>(f[r]=d(e,"fulfilled"),p.resolveDepFor(r,e),e),e=>{c&&(f[r]=d(e,"rejected")),p.rejectDepFor(r,e)}),h.push(s.promise),l(t))return void await t.then(s.resolve,s.reject);if(!o(t))return void s.resolve(t);try{let e=await t.call(a);s.resolve(e)}catch(e){s.reject(e)}}),c)?Promise.allSettled(h).then(()=>f):Promise.all(h).then(()=>f)}export{m as allx};
@@ -11,3 +11,9 @@ export interface AllxContext<M extends Record<PropertyKey, AnyFunc>> {
11
11
  export type AllxResult<M extends Record<PropertyKey, AnyFunc>, O extends AllxOptions = AllxOptions> = {
12
12
  [P in keyof M]: O['allSettled'] extends true ? PromiseSettledResult<Awaited<ReturnType<M[P]>>> : AllxTaskValue<M[P]>;
13
13
  };
14
+ export interface DepProxyResult {
15
+ taskNameSet: Set<PropertyKey>;
16
+ createContextFor: (currentTask: PropertyKey) => any;
17
+ resolveDepFor: (depName: PropertyKey, value: any) => void;
18
+ rejectDepFor: (depName: PropertyKey, error: any) => void;
19
+ }
@@ -1,9 +1,11 @@
1
1
  import type { AnyFunc } from '../types/base';
2
- import type { AllxOptions } from './types';
3
- export declare function createDepProxy(tasks: Record<PropertyKey, AnyFunc>, results: Record<PropertyKey, any>, options: Required<AllxOptions>): {
4
- taskNameSet: Set<PropertyKey>;
5
- createContextFor: (currentTask: PropertyKey) => {};
6
- resolveDepFor: (depName: PropertyKey, value: any) => void;
7
- rejectDepFor: (depName: PropertyKey, error: any) => void;
8
- };
2
+ import type { AllxOptions, DepProxyResult } from './types';
3
+ /**
4
+ * BFS 算法处理 waitingForGraph 的依赖关系
5
+ */
6
+ export declare function detectCycle(from: PropertyKey, to: PropertyKey, waitingForGraph: Map<PropertyKey, Set<PropertyKey>>): boolean;
7
+ export declare function getCached(results: Record<PropertyKey, any>, depName: PropertyKey, allSettled: boolean): Promise<any> | undefined;
8
+ export declare function createDepResolver(waitingFor: Map<PropertyKey, Set<PropertyKey>>, resolverMap: Map<PropertyKey, PromiseWithResolvers<any>>, currentTask: PropertyKey, depName: PropertyKey): Promise<any>;
9
+ export declare function cleanWaitingForGraph(waitingForGraph: Map<PropertyKey, Set<PropertyKey>>, depName: PropertyKey): void;
10
+ export declare function createDepProxy(tasks: Record<PropertyKey, AnyFunc>, results: Record<PropertyKey, any>, options: Required<AllxOptions>): DepProxyResult;
9
11
  export declare function getValueFormatFunc(options?: AllxOptions): (value: any, _type?: PromiseSettledResult<any>["status"]) => any;
@@ -1,94 +1 @@
1
- import { createError } from "../throw-error/index.js";
2
- import { withResolvers } from "../with-resolvers/index.js";
3
- function detectCycle(from, to, waitingForGraph) {
4
- const visited = new Set();
5
- const queue = [
6
- to
7
- ];
8
- let head = 0;
9
- while(head < queue.length){
10
- const node = queue[head++];
11
- if (node === from) return true;
12
- if (visited.has(node)) continue;
13
- visited.add(node);
14
- const deps = waitingForGraph.get(node);
15
- if (deps) {
16
- const depsIter = deps.values();
17
- for(let dep = depsIter.next(); !dep.done; dep = depsIter.next())queue.push(dep.value);
18
- }
19
- }
20
- return false;
21
- }
22
- function getCached(results, depName, allSettled) {
23
- if (Reflect.getOwnPropertyDescriptor(results, depName)) {
24
- const cached = results[depName];
25
- if (allSettled) return 'rejected' === cached.status ? Promise.reject(cached.reason) : Promise.resolve(cached.value);
26
- return Promise.resolve(cached);
27
- }
28
- }
29
- function createDepResolver(waitingFor, resolverMap, currentTask, depName) {
30
- waitingFor.set(currentTask, (waitingFor.get(currentTask) || new Set()).add(depName));
31
- const depResolvers = resolverMap.get(depName) || withResolvers();
32
- resolverMap.set(depName, depResolvers);
33
- return depResolvers.promise.then((value)=>{
34
- waitingFor.get(currentTask)?.delete(depName);
35
- return value;
36
- }, (error)=>{
37
- waitingFor.get(currentTask)?.delete(depName);
38
- throw error;
39
- });
40
- }
41
- function cleanWaitingForGraph(waitingForGraph, depName) {
42
- waitingForGraph.forEach((deps, task)=>{
43
- deps.delete(depName);
44
- if (0 === deps.size) waitingForGraph.delete(task);
45
- });
46
- }
47
- function createDepProxy(tasks, results, options) {
48
- const resolverMap = new Map();
49
- const taskNameSet = new Set(Reflect.ownKeys(tasks));
50
- const waitingForGraph = new Map();
51
- const resolveDepFor = (depName, value)=>{
52
- const resolver = resolverMap.get(depName);
53
- if (resolver) {
54
- resolver.resolve(value);
55
- resolverMap.delete(depName);
56
- }
57
- cleanWaitingForGraph(waitingForGraph, depName);
58
- };
59
- const rejectDepFor = (depName, error)=>{
60
- const resolver = resolverMap.get(depName);
61
- if (resolver) {
62
- resolver.reject(error);
63
- resolverMap.delete(depName);
64
- }
65
- cleanWaitingForGraph(waitingForGraph, depName);
66
- };
67
- const createContextFor = (currentTask)=>new Proxy({}, {
68
- get (_, depName) {
69
- if (!taskNameSet.has(depName)) return Promise.reject(createError('allx', `Unknown task "${String(depName)}"`));
70
- const cached = getCached(results, depName, options.allSettled);
71
- if (cached) return cached;
72
- if (detectCycle(currentTask, depName, waitingForGraph)) return Promise.reject(createError('allx', `Circular dependency detected: "${String(currentTask)}" -> "${String(depName)}"`));
73
- return createDepResolver(waitingForGraph, resolverMap, currentTask, depName);
74
- }
75
- });
76
- return {
77
- taskNameSet,
78
- createContextFor,
79
- resolveDepFor,
80
- rejectDepFor
81
- };
82
- }
83
- function getValueFormatFunc(options) {
84
- if (!options) return (value, _type = 'fulfilled')=>value;
85
- if (options.allSettled) return (value, status = 'fulfilled')=>'fulfilled' === status ? {
86
- status,
87
- value
88
- } : {
89
- status,
90
- reason: value
91
- };
92
- return (value, _type = 'fulfilled')=>value;
93
- }
94
- export { createDepProxy, getValueFormatFunc };
1
+ import{createError as e}from"../throw-error/index.js";import{isNullOrUndef as t}from"../utils/verify.js";import{withResolvers as r}from"../with-resolvers/index.js";function l(e,t,r){let l=new Set,n=[t],o=0;for(;o<n.length;){let t=n[o++];if(t===e)return!0;if(l.has(t))continue;l.add(t);let i=r.get(t);if(i){let e=i.values();for(let t=e.next();!t.done;t=e.next())n.push(t.value)}}return!1}function n(e,t,r){if(Reflect.getOwnPropertyDescriptor(e,t)){let l=e[t];return r?"rejected"===l.status?Promise.reject(l.reason):Promise.resolve(l.value):Promise.resolve(l)}}function o(e,t,l,n){e.set(l,(e.get(l)||new Set).add(n));let o=t.get(n)||r();return t.set(n,o),o.promise.then(t=>(e.get(l)?.delete(n),t),t=>{throw e.get(l)?.delete(n),t})}function i(e,t){e.forEach((r,l)=>{r.delete(t),0===r.size&&e.delete(l)})}function s(r,s,a){let c=new Map,f=new Set(Reflect.ownKeys(r)),u=new Map;return{taskNameSet:f,createContextFor:r=>new Proxy({},{get(i,d){if(!f.has(d))return Promise.reject(e("allx",`Unknown task "${String(d)}"`));let g=n(s,d,a.allSettled);return t(g)?l(r,d,u)?Promise.reject(e("allx",`Circular dependency detected: "${String(r)}" -> "${String(d)}"`)):o(u,c,r,d):g}}),resolveDepFor:(e,t)=>{let r=c.get(e);r&&(r.resolve(t),c.delete(e)),i(u,e)},rejectDepFor:(e,t)=>{let r=c.get(e);r&&(r.reject(t),c.delete(e)),i(u,e)}}}function a(e){return e?e.allSettled?(e,t="fulfilled")=>"fulfilled"===t?{status:t,value:e}:{status:t,reason:e}:(e,t="fulfilled")=>e:(e,t="fulfilled")=>e}export{i as cleanWaitingForGraph,s as createDepProxy,o as createDepResolver,l as detectCycle,n as getCached,a as getValueFormatFunc};
@@ -1,3 +1,4 @@
1
1
  import type { AnimationBaseOptions, AnimationOptions, AnimationResult } from './types';
2
- export declare function stepAnimation<T>(from: T, to: T, step: number, options?: AnimationBaseOptions<T>): Generator<any, void, unknown>;
3
- export declare function animation<T>(from: T, to: T, duration: number, options?: AnimationOptions<T>): AnimationResult;
2
+ declare function stepAnimation<T>(from: T, to: T, step: number, options?: AnimationBaseOptions<T>): Generator<T>;
3
+ declare function animation<T>(from: T, to: T, duration: number, options?: AnimationOptions<T>): AnimationResult;
4
+ export { animation, stepAnimation };
@@ -1,77 +1 @@
1
- import { $dt, $t, dataHandler } from "../data-handler/index.js";
2
- import { throwError } from "../throw-error/index.js";
3
- import { identity, noop } from "../utils/base.js";
4
- import { createNextTick, createRunningControllerSignal, getNextValueHandler, matchValid } from "./utils.js";
5
- const validInfo = $dt({
6
- autoStart: $t.boolean(true),
7
- easing: $t["function"](()=>identity),
8
- onStart: $t["function"](()=>noop),
9
- onStop: $t["function"](()=>noop),
10
- onClear: $t["function"](()=>noop),
11
- onUpdate: $t["function"](()=>noop),
12
- onComplete: $t["function"](()=>noop),
13
- formatterValue: $t["function"](()=>identity),
14
- formatter: $t["function"](()=>identity),
15
- parser: $t["function"](()=>identity)
16
- });
17
- function* stepAnimation(from, to, step, options = {}) {
18
- if (!Number.isInteger(step) || step <= 0) throwError('stepAnimation', 'step must be a positive integer', RangeError);
19
- const validOptions = dataHandler(options, validInfo, {
20
- unwrap: true
21
- });
22
- const { parser: valueParser = identity, formatterValue = identity, formatter } = validOptions;
23
- const [validFrom, validTo] = matchValid(from, to, valueParser);
24
- const getNextValue = getNextValueHandler(validFrom, validTo, formatterValue);
25
- for(let i = 0; i <= step; i++){
26
- const value = formatter(getNextValue(i / step));
27
- yield value;
28
- }
29
- }
30
- function animation(from, to, duration, options = {}) {
31
- if (duration <= 0 || !Number.isInteger(duration)) throwError('animation', 'duration must be a positive integer', RangeError);
32
- const validOptions = dataHandler(options, validInfo, {
33
- unwrap: true
34
- });
35
- const [validFrom, validTo] = matchValid(from, to, validOptions.parser);
36
- const { autoStart, easing, onComplete, onUpdate, formatterValue, formatter } = validOptions;
37
- const _getNextValue = getNextValueHandler(validFrom, validTo, formatterValue);
38
- const getNextValue = (...args)=>formatter(_getNextValue(...args));
39
- let startTime = 0;
40
- let hasStarted = false;
41
- const rcSignal = createRunningControllerSignal(()=>{
42
- const now = performance.now();
43
- startTime += now;
44
- const stopFlag = nextTick(tick);
45
- if (stopFlag) {
46
- startTime -= performance.now();
47
- return;
48
- }
49
- if (!hasStarted) {
50
- onUpdate(getNextValue(0));
51
- hasStarted = true;
52
- }
53
- }, validOptions);
54
- const { resolvers } = rcSignal;
55
- const nextTick = createNextTick(resolvers, rcSignal);
56
- const tick = ()=>{
57
- const elapsed = performance.now() - startTime;
58
- const progress = easing(Math.min(elapsed / duration, 1));
59
- const value = getNextValue(progress);
60
- onUpdate(value);
61
- if (elapsed < duration) {
62
- const stopFlag = nextTick(tick);
63
- if (stopFlag) startTime = -elapsed;
64
- } else {
65
- onComplete();
66
- resolvers.resolve(false);
67
- }
68
- };
69
- if (false !== autoStart) rcSignal.start();
70
- return {
71
- promise: resolvers.promise,
72
- stop: rcSignal.stop,
73
- start: rcSignal.start,
74
- clear: rcSignal.clear
75
- };
76
- }
77
- export { animation, stepAnimation };
1
+ import{$dt as t,$t as r,dataHandler as e}from"../data-handler/index.js";import{throwError as n}from"../throw-error/index.js";import{identity as o,noop as i}from"../utils/base.js";import{createNextTick as a,createRunningControllerSignal as s,getNextValueHandler as m,matchValid as p}from"./utils.js";let u=t({autoStart:r.boolean(!0),easing:r.function(()=>o),onStart:r.function(()=>i),onStop:r.function(()=>i),onClear:r.function(()=>i),onUpdate:r.function(()=>i),onComplete:r.function(()=>i),formatterValue:r.function(()=>o),formatter:r.function(()=>o),parser:r.function(()=>o)});function*f(t,r,i,a={}){(!Number.isInteger(i)||i<=0)&&n("stepAnimation","step must be a positive integer",RangeError);let{parser:s=o,formatterValue:l=o,formatter:c}=e(a,u,{unwrap:!0}),[d,g]=p(t,r,s),b=m(d,g,l);for(let t=0;t<=i;t++){let r=c(b(t/i));yield r}}function l(t,r,o,i={}){(o<=0||!Number.isInteger(o))&&n("animation","duration must be a positive integer",RangeError);let f=e(i,u,{unwrap:!0}),[c,d]=p(t,r,f.parser),{autoStart:g,easing:b,onComplete:w,onUpdate:j,formatterValue:h,formatter:v}=f,x=m(c,d,h),S=(...t)=>v(x(...t)),A=0,C=!1,E=s(()=>{let t=performance.now();if(A+=t,N(R)){A-=performance.now();return}C||(j(S(0)),C=!0)},f),{resolvers:I}=E,N=a(I,E),R=()=>{let t=performance.now()-A;j(S(b(Math.min(t/o,1)))),t<o?N(R)&&(A=-t):(w(),I.resolve(!1))};return!1!==g&&E.start(),{promise:I.promise,stop:E.stop,start:E.start,clear:E.clear}}export{l as animation,f as stepAnimation};
@@ -1,3 +1,4 @@
1
+ import type { Resolver } from '../with-resolvers';
1
2
  export type FormatterValue = (value: number) => any;
2
3
  export type Formatter<T> = (value: T) => any;
3
4
  export interface AnimationBaseOptions<T> {
@@ -22,3 +23,10 @@ export interface AnimationCtrl {
22
23
  export type AnimationResult = AnimationCtrl & {
23
24
  promise: Promise<boolean>;
24
25
  };
26
+ export interface RCSignal {
27
+ stopSignal: boolean;
28
+ resolvers: Resolver<boolean>;
29
+ stop: () => void;
30
+ start: () => void;
31
+ clear: () => void;
32
+ }
@@ -1,14 +1,7 @@
1
1
  import { type Resolver } from '../with-resolvers';
2
- import type { AnimationOptions, FormatterValue } from './types';
2
+ import type { AnimationOptions, FormatterValue, RCSignal } from './types';
3
3
  export declare function getNextValueHandler<T>(from: T, to: T, valueFormatter: FormatterValue): (progress: number) => any;
4
- export declare function matchValid(from: any, to: any, valueParser: (value: any) => number): number[] | unknown[][] | [Record<PropertyKey, any>, Record<PropertyKey, any>];
4
+ export declare function matchValid(from: any, to: any, valueParser: (value: any) => number): [any, any];
5
5
  export declare function createNextTick(resolvers: Resolver<any>, rcSignal: RCSignal): (callback: (...args: any[]) => void) => boolean;
6
6
  export declare function tryRun(callback: () => any, resolvers: Resolver<any>, customErrorHandler?: (err: any) => void): Promise<void>;
7
- export declare function createRunningControllerSignal(startFn: () => void, options: Required<AnimationOptions<any>>): {
8
- stopSignal: boolean;
9
- resolvers: Resolver<boolean>;
10
- stop: () => void;
11
- start: () => void;
12
- clear: () => void;
13
- };
14
- export type RCSignal = Omit<ReturnType<typeof createRunningControllerSignal>, 'resolvers'>;
7
+ export declare function createRunningControllerSignal(startFn: () => void, options: Required<AnimationOptions<any>>): RCSignal;
@@ -1,134 +1 @@
1
- import { throwType } from "../throw-error/index.js";
2
- import { getType } from "../utils/base.js";
3
- import { withResolvers } from "../with-resolvers/index.js";
4
- function getNextValueHandler(from, to, valueFormatter) {
5
- const type = getType(from);
6
- const context = {
7
- progress: 0,
8
- valueFormatter
9
- };
10
- const baseNextValue = (_from, _to)=>{
11
- const { valueFormatter: formatter, progress } = context;
12
- if ('number' !== getType(_from)) return _from;
13
- return formatter(_from + (_to - _from) * progress);
14
- };
15
- const arrayHandler = (_from, _to)=>{
16
- const result = Array.from(_from, (item, idx)=>{
17
- if (Array.isArray(item)) return arrayHandler(item, _to[idx]);
18
- if ('object' === getType(item)) return objectHandler(item, _to[idx]);
19
- return baseNextValue(item, _to[idx]);
20
- });
21
- return result;
22
- };
23
- const objectHandler = (_from, _to)=>{
24
- const result = {};
25
- const keys = Reflect.ownKeys(_from);
26
- for(let i = 0; i < keys.length; i++){
27
- const key = keys[i];
28
- const fromValue = _from[key];
29
- const toValue = _to[key];
30
- if (Array.isArray(_from[key])) result[key] = arrayHandler(fromValue, toValue);
31
- else if ('object' === getType(fromValue)) result[key] = objectHandler(fromValue, toValue);
32
- else result[key] = baseNextValue(fromValue, toValue);
33
- }
34
- return result;
35
- };
36
- let nextValueHandler = baseNextValue;
37
- if ('array' === type) nextValueHandler = arrayHandler;
38
- else if ('object' === type) nextValueHandler = objectHandler;
39
- return (progress)=>{
40
- context.progress = progress;
41
- return nextValueHandler(from, to);
42
- };
43
- }
44
- function matchValid(from, to, valueParser) {
45
- const fromType = getType(from);
46
- const toType = getType(to);
47
- if (fromType !== toType) throwType('animation/stepAnimation', 'from and to must be the same type');
48
- if ('array' === fromType) {
49
- if (from.length !== to.length) throwType('animation/stepAnimation', 'from and to must be the same length');
50
- const result = [
51
- Array.from({
52
- length: from.length
53
- }),
54
- Array.from({
55
- length: to.length
56
- })
57
- ];
58
- for(let i = 0; i < from.length; i++){
59
- const [fromItem, toItem] = matchValid(from[i], to[i], valueParser);
60
- result[0][i] = fromItem;
61
- result[1][i] = toItem;
62
- }
63
- return result;
64
- }
65
- if ('object' === fromType) {
66
- const toKeys = Reflect.ownKeys(to);
67
- const fromKeys = new Set(Reflect.ownKeys(from));
68
- const result = [
69
- {},
70
- {}
71
- ];
72
- for(let i = 0; i < toKeys.length; i++){
73
- const key = toKeys[i];
74
- if (!fromKeys.has(key)) throwType('animation/stepAnimation', `from does not have this key: ${String(key)}`);
75
- const [fromItem, toItem] = matchValid(from[key], to[key], valueParser);
76
- result[0][key] = fromItem;
77
- result[1][key] = toItem;
78
- }
79
- return result;
80
- }
81
- if ('number' !== fromType) return [
82
- valueParser(from),
83
- valueParser(to)
84
- ];
85
- return [
86
- from,
87
- to
88
- ];
89
- }
90
- function createNextTick(resolvers, rcSignal) {
91
- const nextTick = (()=>{
92
- if ('function' == typeof globalThis.requestAnimationFrame) return globalThis.requestAnimationFrame;
93
- return (callback)=>setTimeout(callback, 16);
94
- })();
95
- return (callback)=>{
96
- if (rcSignal.stopSignal) return true;
97
- nextTick(()=>tryRun(callback, resolvers, (error)=>{
98
- rcSignal.stop();
99
- resolvers.reject(error);
100
- }));
101
- return false;
102
- };
103
- }
104
- async function tryRun(callback, resolvers, customErrorHandler) {
105
- return new Promise((resolve, reject)=>{
106
- const result = callback();
107
- if (result && 'function' == typeof result.then) return result.then(resolve, reject);
108
- resolve();
109
- }).catch(customErrorHandler || resolvers.reject);
110
- }
111
- function createRunningControllerSignal(startFn, options) {
112
- const { onStart, onStop, onClear } = options;
113
- const resolvers = withResolvers();
114
- const ctrl = {
115
- stopSignal: true,
116
- resolvers,
117
- stop: ()=>{
118
- ctrl.stopSignal = true;
119
- onStop();
120
- },
121
- start: ()=>{
122
- ctrl.stopSignal = false;
123
- onStart();
124
- startFn();
125
- },
126
- clear: ()=>{
127
- ctrl.stopSignal = true;
128
- onClear();
129
- resolvers.resolve(true);
130
- }
131
- };
132
- return ctrl;
133
- }
134
- export { createNextTick, createRunningControllerSignal, getNextValueHandler, matchValid, tryRun };
1
+ import{throwType as t}from"../throw-error/index.js";import{getType as e}from"../utils/base.js";import{isPromiseLike as r}from"../utils/verify.js";import{withResolvers as n}from"../with-resolvers/index.js";function o(t,r,n){let o=e(t),i={progress:0,valueFormatter:n},a=(t,r)=>{let{valueFormatter:n,progress:o}=i;return"number"!==e(t)?t:n(t+(r-t)*o)},l=(t,r)=>Array.from(t,(t,n)=>Array.isArray(t)?l(t,r[n]):"object"===e(t)?s(t,r[n]):a(t,r[n])),s=(t,r)=>{let n={},o=Reflect.ownKeys(t);for(let i=0;i<o.length;i++){let m=o[i],u=t[m],f=r[m];Array.isArray(t[m])?n[m]=l(u,f):"object"===e(u)?n[m]=s(u,f):n[m]=a(u,f)}return n},m=a;return"array"===o?m=l:"object"===o&&(m=s),e=>(i.progress=e,m(t,r))}function i(r,n,o){let a=e(r);if(a!==e(n)&&t("animation/stepAnimation","from and to must be the same type"),"array"===a){r.length!==n.length&&t("animation/stepAnimation","from and to must be the same length");let e=[Array.from({length:r.length}),Array.from({length:n.length})];for(let t=0;t<r.length;t++){let[a,l]=i(r[t],n[t],o);e[0][t]=a,e[1][t]=l}return e}if("object"===a){let e=Reflect.ownKeys(n),a=new Set(Reflect.ownKeys(r)),l=[{},{}];for(let s=0;s<e.length;s++){let m=e[s];a.has(m)||t("animation/stepAnimation",`from does not have this key: ${String(m)}`);let[u,f]=i(r[m],n[m],o);l[0][m]=u,l[1][m]=f}return l}return"number"!==a?[o(r),o(n)]:[r,n]}function a(t,e){let r="function"==typeof globalThis.requestAnimationFrame?globalThis.requestAnimationFrame:t=>setTimeout(t,16);return n=>!!e.stopSignal||(r(()=>l(n,t,r=>{e.stop(),t.reject(r)})),!1)}async function l(t,e,n){return new Promise((e,n)=>{let o=t();if(r(o))return o.then(e,n);e()}).catch(n??e.reject)}function s(t,e){let{onStart:r,onStop:o,onClear:i}=e,a=n(),l={stopSignal:!0,resolvers:a,stop:()=>{l.stopSignal=!0,o()},start:()=>{l.stopSignal=!1,r(),t()},clear:()=>{l.stopSignal=!0,i(),a.resolve(!0)}};return l}export{a as createNextTick,s as createRunningControllerSignal,o as getNextValueHandler,i as matchValid,l as tryRun};
@@ -0,0 +1,26 @@
1
+ import type { APIConfig, APIMap, APIMapTransformMethods, APITransformMethod, DefaultAPIConfig, DefineAPIConfig } from './types';
2
+ /**
3
+ * 通过 API config map 创建请求对象
4
+ *
5
+ * @param apiMap API config map
6
+ * @param defaultConfig 默认配置
7
+ */
8
+ export declare function createApiWithMap<M extends APIMap, D extends DefaultAPIConfig = DefaultAPIConfig>(apiMap: M, defaultConfig?: D): APIMapTransformMethods<M, D>;
9
+ /**
10
+ * 通过 API config 创建一个请求方法
11
+ *
12
+ * @param api API config
13
+ * @param defaultConfig 默认配置
14
+ * @param custom 是否为自定义请求
15
+ */
16
+ export declare function createApi<A extends APIConfig, D extends DefaultAPIConfig = DefaultAPIConfig, C extends boolean = false>(api: A, defaultConfig?: D, custom?: C): APITransformMethod<A, D, C>;
17
+ /**
18
+ * 定义 API, ts 支持, 获取更好的类型声明
19
+ * @warn 不应该被复用, 如果希望复用的话请使用 apiInstance.$
20
+ */
21
+ export declare function defineApi<U extends string, A extends DefineAPIConfig<U>>(_api: A): A;
22
+ /**
23
+ * 定义 API map, ts 支持, 获取更好的类型声明
24
+ * @warn 不应该被复用, 如果希望复用的话请使用 apiInstance.$
25
+ */
26
+ export declare function defineApiMap<U extends string, A extends APIMap<U>>(_apiMap: A): A;
@@ -0,0 +1 @@
1
+ import{logger as e}from"../logger/index.js";import{throwType as r}from"../throw-error/index.js";import{isString as t,isTrue as l}from"../utils/verify.js";import{request as i}from"./request.js";import{apiNamesCheck as n,createInstance as o,getInstanceMemberOrApi as u,instanceMemberGetter as p,isAbsUrl as f}from"./utils.js";let a=Symbol("fromDefine");function c(e,r){let i=e[a];delete e[a];let p=Object.create(null),f=r||{};l(i)||n(e);let s=o(e,f,r);return new Proxy(e,{get(e,r,l){if(Reflect.getOwnPropertyDescriptor(p,r))return p[r];let{instanceMember:n,api:o,isCustom:A=!1}=u(e,r,l,s)||{};if(n)return n;if(!o)return;let d=null;return d=t(o.url)?m({...o,[a]:i},f,A):c({...o,[a]:i},f),p[r]=d,d}})}function m(n,u,c){let m=n[a];delete n[a];let s=u||{};t(n.url)||r("apiController.createApi","入参应为 APIConfig 对象"),n.url.includes("/:")&&(l(m)||e.warn("apiController.createApi","url 中存在 params 参数, 使用 defineApi 或 defineApiMap 定义 API 或 API map 来获取更好的类型提示"),l(c)||r("apiController.createApi","url 中存在 params 参数, 不支持普通请求, 转为自定义请求"));let A=null;A=l(c)?(e,r)=>i({...s,...n,...r,url:n.url,data:e,oriUrl:n.url}):e=>i({...s,...n,data:e,oriUrl:n.url});let d=o(n,s,u);return f(n.url)||d.$updateBaseUrl(s.baseUrl),new Proxy(A,{get:(e,r,t)=>Reflect.getOwnPropertyDescriptor(d,r)?p(r,d):Reflect.get(e,r,t)})}function s(e){return{...e,[a]:!0}}function A(e){return n(e),{...e,[a]:!0}}export{m as createApi,c as createApiWithMap,s as defineApi,A as defineApiMap};
@@ -0,0 +1,3 @@
1
+ export { createApi, createApiWithMap, defineApi, defineApiMap } from './create-api';
2
+ export { request } from './request';
3
+ export type { APIConfig, APIMap, RequestMethod } from './types';
@@ -0,0 +1 @@
1
+ export{createApi,createApiWithMap,defineApi,defineApiMap}from"./create-api.js";export{request}from"./request.js";
@@ -0,0 +1,7 @@
1
+ import type { RequestAPIConfig } from './types';
2
+ /**
3
+ * 请求方法
4
+ *
5
+ * @param config 请求配置
6
+ */
7
+ export declare function request<R, C extends RequestAPIConfig<any, R> = RequestAPIConfig<any, R>>(config: C): Promise<R>;
@@ -0,0 +1 @@
1
+ import{throwType as e}from"../throw-error/index.js";import{tryCall as r}from"../try-call/index.js";import{isFunction as t,isNullOrUndef as n}from"../utils/verify.js";import{getBody as s,targetUrlParser as o,urlParamsParser as a}from"./utils.js";async function i(a,i){let{baseUrl:u,url:l,method:f,parser:p,data:c,tdto:m,tvo:y,onResponse:w,...d}=a,j=o(l,u),h=f?.toUpperCase(),R=r(()=>{if(n(h)||"GET"===h||"HEAD"===h){let e=Object.keys(c||{});for(let r=0;r<e.length;++r)j.searchParams.append(e[r],c[e[r]]);return new Request(j,{...d,method:h})}let e=s(c,m);return new Request(j,{...d,method:h,body:e})}),q=await i(R),x=await r(()=>{if(w)return w(q,a);if(!p)return q.json();if("stream"===p)return q.body;let r=q[p];if(t(r))return Reflect.apply(r,q,[]);e("apiController.responseParser","Invalid parser")});return y?y(x):x}async function u(e){let{onRequest:r,...t}=e;return i(e,async n=>new Response(s(await (r&&r(n,e))),{...t}))}async function l(e){return i(e,fetch)}function f(e){let r=a(e.url,e.params),{requestMode:t,requestModeMap:n}=e,s=(n||{})[t||""];return s?s({...e,url:r}):"mock"===t?u({...e,url:r}):l({...e,url:r})}export{f as request};
@@ -0,0 +1,140 @@
1
+ import type { AnyFunc, Cast, Equal, Func } from '../types/base';
2
+ import type { Pack as TPack } from '../types/pack';
3
+ export interface Empty {
4
+ __EMPTY__: never;
5
+ }
6
+ /** 请求方法 */
7
+ export type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | (string & {});
8
+ export type Parser = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData' | 'bytes' | 'stream' | (string & {});
9
+ export type RequestMode<E extends string = string & {}> = 'mock' | 'network' | E;
10
+ export type EmptyUnwrap<UserR = Empty, T = any> = Equal<UserR, Empty> extends true ? T : UserR;
11
+ export interface ParserResultMap<UserR = Empty> {
12
+ json: EmptyUnwrap<UserR>;
13
+ text: string;
14
+ blob: Blob;
15
+ arrayBuffer: ArrayBuffer;
16
+ formData: FormData;
17
+ bytes: Uint8Array;
18
+ stream: ReadableStream | null;
19
+ }
20
+ export type ParserResult<P extends Parser, UserR = Empty> = P extends keyof ParserResultMap ? ParserResultMap<UserR>[P] : EmptyUnwrap<UserR>;
21
+ export type ParserReturn<RM extends RequestMode, P extends Parser, ReqOutput, UserR = Empty> = RM extends 'network' ? ParserResult<P, UserR> : EmptyUnwrap<UserR, RM extends 'mock' ? ReqOutput : any>;
22
+ export type URLParamParser<U extends string, Param extends string = never> = U extends `${string}/:${infer P}/${infer Rest}` ? URLParamParser<`/${Rest}`, Param | P> : U extends `${string}/:${infer P}` ? P | Param : Param;
23
+ export type CheckNonParamUrlAPIConfig<A extends APIConfig> = Equal<URLParamParser<A['url']>, never>;
24
+ export interface BaseAPIConfig<Input = any, Output = any, ReqOutput = any, ResOutput = any, DefaultConfig extends DefaultAPIConfig = DefaultAPIConfig, ReqModeMapKeys extends string = string & {}, Url extends string = string> extends RequestInit {
25
+ /**
26
+ * 请求地址
27
+ *
28
+ * @example '/api/user'
29
+ * @example 'https://example.com/api/user'
30
+ */
31
+ url: Url;
32
+ params?: Record<URLParamParser<Url>, string | number>;
33
+ /** 请求模式 */
34
+ requestMode?: RequestMode<ReqModeMapKeys>;
35
+ /** 请求方法 */
36
+ method?: RequestMethod | Lowercase<RequestMethod>;
37
+ /**
38
+ * 响应体解析方式
39
+ * 如果存在 onResponse 的话, 则会使用 onResponse 的返回值, 如果想要屏蔽 onResponse 的继承, 则应该设置 onResponse 为 null
40
+ *
41
+ * @default 'json'
42
+ */
43
+ parser?: Parser;
44
+ /**
45
+ * transform data transfer object
46
+ *
47
+ * @tips GET/HEAD 方法因为是无 body 的请求, 不会触发 tdto 的转换
48
+ *
49
+ * @description hook 顺序: tdto -> onRequest -> onResponse/parser -> tvo
50
+ */
51
+ tdto?: ((data: Input) => any) | null;
52
+ /**
53
+ * transform view object
54
+ *
55
+ * @description hook 顺序: tdto -> onRequest -> onResponse/parser -> tvo
56
+ */
57
+ tvo?: ((data: Awaited<FindNonAny<[ResOutput, ReturnType<NonNullable<DefaultConfig['onResponse']>>]>>) => Output) | null;
58
+ /**
59
+ * 请求前 hook
60
+ *
61
+ * @description hook 顺序: tdto -> onRequest -> onResponse/parser -> tvo
62
+ */
63
+ onRequest?: ((req: Request, config: RequestAPIConfig<Input, Output, ReqOutput, ResOutput, ReqModeMapKeys>) => ReqOutput) | null;
64
+ /**
65
+ * 响应前 hook
66
+ * 会覆盖 parser 的解析方式
67
+ *
68
+ * @description hook 顺序: tdto -> onRequest -> onResponse/parser -> tvo
69
+ */
70
+ onResponse?: ((res: Response, config: RequestAPIConfig<Input, Output, ReqOutput, ResOutput, ReqModeMapKeys>) => ResOutput) | null;
71
+ }
72
+ export interface DefaultAPIConfig<Input = any, Output = any, ReqOutput = any, ResOutput = any, ReqModeMapKeys extends string = string & {}> extends Omit<BaseAPIConfig<Input, Output, ReqOutput, ResOutput, DefaultAPIConfig, ReqModeMapKeys>, 'url'> {
73
+ /** 基本地址 */
74
+ baseUrl?: string;
75
+ /** 请求模式 map */
76
+ requestModeMap?: Record<ReqModeMapKeys, (config: RequestAPIConfig<Input, Output, ReqOutput, ResOutput, ReqModeMapKeys>) => any>;
77
+ }
78
+ export interface RequestAPIConfig<Input = any, Output = any, ReqOutput = any, ResOutput = any, ReqModeMapKeys extends string = string & {}> extends DefaultAPIConfig<Input, Output, ReqOutput, ResOutput, ReqModeMapKeys>, APIConfig<Input, Output, ReqOutput, ResOutput, DefaultAPIConfig, ReqModeMapKeys> {
79
+ /** 请求数据 */
80
+ data?: Input;
81
+ oriUrl: string;
82
+ }
83
+ /**
84
+ * API config
85
+ */
86
+ export type APIConfig<Input = any, Output = any, ReqOutput = any, ResOutput = any, DefaultConfig extends DefaultAPIConfig = DefaultAPIConfig, ReqModeMapKeys extends string = string & {}, Url extends string = string> = BaseAPIConfig<Input, Output, ReqOutput, ResOutput, DefaultConfig, ReqModeMapKeys, Url>;
87
+ export type CallAPIConfig<Input = any, Output = any, ReqOutput = any, ResOutput = any, DefaultConfig extends DefaultAPIConfig = DefaultAPIConfig, ReqModeMapKeys extends string = string & {}, Url extends string = string> = Omit<APIConfig<Input, Output, ReqOutput, ResOutput, DefaultConfig, ReqModeMapKeys, Url>, 'url'>;
88
+ export type DefineAPIConfig<U extends string> = APIConfig<any, any, any, any, any, any, U>;
89
+ /** API map */
90
+ export interface APIMap<U extends string = string & {}> {
91
+ [key: string]: DefineAPIConfig<U> | APIMap<U>;
92
+ }
93
+ export type IsUnknownAny<T> = Equal<T, any> extends true ? true : Equal<T, unknown> extends true ? true : false;
94
+ export type FindNonAny<T extends any[], Other = Empty> = T extends [infer F, ...infer Last] ? IsUnknownAny<F> extends true ? FindNonAny<Last, Other> : F extends Other ? FindNonAny<Last, Other> : F : any;
95
+ export type APIHandlerArgs<I, C extends CallAPIConfig, Custom, NonParamUrl extends boolean> = FindNonAny<[
96
+ NonParamUrl extends true ? any : [I, C & Required<Pick<C, 'params'>>],
97
+ Custom extends true ? [I?, C?] : [I?],
98
+ [I?]
99
+ ]>;
100
+ export type DefineRequestModes<D extends DefaultAPIConfig> = keyof NonNullable<D['requestModeMap']> & string;
101
+ export type RealProp<P extends keyof DefaultAPIConfig & keyof APIConfig, C extends Pick<APIConfig, P>, A extends Pick<APIConfig, P>, D extends DefaultAPIConfig, Other = Empty> = FindNonAny<[C[P], A[P], D[P]], Other>;
102
+ export type OnResponseReturn<OnResponse> = OnResponse extends AnyFunc ? ReturnType<OnResponse> : any;
103
+ export type CustomCallConfigUnwrap<C extends CallAPIConfig, Custom extends boolean> = Custom extends true ? {
104
+ [K in keyof C as undefined extends C[K] ? never : K]: C[K];
105
+ } : Record<never, Empty>;
106
+ export interface Pack<T> extends TPack<T> {
107
+ __value: T;
108
+ }
109
+ export type PackUnwrap<P> = P extends Pack<any> ? P['__value'] : P;
110
+ export interface OriginalPack<T> extends TPack<T> {
111
+ __originValue: T;
112
+ }
113
+ export type OriginalPackUnwrap<P> = P extends OriginalPack<any> ? P['__originValue'] : Promise<P>;
114
+ export type CustomRequestModeReturn<RealRM extends RequestMode, InputD extends DefaultAPIConfig, CustomReq = NonNullable<InputD['requestModeMap']>[RealRM]> = IsUnknownAny<RealRM> extends true ? any : Equal<RealRM, string> extends true ? any : CustomReq extends AnyFunc ? OriginalPack<ReturnType<CustomReq>> : any;
115
+ export type UserInputResult<UserR, CustomRequestResult> = IsUnknownAny<CustomRequestResult> extends true ? UserR : IsUnknownAny<UserR> extends true ? any : UserR extends CustomRequestResult ? OriginalPack<UserR> : UserR;
116
+ export type APIHandlerResult<AConfig extends APIConfig, CallConfig extends CallAPIConfig = APIConfig, UserR = Empty, InputDefault extends DefaultAPIConfig = DefaultAPIConfig, ReqOutput = any, Custom extends boolean = false, CC extends CallAPIConfig = CustomCallConfigUnwrap<CallConfig, Custom>, CustomRequestResult = CustomRequestModeReturn<NonNullable<RealProp<'requestMode', CC, AConfig, InputDefault>>, InputDefault>> = OriginalPackUnwrap<Awaited<PackUnwrap<FindNonAny<[
117
+ UserInputResult<EmptyUnwrap<UserR>, OriginalPackUnwrap<CustomRequestResult>>,
118
+ CustomRequestResult,
119
+ ReturnType<Cast<RealProp<'tvo', CC, AConfig, InputDefault>, AnyFunc>>,
120
+ OnResponseReturn<RealProp<'onResponse', CC, AConfig, InputDefault>>,
121
+ ParserReturn<NonNullable<RealProp<'requestMode', CC, AConfig, InputDefault>>, NonNullable<RealProp<'parser', CC, AConfig, InputDefault>>, ReqOutput, UserR>
122
+ ], undefined | null>>>>;
123
+ export type APIInputType<A extends Pick<APIConfig, 'tdto'> = APIConfig, D extends Pick<DefaultAPIConfig, 'tdto'> = DefaultAPIConfig> = Parameters<Cast<FindNonAny<[A['tdto'], D['tdto']], undefined | null>, (...args: any[]) => any>>[0];
124
+ export type PropResult<A extends APIConfig, P extends keyof A> = A[P] extends AnyFunc ? ReturnType<A[P]> : unknown;
125
+ export type APITransformMethod<A extends APIConfig, InputD extends DefaultAPIConfig = DefaultAPIConfig, Custom extends boolean = false, NonParamUrl extends boolean = CheckNonParamUrlAPIConfig<A>, I extends APIInputType<A, InputD> = APIInputType<A, InputD>> = (<R = Empty, C extends CallAPIConfig<I, any, PropResult<A, 'onRequest'>, PropResult<A, 'onResponse'>, InputD, DefineRequestModes<InputD>, A['url']> = CallAPIConfig<I, any, PropResult<A, 'onRequest'>, PropResult<A, 'onResponse'>, InputD, DefineRequestModes<InputD>, A['url']>>(...args: APIHandlerArgs<Equal<I, APIInputType<A, InputD>> extends true ? APIInputType<C, {
126
+ tdto: Func<[I]>;
127
+ }> : I, C, Custom, NonParamUrl>) => APIHandlerResult<A, Cast<C, Partial<APIConfig>>, R, InputD, ReturnType<Cast<RealProp<'onRequest', C, A, InputD>, AnyFunc>>, Custom>) & APIInstance<A, InputD>;
128
+ export type APIInstance<A, D> = {
129
+ $: A;
130
+ $$: DefaultAPIConfig extends D ? undefined : D;
131
+ $$r: DefaultAPIConfig;
132
+ } & APIInstanceHandler;
133
+ export interface APIInstanceHandler {
134
+ $updateBaseUrl: (baseUrl?: string) => void;
135
+ }
136
+ export type APIMapTransformMethods<M extends APIMap | Record<string, APIConfig>, D extends DefaultAPIConfig = DefaultAPIConfig> = {
137
+ [K in keyof M as M[K] extends APIConfig ? CheckNonParamUrlAPIConfig<M[K]> extends true ? K : never : K]: M[K] extends APIConfig ? APITransformMethod<M[K], D, false> : APIMapTransformMethods<Cast<M[K], APIMap>, D>;
138
+ } & {
139
+ [K in keyof M as M[K] extends APIConfig ? `${K & string}Custom` : never]: APITransformMethod<Cast<M[K], APIConfig>, D, true>;
140
+ } & APIInstance<M, D>;
File without changes