target-supabase-sdk 0.1.7 → 0.1.9

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 (171) hide show
  1. package/README.md +8 -6
  2. package/dist/auth/auth.api.d.ts.map +1 -1
  3. package/dist/auth/auth.api.js +8 -7
  4. package/dist/auth/auth.api.js.map +1 -1
  5. package/dist/command/command.api.d.ts +43 -0
  6. package/dist/command/command.api.d.ts.map +1 -0
  7. package/dist/command/command.api.js +58 -0
  8. package/dist/command/command.api.js.map +1 -0
  9. package/dist/command/command.interface.d.ts +14 -0
  10. package/dist/command/command.interface.d.ts.map +1 -0
  11. package/dist/command/command.interface.js +9 -0
  12. package/dist/command/command.interface.js.map +1 -0
  13. package/dist/core.api.d.ts +116 -12
  14. package/dist/core.api.d.ts.map +1 -1
  15. package/dist/core.api.js +289 -103
  16. package/dist/core.api.js.map +1 -1
  17. package/dist/core.interface.d.ts +2 -1
  18. package/dist/core.interface.d.ts.map +1 -1
  19. package/dist/core.interface.js +1 -1
  20. package/dist/core.interface.js.map +1 -1
  21. package/dist/core.utils.d.ts +0 -2
  22. package/dist/core.utils.d.ts.map +1 -1
  23. package/dist/core.utils.js +0 -5
  24. package/dist/core.utils.js.map +1 -1
  25. package/dist/file/file-manager.d.ts +1 -1
  26. package/dist/file/file-manager.d.ts.map +1 -1
  27. package/dist/file/file-manager.js +1 -1
  28. package/dist/file/file-manager.js.map +1 -1
  29. package/dist/file-list/file-list.api.js +1 -1
  30. package/dist/file-list/file-list.api.js.map +1 -1
  31. package/dist/index.d.ts +12 -1
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +11 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/list/list.interface.d.ts +2 -2
  36. package/dist/list/list.interface.d.ts.map +1 -1
  37. package/dist/node/node-manager.d.ts +48 -0
  38. package/dist/node/node-manager.d.ts.map +1 -0
  39. package/dist/node/node-manager.js +619 -0
  40. package/dist/node/node-manager.js.map +1 -0
  41. package/dist/node/node-task.preset.d.ts +1 -0
  42. package/dist/node/node-task.preset.d.ts.map +1 -0
  43. package/dist/node/node-task.preset.js +14 -0
  44. package/dist/node/node-task.preset.js.map +1 -0
  45. package/dist/node/node.api.d.ts +68 -0
  46. package/dist/node/node.api.d.ts.map +1 -0
  47. package/dist/node/node.api.js +100 -0
  48. package/dist/node/node.api.js.map +1 -0
  49. package/dist/node/node.interface.d.ts +35 -0
  50. package/dist/node/node.interface.d.ts.map +1 -0
  51. package/dist/node/node.interface.js +19 -0
  52. package/dist/node/node.interface.js.map +1 -0
  53. package/dist/node/node.utils.d.ts +5 -0
  54. package/dist/node/node.utils.d.ts.map +1 -0
  55. package/dist/node/node.utils.js +36 -0
  56. package/dist/node/node.utils.js.map +1 -0
  57. package/dist/parcel/parcel-manager.d.ts +1 -1
  58. package/dist/parcel/parcel-manager.d.ts.map +1 -1
  59. package/dist/parcel/parcel-manager.js +1 -1
  60. package/dist/parcel/parcel-manager.js.map +1 -1
  61. package/dist/question-list/question-list.api.js +1 -1
  62. package/dist/question-list/question-list.api.js.map +1 -1
  63. package/dist/repo/repo-context.utils.d.ts +24 -0
  64. package/dist/repo/repo-context.utils.d.ts.map +1 -0
  65. package/dist/repo/repo-context.utils.js +81 -0
  66. package/dist/repo/repo-context.utils.js.map +1 -0
  67. package/dist/repo/repo-manager.d.ts +31 -0
  68. package/dist/repo/repo-manager.d.ts.map +1 -0
  69. package/dist/repo/repo-manager.js +156 -0
  70. package/dist/repo/repo-manager.js.map +1 -0
  71. package/dist/repo/repo.api.d.ts +16 -0
  72. package/dist/repo/repo.api.d.ts.map +1 -0
  73. package/dist/repo/repo.api.js +40 -0
  74. package/dist/repo/repo.api.js.map +1 -0
  75. package/dist/repo/repo.interface.d.ts +27 -0
  76. package/dist/repo/repo.interface.d.ts.map +1 -0
  77. package/dist/repo/repo.interface.js +8 -0
  78. package/dist/repo/repo.interface.js.map +1 -0
  79. package/dist/repo/repo.script-loader.d.ts +19 -0
  80. package/dist/repo/repo.script-loader.d.ts.map +1 -0
  81. package/dist/repo/repo.script-loader.js +108 -0
  82. package/dist/repo/repo.script-loader.js.map +1 -0
  83. package/dist/review/review.api.js +5 -5
  84. package/dist/review/review.api.js.map +1 -1
  85. package/dist/shared/log/create-api-logger.d.ts +17 -0
  86. package/dist/shared/log/create-api-logger.d.ts.map +1 -0
  87. package/dist/shared/log/create-api-logger.js +15 -0
  88. package/dist/shared/log/create-api-logger.js.map +1 -0
  89. package/dist/shared/log/log-manager.d.ts +114 -0
  90. package/dist/shared/log/log-manager.d.ts.map +1 -0
  91. package/dist/shared/log/log-manager.js +218 -0
  92. package/dist/shared/log/log-manager.js.map +1 -0
  93. package/dist/shared/utils/config-path.utils.d.ts +38 -0
  94. package/dist/shared/utils/config-path.utils.d.ts.map +1 -0
  95. package/dist/shared/utils/config-path.utils.js +85 -0
  96. package/dist/shared/utils/config-path.utils.js.map +1 -0
  97. package/dist/shared/utils/error.utils.d.ts +11 -0
  98. package/dist/shared/utils/error.utils.d.ts.map +1 -0
  99. package/dist/shared/utils/error.utils.js +15 -0
  100. package/dist/shared/utils/error.utils.js.map +1 -0
  101. package/dist/shared/utils/id.utils.d.ts +3 -0
  102. package/dist/shared/utils/id.utils.d.ts.map +1 -0
  103. package/dist/shared/utils/id.utils.js +5 -0
  104. package/dist/shared/utils/id.utils.js.map +1 -0
  105. package/dist/supabase.js +1 -1
  106. package/dist/supabase.js.map +1 -1
  107. package/dist/task/local-task-registry.d.ts +27 -0
  108. package/dist/task/local-task-registry.d.ts.map +1 -0
  109. package/dist/task/local-task-registry.js +153 -0
  110. package/dist/task/local-task-registry.js.map +1 -0
  111. package/dist/task/task-manager.d.ts +52 -0
  112. package/dist/task/task-manager.d.ts.map +1 -0
  113. package/dist/task/task-manager.js +217 -0
  114. package/dist/task/task-manager.js.map +1 -0
  115. package/dist/task/task-repo-context.d.ts +95 -0
  116. package/dist/task/task-repo-context.d.ts.map +1 -0
  117. package/dist/task/task-repo-context.js +12 -0
  118. package/dist/task/task-repo-context.js.map +1 -0
  119. package/dist/task/task.api.d.ts +241 -0
  120. package/dist/task/task.api.d.ts.map +1 -0
  121. package/dist/task/task.api.js +351 -0
  122. package/dist/task/task.api.js.map +1 -0
  123. package/dist/task/task.interface.d.ts +56 -0
  124. package/dist/task/task.interface.d.ts.map +1 -0
  125. package/dist/task/task.interface.js +36 -0
  126. package/dist/task/task.interface.js.map +1 -0
  127. package/dist/task/task.utils.d.ts +1 -0
  128. package/dist/task/task.utils.d.ts.map +1 -0
  129. package/dist/task/task.utils.js +2 -0
  130. package/dist/task/task.utils.js.map +1 -0
  131. package/dist/word/word.api.d.ts +5 -5
  132. package/dist/word/word.api.d.ts.map +1 -1
  133. package/dist/word/word.api.js +1 -1
  134. package/dist/word/word.api.js.map +1 -1
  135. package/package.json +10 -3
  136. package/src/auth/auth.api.ts +9 -7
  137. package/src/command/command.api.ts +88 -0
  138. package/src/command/command.interface.ts +17 -0
  139. package/src/core.api.ts +489 -133
  140. package/src/core.interface.ts +3 -1
  141. package/src/core.utils.ts +0 -6
  142. package/src/file/file-manager.ts +1 -1
  143. package/src/file-list/file-list.api.ts +1 -1
  144. package/src/index.ts +22 -1
  145. package/src/list/list.interface.ts +2 -2
  146. package/src/node/node-manager.ts +673 -0
  147. package/src/node/node-task.preset.ts +13 -0
  148. package/src/node/node.api.ts +139 -0
  149. package/src/node/node.interface.ts +40 -0
  150. package/src/node/node.utils.ts +36 -0
  151. package/src/parcel/parcel-manager.ts +1 -1
  152. package/src/question-list/question-list.api.ts +1 -1
  153. package/src/repo/repo-context.utils.ts +111 -0
  154. package/src/repo/repo-manager.ts +217 -0
  155. package/src/repo/repo.api.ts +50 -0
  156. package/src/repo/repo.interface.ts +31 -0
  157. package/src/repo/repo.script-loader.ts +140 -0
  158. package/src/review/review.api.ts +5 -5
  159. package/src/shared/log/create-api-logger.ts +25 -0
  160. package/src/shared/log/log-manager.ts +340 -0
  161. package/src/shared/utils/config-path.utils.ts +104 -0
  162. package/src/shared/utils/error.utils.ts +15 -0
  163. package/src/shared/utils/id.utils.ts +4 -0
  164. package/src/supabase.ts +1 -1
  165. package/src/task/local-task-registry.ts +195 -0
  166. package/src/task/task-manager.ts +312 -0
  167. package/src/task/task-repo-context.ts +103 -0
  168. package/src/task/task.api.ts +429 -0
  169. package/src/task/task.interface.ts +68 -0
  170. package/src/task/task.utils.ts +0 -0
  171. package/src/word/word.api.ts +6 -6
@@ -0,0 +1,139 @@
1
+ import { createTarget, QueryFilter, updateTargetDetails, validateWithSchema } from "../core.api";
2
+ import { generateResponse } from "../core.interface";
3
+ import { createApiLogger } from "../shared/log/log-manager";
4
+ import { z } from "zod";
5
+ import { CategoryNode, Node, NodeDetails, NodeStatus } from "./node.interface";
6
+
7
+ const NODE_STATUS_FIELD = "details->>status" as const;
8
+
9
+ const nodeIdSchema = z.string().trim().min(1);
10
+ const traceIdSchema = z.string().trim().min(1).optional();
11
+
12
+ // ─── Zod schemas ─────────────────────────────────────────────────────────────
13
+
14
+ export const postRegisterNodeSchema = z.object({
15
+ traceId: traceIdSchema,
16
+ });
17
+
18
+ export type PostRegisterNodePayload = z.infer<typeof postRegisterNodeSchema>;
19
+
20
+ export const patchNodeHeartBeatSchema = z.object({
21
+ nodeId: nodeIdSchema,
22
+ traceId: traceIdSchema,
23
+ });
24
+
25
+ export type PatchNodeHeartBeatPayload = z.infer<typeof patchNodeHeartBeatSchema>;
26
+
27
+ export const patchStopNodeSchema = z.object({
28
+ nodeId: nodeIdSchema,
29
+ traceId: traceIdSchema,
30
+ });
31
+
32
+ export type PatchStopNodePayload = z.infer<typeof patchStopNodeSchema>;
33
+
34
+ export const patchChangeNodeStatusSchema = z.object({
35
+ nodeId: nodeIdSchema,
36
+ status: z.nativeEnum(NodeStatus),
37
+ /** When set, UPDATE only if current status matches (optimistic lock). */
38
+ fromStatus: z.nativeEnum(NodeStatus).optional(),
39
+ traceId: traceIdSchema,
40
+ });
41
+
42
+ export type PatchChangeNodeStatusPayload = z.infer<typeof patchChangeNodeStatusSchema>;
43
+
44
+ // ─── Optimistic lock helpers ─────────────────────────────────────────────────
45
+
46
+ function lockOnNodeStatus(status: NodeStatus): QueryFilter[] {
47
+ return [{ field: NODE_STATUS_FIELD, operator: "eq", value: status }];
48
+ }
49
+
50
+ // ─── postRegisterNode ────────────────────────────────────────────────────────
51
+
52
+ export const postRegisterNode = validateWithSchema(
53
+ postRegisterNodeSchema,
54
+ "postRegisterNodeSchema"
55
+ )(async (payload) => {
56
+ return createTarget<Node, PostRegisterNodePayload>({
57
+ payload,
58
+ createFn: () => {
59
+ const details: NodeDetails = {
60
+ manifestVersion: 0,
61
+ status: NodeStatus.READY,
62
+ lastHeartBeat: Date.now(),
63
+ };
64
+ return {
65
+ name: "",
66
+ category: CategoryNode.NODE,
67
+ value: "",
68
+ tagList: [],
69
+ details,
70
+ };
71
+ },
72
+ });
73
+ });
74
+
75
+ // ─── patchNodeHeartBeat ──────────────────────────────────────────────────────
76
+
77
+ export const patchNodeHeartBeat = validateWithSchema(
78
+ patchNodeHeartBeatSchema,
79
+ "patchNodeHeartBeatSchema"
80
+ )(async ({ nodeId }) => {
81
+ const lastHeartBeat = Date.now();
82
+ await updateTargetDetails<Node, NodeDetails>({
83
+ id: nodeId,
84
+ updateFn: (details) => ({
85
+ ...details,
86
+ lastHeartBeat,
87
+ }),
88
+ });
89
+ return generateResponse.success(lastHeartBeat);
90
+ });
91
+
92
+ // ─── patchStopNode ───────────────────────────────────────────────────────────
93
+
94
+ export const patchStopNode = validateWithSchema(
95
+ patchStopNodeSchema,
96
+ "patchStopNodeSchema"
97
+ )(async ({ nodeId }) => {
98
+ const lastHeartBeat = Date.now();
99
+ // TODO 等待任務全部完成才下綫 應該先使用NodeStatus.DRAINING
100
+ await updateTargetDetails<Node, NodeDetails>({
101
+ id: nodeId,
102
+ updateFn: (details) => ({
103
+ ...details,
104
+ lastHeartBeat,
105
+ status: NodeStatus.LOST,
106
+ }),
107
+ });
108
+ return generateResponse.success(lastHeartBeat);
109
+ });
110
+
111
+ // ─── patchChangeNodeStatus ───────────────────────────────────────────────────
112
+
113
+ export const patchChangeNodeStatus = validateWithSchema(
114
+ patchChangeNodeStatusSchema,
115
+ "patchChangeNodeStatusSchema"
116
+ )(async ({ nodeId, status, fromStatus, traceId }) => {
117
+ const logger = createApiLogger("patchChangeNodeStatus", { traceId, nodeId });
118
+
119
+ const data = await updateTargetDetails<Node, NodeDetails>({
120
+ id: nodeId,
121
+ optimisticLockFilterList: fromStatus != null ? lockOnNodeStatus(fromStatus) : [],
122
+ updateFn: (details) => ({
123
+ ...details,
124
+ status,
125
+ lastHeartBeat: Date.now(),
126
+ }),
127
+ });
128
+
129
+ logger.info("节点状态更新成功", {
130
+ topic: "node",
131
+ context: {
132
+ nodeId,
133
+ status,
134
+ fromStatus,
135
+ },
136
+ });
137
+
138
+ return generateResponse.success(data);
139
+ });
@@ -0,0 +1,40 @@
1
+ import { Target } from "../core.interface";
2
+
3
+ export enum NodeStatus {
4
+ /** Registered, not yet in worker loop. */
5
+ READY = "READY",
6
+ /** Worker main loop is running (accepts tasks until shutdown). */
7
+ BUSY = "BUSY",
8
+ /** Heartbeat lost or voluntarily offline; considered unavailable by the scheduler. */
9
+ LOST = "LOST",
10
+ /** TODO Gracefully draining: not accepting new tasks, waiting for in-flight tasks to complete. */
11
+ DRAINING = "DRAINING",
12
+ /** TODO Disabled by an administrator; excluded from scheduling. */
13
+ DISABLED = "DISABLED",
14
+ }
15
+
16
+ export enum CategoryNode {
17
+ NODE = "node",
18
+ }
19
+
20
+ export interface Node extends Target {
21
+ /** Empty */
22
+ name: string;
23
+ /** Empty */
24
+ value: string;
25
+ details: NodeDetails;
26
+ category: CategoryNode;
27
+ }
28
+
29
+ export interface NodeDetails {
30
+ manifestVersion: number;
31
+ status: NodeStatus;
32
+ lastHeartBeat: number;
33
+ };
34
+
35
+ /** 主循环单轮运行时上下文 — 由 start() 创建并向下传递 */
36
+ export interface NodeLoopContext {
37
+ loopTraceId: string;
38
+ nodeId: string;
39
+ }
40
+
@@ -0,0 +1,36 @@
1
+ export const formatTimestamp = (timestamp: number): string => {
2
+ return new Intl.DateTimeFormat("zh-CN", {
3
+ year: "numeric",
4
+ month: "2-digit",
5
+ day: "2-digit",
6
+ hour: "2-digit",
7
+ minute: "2-digit",
8
+ second: "2-digit",
9
+ hour12: false,
10
+ fractionalSecondDigits: 3,
11
+ }).format(timestamp);
12
+ };
13
+
14
+ export const formatRelativeTime = (timestamp: number): string => {
15
+ const now = Date.now();
16
+ const diff = now - timestamp;
17
+
18
+ if (diff < 1000) return "刚刚";
19
+ if (diff < 60000) return `${Math.floor(diff / 1000)}秒前`;
20
+ if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
21
+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
22
+
23
+ return formatTimestamp(timestamp);
24
+ };
25
+
26
+ export const getRandomInterval = (): number => {
27
+ const min = 15 * 1000;
28
+ const max = 1 * 60 * 1000;
29
+ return Math.floor(Math.random() * (max - min + 1)) + min;
30
+ };
31
+
32
+ export const formatHeartbeat = (timestamp: number): string => {
33
+ const absolute = formatTimestamp(timestamp);
34
+ const relative = formatRelativeTime(timestamp);
35
+ return `${absolute} (${relative})`;
36
+ };
@@ -206,4 +206,4 @@ const ParcelManager = {
206
206
  reassembly,
207
207
  };
208
208
 
209
- export default ParcelManager;
209
+ export { ParcelManager };
@@ -9,7 +9,7 @@ export class PostCreateQuestionListValidator extends BaseValidator<PostCreateQue
9
9
  constructor() {
10
10
  super();
11
11
  // Add custom
12
- this.addValidator((val) => {
12
+ this.addCustomValidator((val) => {
13
13
  return true;
14
14
  });
15
15
  }
@@ -0,0 +1,111 @@
1
+ import {
2
+ TASK_REPO_SCRIPT_CATEGORY,
3
+ type TaskRepoContext,
4
+ type TaskRepoScriptDetails,
5
+ type TaskRepoScriptRecord,
6
+ } from "../task/task-repo-context";
7
+
8
+ export { TASK_REPO_SCRIPT_CATEGORY };
9
+
10
+ export interface LoadedRepoContext {
11
+ context: TaskRepoContext;
12
+ /** Cache key segment — typically repo hash or script hash */
13
+ contentHash: string;
14
+ }
15
+
16
+ export function isTaskRepoContext(value: unknown): value is TaskRepoContext {
17
+ if (value == null || typeof value !== "object") {
18
+ return false;
19
+ }
20
+ const record = value as TaskRepoContext;
21
+ return typeof record.taskParamsValidator === "function" && typeof record.taskFn === "function";
22
+ }
23
+
24
+ /**
25
+ * Normalize a dynamically imported module into {@link TaskRepoContext}.
26
+ * Supported shapes:
27
+ * - `export default { taskParamsValidator, taskFn }`
28
+ * - `export { taskParamsValidator, taskFn }`
29
+ * - `export default taskFn` (validator becomes `() => true`)
30
+ */
31
+ export function normalizeRepoContextModule(
32
+ moduleExports: unknown,
33
+ taskTypeKey: string,
34
+ exportName?: string
35
+ ): TaskRepoContext | null {
36
+ if (moduleExports == null) {
37
+ return null;
38
+ }
39
+
40
+ const record = moduleExports as Record<string, unknown>;
41
+ const namedExport =
42
+ exportName != null && exportName !== "" ? record[exportName] : undefined;
43
+ const defaultExport = record.default;
44
+ const candidate = namedExport ?? defaultExport ?? moduleExports;
45
+
46
+ let taskParamsValidator: unknown;
47
+ let taskFn: unknown;
48
+
49
+ if (typeof candidate === "function") {
50
+ taskFn = candidate;
51
+ taskParamsValidator = record.taskParamsValidator;
52
+ } else if (typeof candidate === "object" && candidate != null) {
53
+ const ctx = candidate as Record<string, unknown>;
54
+ taskParamsValidator = ctx.taskParamsValidator;
55
+ taskFn = ctx.taskFn;
56
+ }
57
+
58
+ taskParamsValidator ??= record.taskParamsValidator;
59
+ taskFn ??= record.taskFn;
60
+
61
+ if (typeof taskFn !== "function") {
62
+ return null;
63
+ }
64
+
65
+ if (typeof taskParamsValidator !== "function") {
66
+ taskParamsValidator = () => true;
67
+ }
68
+
69
+ const fn = taskFn as TaskRepoContext["taskFn"];
70
+ if (fn.displayName == null || fn.displayName === "") {
71
+ fn.displayName = taskTypeKey;
72
+ }
73
+ if (fn.taskTypeKey == null || fn.taskTypeKey === "") {
74
+ fn.taskTypeKey = taskTypeKey;
75
+ }
76
+
77
+ return {
78
+ taskParamsValidator: taskParamsValidator as TaskRepoContext["taskParamsValidator"],
79
+ taskFn: fn,
80
+ };
81
+ }
82
+
83
+ export function pickEntryScript(scripts: TaskRepoScriptRecord[]): TaskRepoScriptRecord | null {
84
+ if (scripts.length === 0) {
85
+ return null;
86
+ }
87
+ const entry = scripts.find((script) => script.details.isEntry === true);
88
+ return entry ?? scripts[0];
89
+ }
90
+
91
+ export function getScriptLoadKey(script: TaskRepoScriptRecord): string {
92
+ const { source, modulePath, hash } = script.details;
93
+ if (hash != null && hash !== "") {
94
+ return hash;
95
+ }
96
+ if (source != null && source !== "") {
97
+ return `source:${source.length}:${source.slice(0, 64)}`;
98
+ }
99
+ if (modulePath != null && modulePath !== "") {
100
+ return `path:${modulePath}`;
101
+ }
102
+ return script.id;
103
+ }
104
+
105
+ export function assertScriptLoadable(
106
+ details: TaskRepoScriptDetails
107
+ ): details is TaskRepoScriptDetails & ({ source: string } | { modulePath: string }) {
108
+ const hasSource = details.source != null && details.source.trim() !== "";
109
+ const hasModulePath = details.modulePath != null && details.modulePath.trim() !== "";
110
+ return hasSource || hasModulePath;
111
+ }
@@ -0,0 +1,217 @@
1
+ import { getPossibleTarget } from "../core.api";
2
+ import { SupabaseInitializer } from "../supabase";
3
+ import { LoggerWithContext } from "../shared/log/log-manager";
4
+ import type { TaskRepoContext, TaskRepoScriptRecord } from "../task/task-repo-context";
5
+ import { TASK_REPO_SCRIPT_CATEGORY } from "../task/task-repo-context";
6
+ import {
7
+ assertScriptLoadable,
8
+ isTaskRepoContext,
9
+ pickEntryScript,
10
+ } from "./repo-context.utils";
11
+ import { CategoryRepo, Repo } from "./repo.interface";
12
+ import {
13
+ clearRepoScriptModuleCache,
14
+ loadRepoContextFromScript,
15
+ loadRepoContextFromUrl,
16
+ } from "./repo.script-loader";
17
+
18
+ const supabase = SupabaseInitializer.getInstance();
19
+
20
+ type LocalRepoEntry =
21
+ | { kind: "context"; context: TaskRepoContext }
22
+ | { kind: "modulePath"; modulePath: string; exportName?: string };
23
+
24
+ const localRepoRegistry = new Map<string, LocalRepoEntry>();
25
+ const remoteContextCache = new Map<string, TaskRepoContext>();
26
+
27
+ export interface GetRepoContextParams {
28
+ logger: LoggerWithContext;
29
+ /** Task type key (`task.value`) — matches {@link Repo.value} for remote lookup; local registry key */
30
+ taskTypeKey: string;
31
+ }
32
+
33
+ export interface GetRepoContextResult<T extends TaskRepoContext = TaskRepoContext> {
34
+ context: T | null;
35
+ /** Present when `context` is null — import / DB / format failure at repo layer */
36
+ error?: string;
37
+ }
38
+
39
+ function buildRemoteCacheKey(taskTypeKey: string, contentHash: string): string {
40
+ return `${taskTypeKey}@${contentHash}`;
41
+ }
42
+
43
+ async function fetchRemoteRepo(taskTypeKey: string): Promise<Repo | null> {
44
+ const { data } = await getPossibleTarget({
45
+ filterList: [
46
+ { field: "category", operator: "eq", value: CategoryRepo.REPO },
47
+ { field: "value", operator: "eq", value: taskTypeKey },
48
+ ],
49
+ });
50
+ return (data as Repo | null) ?? null;
51
+ }
52
+
53
+ async function fetchRemoteScripts(taskTypeKey: string): Promise<TaskRepoScriptRecord[]> {
54
+ const { data, error } = await supabase.client
55
+ .from("target")
56
+ .select("id, value, details")
57
+ .eq("category", TASK_REPO_SCRIPT_CATEGORY)
58
+ .eq("value", taskTypeKey);
59
+
60
+ if (error) {
61
+ throw error;
62
+ }
63
+
64
+ return (data ?? []) as TaskRepoScriptRecord[];
65
+ }
66
+
67
+ async function loadLocalEntry(
68
+ logger: LoggerWithContext,
69
+ entry: LocalRepoEntry,
70
+ taskTypeKey: string
71
+ ): Promise<TaskRepoContext | null> {
72
+ if (entry.kind === "context") {
73
+ return entry.context;
74
+ }
75
+
76
+ const loaded = await loadRepoContextFromScript({
77
+ logger,
78
+ script: {
79
+ id: `local:${taskTypeKey}`,
80
+ value: taskTypeKey,
81
+ details: {
82
+ manifestVersion: 0,
83
+ modulePath: entry.modulePath,
84
+ exportName: entry.exportName,
85
+ isEntry: true,
86
+ },
87
+ },
88
+ taskTypeKey,
89
+ });
90
+ return loaded?.context ?? null;
91
+ }
92
+
93
+ async function loadRemoteRepoContext(
94
+ logger: LoggerWithContext,
95
+ taskTypeKey: string
96
+ ): Promise<GetRepoContextResult> {
97
+ logger.info("從 Supabase 加載 Repo", { topic: "repo", context: { taskTypeKey } });
98
+
99
+ const remoteRepo = await fetchRemoteRepo(taskTypeKey);
100
+ if (remoteRepo == null) {
101
+ const error = `Supabase 未找到 Repo (value=${taskTypeKey})`;
102
+ logger.warn(error, { topic: "repo", context: { taskTypeKey } });
103
+ return { context: null, error };
104
+ }
105
+
106
+ const repoUrl = remoteRepo.details?.url?.trim() ?? "";
107
+ const repoHash = remoteRepo.details?.hash?.trim() ?? repoUrl;
108
+ const cacheKey = buildRemoteCacheKey(taskTypeKey, repoHash);
109
+ const cached = remoteContextCache.get(cacheKey);
110
+ if (cached != null) {
111
+ logger.info("命中遠程 Repo 上下文緩存", { topic: "repo", context: { cacheKey } });
112
+ return { context: cached };
113
+ }
114
+
115
+ const scripts = await fetchRemoteScripts(taskTypeKey);
116
+ const entryScript = pickEntryScript(scripts);
117
+
118
+ let loaded =
119
+ entryScript != null && assertScriptLoadable(entryScript.details)
120
+ ? await loadRepoContextFromScript({ logger, script: entryScript, taskTypeKey })
121
+ : null;
122
+
123
+ if (loaded == null && repoUrl !== "") {
124
+ logger.info("未找到 script 行,嘗試從 Repo.details.url 加載", {
125
+ topic: "repo",
126
+ context: { taskTypeKey, url: repoUrl },
127
+ });
128
+ loaded = await loadRepoContextFromUrl({ logger, url: repoUrl, taskTypeKey });
129
+ }
130
+
131
+ if (loaded == null) {
132
+ const error = `無法從 Repo 加載 TaskRepoContext (hasUrl=${repoUrl !== ""}, scriptCount=${scripts.length})`;
133
+ logger.warn(error, {
134
+ topic: "repo",
135
+ context: { taskTypeKey, hasUrl: repoUrl !== "", scriptCount: scripts.length },
136
+ });
137
+ return { context: null, error };
138
+ }
139
+
140
+ remoteContextCache.set(cacheKey, loaded.context);
141
+ return { context: loaded.context };
142
+ }
143
+
144
+ const getRepoContext = async <RepoContext extends TaskRepoContext>({
145
+ logger,
146
+ taskTypeKey,
147
+ }: GetRepoContextParams): Promise<GetRepoContextResult<RepoContext>> => {
148
+ const localEntry = localRepoRegistry.get(taskTypeKey);
149
+ if (localEntry != null) {
150
+ logger.info("使用本地註冊的 Repo", { topic: "repo", context: { taskTypeKey } });
151
+ const context = await loadLocalEntry(logger, localEntry, taskTypeKey);
152
+ if (context != null && isTaskRepoContext(context)) {
153
+ return { context: context as RepoContext };
154
+ }
155
+ const error = "本地 Repo 模組加載失敗或未導出有效的 TaskRepoContext";
156
+ logger.warn(error, { topic: "repo", context: { taskTypeKey } });
157
+ return { context: null, error };
158
+ }
159
+
160
+ try {
161
+ const result = await loadRemoteRepoContext(logger, taskTypeKey);
162
+ if (result.context != null && isTaskRepoContext(result.context)) {
163
+ return { context: result.context as RepoContext };
164
+ }
165
+ return {
166
+ context: null,
167
+ error: result.error ?? "遠程 Repo 上下文無效",
168
+ };
169
+ } catch (error) {
170
+ const message = error instanceof Error ? error.message : String(error);
171
+ logger.error("從 Supabase 加載 Repo 失敗", {
172
+ topic: "repo",
173
+ context: { taskTypeKey, error: message },
174
+ });
175
+ return { context: null, error: message };
176
+ }
177
+ };
178
+
179
+ /** Register an in-process TaskRepoContext (highest priority — no Supabase fetch). */
180
+ function registerLocalRepoContext(taskTypeKey: string, context: TaskRepoContext): void {
181
+ if (!isTaskRepoContext(context)) {
182
+ throw new Error("[RepoManager] Invalid TaskRepoContext");
183
+ }
184
+ localRepoRegistry.set(taskTypeKey, { kind: "context", context });
185
+ }
186
+
187
+ /** Register a local ESM module path; loaded via dynamic import when the task runs. */
188
+ function registerLocalModule(taskTypeKey: string, modulePath: string, exportName?: string): void {
189
+ if (modulePath.trim() === "") {
190
+ throw new Error("[RepoManager] modulePath must not be empty");
191
+ }
192
+ localRepoRegistry.set(taskTypeKey, { kind: "modulePath", modulePath, exportName });
193
+ }
194
+
195
+ function unregisterLocalRepo(taskTypeKey: string): void {
196
+ localRepoRegistry.delete(taskTypeKey);
197
+ }
198
+
199
+ function getRegisteredLocalTaskTypeKeys(): string[] {
200
+ return [...localRepoRegistry.keys()];
201
+ }
202
+
203
+ function clearRemoteContextCache(): void {
204
+ remoteContextCache.clear();
205
+ }
206
+
207
+ const RepoManager = {
208
+ getRepoContext,
209
+ registerLocalRepoContext,
210
+ registerLocalModule,
211
+ unregisterLocalRepo,
212
+ getRegisteredLocalTaskTypeKeys,
213
+ clearRemoteContextCache,
214
+ clearRepoScriptModuleCache,
215
+ };
216
+
217
+ export { RepoManager };
@@ -0,0 +1,50 @@
1
+ import { scanTargetList, validateWithSchema } from "../core.api";
2
+ import { generateResponse, SupabaseResponse } from "../core.interface";
3
+ import { z } from "zod";
4
+ import { CategoryRepo, Repo } from "./repo.interface";
5
+
6
+ const REPO_USAGE_FIELD = "details->>usage" as const;
7
+
8
+ export const getScanRemoteRepoValuesSchema = z.object({
9
+ usage: z.string().trim().min(1),
10
+ });
11
+
12
+ export type GetScanRemoteRepoValuesPayload = z.infer<typeof getScanRemoteRepoValuesSchema>;
13
+
14
+ /**
15
+ * Scan `Repo.value` keys for `category=repo` with matching `details.usage`.
16
+ * Returns `{ data: string[] }` on success; validation and DB failures use `{ error }` (never throws).
17
+ */
18
+ export const getScanRemoteRepoValues = async (
19
+ payload: GetScanRemoteRepoValuesPayload
20
+ ): Promise<SupabaseResponse<string[]>> => {
21
+ try {
22
+ return await getScanRemoteRepoValuesValidated(payload);
23
+ } catch (error) {
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ return generateResponse.error(message) as SupabaseResponse<string[]>;
26
+ }
27
+ };
28
+
29
+ const getScanRemoteRepoValuesValidated = validateWithSchema(
30
+ getScanRemoteRepoValuesSchema,
31
+ "getScanRemoteRepoValuesSchema"
32
+ )(async ({ usage }): Promise<SupabaseResponse<string[]>> => {
33
+ try {
34
+ const { data } = await scanTargetList<Repo>({
35
+ category: CategoryRepo.REPO,
36
+ selectFields: "value",
37
+ orderBy: { field: "value", ascending: true },
38
+ filterList: [{ field: REPO_USAGE_FIELD, operator: "eq", value: usage }],
39
+ });
40
+
41
+ const values = (data ?? [])
42
+ .map((row) => row.value?.trim())
43
+ .filter((value): value is string => value != null && value !== "");
44
+
45
+ return generateResponse.success([...new Set(values)]);
46
+ } catch (error) {
47
+ const message = error instanceof Error ? error.message : String(error);
48
+ return generateResponse.error(message) as SupabaseResponse<string[]>;
49
+ }
50
+ });
@@ -0,0 +1,31 @@
1
+ import { Target } from "../core.interface";
2
+
3
+ export enum CategoryRepo {
4
+ /** Project */
5
+ REPO = "repo",
6
+ }
7
+
8
+ /** `Repo.details.usage` for task worker remote discovery ({@link registerTasks}). */
9
+ export const TASK_REPO_USAGE = "task";
10
+
11
+ export interface Repo extends Target {
12
+ /** Human readable name */
13
+ name: string;
14
+ /** Unique key, consumers use this to determine which repo to use */
15
+ value: string;
16
+ details: RepoDetails;
17
+ category: CategoryRepo;
18
+ }
19
+
20
+ export interface RepoDetails {
21
+ manifestVersion: number;
22
+ /**
23
+ * Business usage partition for discovery and load (caller-defined string, e.g. `"task"`).
24
+ * Used by {@link getScanRemoteRepoValues} to narrow scan scope; validity is the caller's responsibility.
25
+ */
26
+ usage: string;
27
+ /** Repo entry module URL or filesystem path — used to dynamic-import TaskRepoContext. */
28
+ url: string;
29
+ hash: string;
30
+ }
31
+