ima2-gen 1.1.21 → 1.1.22

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 (208) hide show
  1. package/README.md +30 -4
  2. package/bin/ima2.js +14 -4
  3. package/bin/lib/platform.js +34 -5
  4. package/docs/README.ko.md +31 -0
  5. package/lib/agentQueueWorker.js +6 -0
  6. package/lib/agentRuntime.js +3 -2
  7. package/lib/atomicWrite.js +14 -0
  8. package/lib/grokProxyLauncher.js +5 -3
  9. package/lib/inflight.js +1 -1
  10. package/lib/oauthLauncher.js +5 -0
  11. package/lib/videoFrameExtract.js +3 -3
  12. package/package.json +5 -7
  13. package/routes/edit.js +2 -1
  14. package/routes/generate.js +4 -3
  15. package/routes/health.js +4 -3
  16. package/routes/multimode.js +2 -1
  17. package/routes/video.js +4 -2
  18. package/server.js +29 -2
  19. package/ui/dist/.vite/manifest.json +12 -12
  20. package/ui/dist/assets/{AgentWorkspace-B_hq9CLg.js → AgentWorkspace-COxQ5TjU.js} +1 -1
  21. package/ui/dist/assets/{CardNewsWorkspace-wD12J7qk.js → CardNewsWorkspace-B0OkcuVz.js} +1 -1
  22. package/ui/dist/assets/{NodeCanvas-CI_wuPMf.js → NodeCanvas-BSsclEBh.js} +1 -1
  23. package/ui/dist/assets/{PromptBuilderPanel-CUTujJUV.js → PromptBuilderPanel-DpC9A5Rz.js} +1 -1
  24. package/ui/dist/assets/{PromptImportDialog-CUi66jPK.js → PromptImportDialog-CVwT0rLd.js} +2 -2
  25. package/ui/dist/assets/{PromptImportDiscoverySection-Cm3vrjY4.js → PromptImportDiscoverySection-BDCkRCRs.js} +1 -1
  26. package/ui/dist/assets/{PromptImportFolderSection-DOtWTD9n.js → PromptImportFolderSection-QoKbZD83.js} +1 -1
  27. package/ui/dist/assets/{PromptLibraryPanel-BMjQegRa.js → PromptLibraryPanel-BhFgeKnY.js} +2 -2
  28. package/ui/dist/assets/SettingsWorkspace-CfjrlH5R.js +1 -0
  29. package/ui/dist/assets/index-C-mur7pa.css +1 -0
  30. package/ui/dist/assets/index-CCP5nUOj.js +42 -0
  31. package/ui/dist/assets/{index-31uVIdt4.js → index-Cxhzi3bs.js} +1 -1
  32. package/ui/dist/index.html +2 -2
  33. package/bin/commands/annotate.ts +0 -119
  34. package/bin/commands/cancel.ts +0 -48
  35. package/bin/commands/canvas-versions.ts +0 -80
  36. package/bin/commands/capabilities.ts +0 -110
  37. package/bin/commands/cardnews.ts +0 -249
  38. package/bin/commands/comfy.ts +0 -54
  39. package/bin/commands/config.ts +0 -186
  40. package/bin/commands/defaults.ts +0 -192
  41. package/bin/commands/doctor.ts +0 -202
  42. package/bin/commands/edit.ts +0 -150
  43. package/bin/commands/gen.ts +0 -214
  44. package/bin/commands/grok.ts +0 -90
  45. package/bin/commands/history.ts +0 -146
  46. package/bin/commands/ls.ts +0 -64
  47. package/bin/commands/metadata.ts +0 -39
  48. package/bin/commands/multimode.ts +0 -196
  49. package/bin/commands/node.ts +0 -166
  50. package/bin/commands/observability.ts +0 -176
  51. package/bin/commands/ping.ts +0 -31
  52. package/bin/commands/prompt-sub/build.ts +0 -101
  53. package/bin/commands/prompt.ts +0 -492
  54. package/bin/commands/ps.ts +0 -81
  55. package/bin/commands/session.ts +0 -266
  56. package/bin/commands/show.ts +0 -72
  57. package/bin/commands/skill.ts +0 -70
  58. package/bin/commands/video.ts +0 -442
  59. package/bin/ima2.ts +0 -430
  60. package/bin/lib/args.ts +0 -92
  61. package/bin/lib/browser-id.ts +0 -16
  62. package/bin/lib/client.ts +0 -122
  63. package/bin/lib/config-store.ts +0 -120
  64. package/bin/lib/destructive-confirm.ts +0 -19
  65. package/bin/lib/doctor-checks.ts +0 -91
  66. package/bin/lib/error-hints.ts +0 -23
  67. package/bin/lib/files.ts +0 -39
  68. package/bin/lib/output.ts +0 -73
  69. package/bin/lib/platform.ts +0 -99
  70. package/bin/lib/recover-output.ts +0 -139
  71. package/bin/lib/sse.ts +0 -73
  72. package/bin/lib/star-prompt.ts +0 -97
  73. package/bin/lib/storage-doctor.ts +0 -39
  74. package/bin/lib/ui-build.ts +0 -85
  75. package/config.ts +0 -354
  76. package/lib/agentCommandParser.ts +0 -69
  77. package/lib/agentGenerationPlanner.ts +0 -273
  78. package/lib/agentQuestionResponder.ts +0 -266
  79. package/lib/agentQueueStore.ts +0 -270
  80. package/lib/agentQueueWorker.ts +0 -89
  81. package/lib/agentRuntime.ts +0 -604
  82. package/lib/agentSettings.ts +0 -72
  83. package/lib/agentStore.ts +0 -422
  84. package/lib/agentStoreRows.ts +0 -136
  85. package/lib/agentTypes.ts +0 -154
  86. package/lib/apiCachePolicy.ts +0 -11
  87. package/lib/assetLifecycle.ts +0 -146
  88. package/lib/canvasVersionStore.ts +0 -223
  89. package/lib/capabilities.ts +0 -126
  90. package/lib/cardNewsGenerator.ts +0 -271
  91. package/lib/cardNewsJobStore.ts +0 -142
  92. package/lib/cardNewsManifestStore.ts +0 -154
  93. package/lib/cardNewsPlanner.ts +0 -236
  94. package/lib/cardNewsPlannerClient.ts +0 -155
  95. package/lib/cardNewsPlannerPrompt.ts +0 -62
  96. package/lib/cardNewsPlannerSchema.ts +0 -321
  97. package/lib/cardNewsRoleTemplateStore.ts +0 -47
  98. package/lib/cardNewsTemplateStore.ts +0 -252
  99. package/lib/codexDetect.ts +0 -71
  100. package/lib/comfyBridge.ts +0 -235
  101. package/lib/composerSnapshot.ts +0 -33
  102. package/lib/configKeys.ts +0 -62
  103. package/lib/db.ts +0 -295
  104. package/lib/errInfo.ts +0 -43
  105. package/lib/errorClassify.ts +0 -100
  106. package/lib/generationCancel.ts +0 -28
  107. package/lib/generationErrors.ts +0 -238
  108. package/lib/grokImageAdapter.ts +0 -513
  109. package/lib/grokMultimodeAdapter.ts +0 -84
  110. package/lib/grokProxyLauncher.ts +0 -153
  111. package/lib/grokRuntime.ts +0 -23
  112. package/lib/grokSizeMapper.ts +0 -71
  113. package/lib/grokVideoAdapter.ts +0 -458
  114. package/lib/grokVideoCanvas.ts +0 -26
  115. package/lib/grokVideoDownload.ts +0 -59
  116. package/lib/grokVideoPlannerPrompt.ts +0 -67
  117. package/lib/historyIndex.ts +0 -51
  118. package/lib/historyList.ts +0 -181
  119. package/lib/imageMetadata.ts +0 -113
  120. package/lib/imageMetadataStore.ts +0 -67
  121. package/lib/imageModels.ts +0 -165
  122. package/lib/inflight.ts +0 -281
  123. package/lib/localImportStore.ts +0 -114
  124. package/lib/logger.ts +0 -161
  125. package/lib/nodeStore.ts +0 -91
  126. package/lib/oauthLauncher.ts +0 -94
  127. package/lib/oauthNormalize.ts +0 -30
  128. package/lib/oauthProxy/errors.ts +0 -128
  129. package/lib/oauthProxy/generators.ts +0 -494
  130. package/lib/oauthProxy/index.ts +0 -28
  131. package/lib/oauthProxy/prompts.ts +0 -123
  132. package/lib/oauthProxy/references.ts +0 -45
  133. package/lib/oauthProxy/runtime.ts +0 -115
  134. package/lib/oauthProxy/streams.ts +0 -232
  135. package/lib/oauthProxy/types.ts +0 -9
  136. package/lib/oauthProxy.ts +0 -3
  137. package/lib/openDirectory.ts +0 -47
  138. package/lib/pngInfo.ts +0 -26
  139. package/lib/promptBuilder/attachments.ts +0 -74
  140. package/lib/promptBuilder/client.ts +0 -130
  141. package/lib/promptBuilder/constants.ts +0 -9
  142. package/lib/promptBuilder/context.ts +0 -36
  143. package/lib/promptBuilder/errors.ts +0 -12
  144. package/lib/promptBuilder/requestSchema.ts +0 -56
  145. package/lib/promptBuilder/responseParser.ts +0 -219
  146. package/lib/promptBuilder/systemPrompt.ts +0 -135
  147. package/lib/promptBuilder/transport.ts +0 -94
  148. package/lib/promptBuilder/types.ts +0 -109
  149. package/lib/promptImport/curatedSources.ts +0 -141
  150. package/lib/promptImport/discoveryRegistry.ts +0 -329
  151. package/lib/promptImport/errors.ts +0 -18
  152. package/lib/promptImport/githubDiscovery.ts +0 -309
  153. package/lib/promptImport/githubFolder.ts +0 -397
  154. package/lib/promptImport/githubSource.ts +0 -257
  155. package/lib/promptImport/gptImageHints.ts +0 -70
  156. package/lib/promptImport/parsePromptCandidates.ts +0 -179
  157. package/lib/promptImport/promptIndex.ts +0 -326
  158. package/lib/promptImport/rankPromptCandidates.ts +0 -65
  159. package/lib/promptImport/types.ts +0 -103
  160. package/lib/promptSafetyPolicy.ts +0 -5
  161. package/lib/providerOptions.ts +0 -56
  162. package/lib/referenceImageCompress.ts +0 -84
  163. package/lib/refs.ts +0 -133
  164. package/lib/requestLogger.ts +0 -49
  165. package/lib/responsesDoctor.ts +0 -456
  166. package/lib/responsesErrors.ts +0 -83
  167. package/lib/responsesFallback.ts +0 -114
  168. package/lib/responsesImageAdapter.ts +0 -466
  169. package/lib/responsesParse.ts +0 -452
  170. package/lib/responsesTools.ts +0 -28
  171. package/lib/runtimeContext.ts +0 -146
  172. package/lib/runtimePorts.ts +0 -105
  173. package/lib/sessionStore.ts +0 -308
  174. package/lib/storageMigration.ts +0 -310
  175. package/lib/styleSheet.ts +0 -139
  176. package/lib/systemTrash.ts +0 -20
  177. package/lib/videoContinuity.ts +0 -180
  178. package/lib/videoFrameExtract.ts +0 -78
  179. package/lib/videoSeriesChain.ts +0 -29
  180. package/lib/visibleTextLanguagePolicy.ts +0 -7
  181. package/routes/agent.ts +0 -308
  182. package/routes/annotations.ts +0 -118
  183. package/routes/canvasVersions.ts +0 -69
  184. package/routes/capabilities.ts +0 -18
  185. package/routes/cardNews.ts +0 -211
  186. package/routes/comfy.ts +0 -43
  187. package/routes/edit.ts +0 -352
  188. package/routes/generate.ts +0 -492
  189. package/routes/grok.ts +0 -24
  190. package/routes/health.ts +0 -123
  191. package/routes/history.ts +0 -221
  192. package/routes/imageImport.ts +0 -37
  193. package/routes/index.ts +0 -52
  194. package/routes/metadata.ts +0 -77
  195. package/routes/multimode.ts +0 -499
  196. package/routes/nodes.ts +0 -578
  197. package/routes/promptBuilder.ts +0 -37
  198. package/routes/promptImport.ts +0 -379
  199. package/routes/prompts.ts +0 -428
  200. package/routes/quota.ts +0 -89
  201. package/routes/sessions.ts +0 -317
  202. package/routes/storage.ts +0 -47
  203. package/routes/video.ts +0 -300
  204. package/routes/videoExtended.ts +0 -284
  205. package/server.ts +0 -293
  206. package/ui/dist/assets/SettingsWorkspace-PiaVnsdA.js +0 -1
  207. package/ui/dist/assets/index-CjgnNtgt.css +0 -1
  208. package/ui/dist/assets/index-Da2s4_-5.js +0 -36
@@ -1,257 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { promptImportError } from "./errors.js";
3
- import type { GitHubFileSource, PromptImportLimits } from "./types.js";
4
-
5
- import { errInfo } from "../errInfo.js";
6
- const ALLOWED_HOSTS = new Set(["github.com", "raw.githubusercontent.com"]);
7
- const SUPPORTED_EXTENSIONS = new Set(["md", "markdown", "txt"]);
8
- const OWNER_REPO_RE = /^[A-Za-z0-9_.-]+$/;
9
-
10
- function safeDecode(value: string): string {
11
- try {
12
- return decodeURIComponent(value);
13
- } catch {
14
- throw promptImportError("INVALID_GITHUB_SOURCE", "Invalid encoded GitHub path");
15
- }
16
- }
17
-
18
- function assertCleanPath(path: string): string {
19
- const lower = path.toLowerCase();
20
- if (path.includes("\0") || lower.includes("%00")) {
21
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub path contains a null byte");
22
- }
23
- if (/%2f|%5c/i.test(path)) {
24
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub path contains an encoded slash");
25
- }
26
- const decoded = safeDecode(path);
27
- if (decoded.includes("\\") || decoded.split("/").includes("..")) {
28
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub path traversal is not allowed");
29
- }
30
- return decoded.replace(/^\/+/, "");
31
- }
32
-
33
- function extensionForPath(path: string): string {
34
- const match = /\.([A-Za-z0-9]+)$/.exec(path);
35
- return match?.[1]?.toLowerCase() ?? "";
36
- }
37
-
38
- function assertSupportedFilePath(path: string): string {
39
- const ext = extensionForPath(path);
40
- if (!ext) {
41
- throw promptImportError("FOLDER_IMPORT_DEFERRED", "Folder import is planned for a later version", 422);
42
- }
43
- if (!SUPPORTED_EXTENSIONS.has(ext)) {
44
- throw promptImportError("UNSUPPORTED_EXTENSION", "Only .md, .markdown, and .txt files are supported");
45
- }
46
- return ext;
47
- }
48
-
49
- function assertOwnerRepo(owner: string | undefined, repo: string | undefined): void {
50
- if (!OWNER_REPO_RE.test(owner || "") || !OWNER_REPO_RE.test(repo || "")) {
51
- throw promptImportError("INVALID_GITHUB_SOURCE", "Invalid GitHub owner or repository");
52
- }
53
- }
54
-
55
- function normalizeUrlInput(input: string): GitHubFileSource | null {
56
- let url;
57
- try {
58
- url = new URL(input);
59
- } catch {
60
- return null;
61
- }
62
- if (!["http:", "https:"].includes(url.protocol)) {
63
- throw promptImportError("INVALID_GITHUB_SOURCE", "Only http(s) GitHub URLs are supported");
64
- }
65
- if (!ALLOWED_HOSTS.has(url.hostname)) {
66
- throw promptImportError("INVALID_GITHUB_SOURCE", "Only GitHub file URLs are supported");
67
- }
68
-
69
- const parts = url.pathname.split("/").filter(Boolean);
70
- if (url.hostname === "github.com") {
71
- const [owner, repo, marker, ref, ...pathParts] = parts;
72
- assertOwnerRepo(owner, repo);
73
- if (marker !== "blob") {
74
- throw promptImportError("FOLDER_IMPORT_DEFERRED", "Only GitHub file URLs are supported in PR1", 422);
75
- }
76
- if (!ref || pathParts.length === 0) {
77
- throw promptImportError("FOLDER_IMPORT_DEFERRED", "Folder import is planned for a later version", 422);
78
- }
79
- const path = assertCleanPath(pathParts.join("/"));
80
- const ext = assertSupportedFilePath(path);
81
- return {
82
- kind: "github",
83
- owner,
84
- repo,
85
- ref: safeDecode(ref),
86
- path,
87
- extension: ext,
88
- htmlUrl: url.toString(),
89
- rawUrl: `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(safeDecode(ref))}/${path}`,
90
- tags: ["github", `repo:${owner}/${repo}`, `ref:${safeDecode(ref)}`, `file:${path.split("/").pop()}`, `ext:${ext}`],
91
- };
92
- }
93
-
94
- const [owner, repo, ref, ...pathParts] = parts;
95
- assertOwnerRepo(owner, repo);
96
- if (!ref || pathParts.length === 0) {
97
- throw promptImportError("FOLDER_IMPORT_DEFERRED", "Folder import is planned for a later version", 422);
98
- }
99
- const path = assertCleanPath(pathParts.join("/"));
100
- const ext = assertSupportedFilePath(path);
101
- return {
102
- kind: "github",
103
- owner,
104
- repo,
105
- ref: safeDecode(ref),
106
- path,
107
- extension: ext,
108
- htmlUrl: `https://github.com/${owner}/${repo}/blob/${safeDecode(ref)}/${path}`,
109
- rawUrl: url.toString(),
110
- tags: ["github", `repo:${owner}/${repo}`, `ref:${safeDecode(ref)}`, `file:${path.split("/").pop()}`, `ext:${ext}`],
111
- };
112
- }
113
-
114
- function normalizeShorthand(input: string): GitHubFileSource {
115
- const match = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:@([^:]+))?:(.+)$/.exec(input);
116
- if (!match) {
117
- throw promptImportError("INVALID_GITHUB_SOURCE", "Enter a GitHub file URL or owner/repo:path");
118
- }
119
- const [, owner, repo, rawRef, rawPath] = match;
120
- assertOwnerRepo(owner, repo);
121
- const ref = rawRef ? safeDecode(rawRef.trim()) : "main";
122
- if (ref.includes("/")) {
123
- throw promptImportError("AMBIGUOUS_GITHUB_REF", "Branches with slashes need GitHub API folder support planned for PR3");
124
- }
125
- const path = assertCleanPath(rawPath.trim());
126
- const ext = assertSupportedFilePath(path);
127
- return {
128
- kind: "github",
129
- owner,
130
- repo,
131
- ref,
132
- path,
133
- extension: ext,
134
- htmlUrl: `https://github.com/${owner}/${repo}/blob/${ref}/${path}`,
135
- rawUrl: `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(ref)}/${path}`,
136
- tags: ["github", `repo:${owner}/${repo}`, `ref:${ref}`, `file:${path.split("/").pop()}`, `ext:${ext}`],
137
- };
138
- }
139
-
140
- interface BuildRawSourceInput {
141
- owner: string;
142
- repo: string;
143
- ref?: string;
144
- path: string;
145
- }
146
-
147
- export function buildGitHubRawFileSource({ owner, repo, ref = "main", path }: BuildRawSourceInput): GitHubFileSource {
148
- assertOwnerRepo(owner, repo);
149
- const cleanRef = safeDecode(String(ref || "main").trim());
150
- if (!cleanRef || cleanRef.includes("/")) {
151
- throw promptImportError("AMBIGUOUS_GITHUB_REF", "Branches with slashes need GitHub API folder support planned for PR3");
152
- }
153
- const cleanPath = assertCleanPath(String(path || "").trim());
154
- const ext = assertSupportedFilePath(cleanPath);
155
- return {
156
- kind: "github",
157
- owner,
158
- repo,
159
- ref: cleanRef,
160
- path: cleanPath,
161
- extension: ext,
162
- htmlUrl: `https://github.com/${owner}/${repo}/blob/${cleanRef}/${cleanPath}`,
163
- rawUrl: `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(cleanRef)}/${cleanPath}`,
164
- tags: ["github", `repo:${owner}/${repo}`, `ref:${cleanRef}`, `file:${cleanPath.split("/").pop()}`, `ext:${ext}`],
165
- };
166
- }
167
-
168
- function validateFinalFetchUrl(rawUrl: string): void {
169
- let url;
170
- try {
171
- url = new URL(rawUrl);
172
- } catch {
173
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub fetch returned an invalid final URL");
174
- }
175
- if (!["http:", "https:"].includes(url.protocol)) {
176
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub fetch returned an unsupported protocol");
177
- }
178
- if (!ALLOWED_HOSTS.has(url.hostname)) {
179
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub fetch redirected to an unsupported host");
180
- }
181
- const parts = url.pathname.split("/").filter(Boolean);
182
- if (url.hostname === "github.com") {
183
- const marker = parts[2];
184
- if (parts.length < 5 || marker !== "blob") {
185
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub fetch redirected to a non-file page");
186
- }
187
- const finalPath = assertCleanPath(parts.slice(4).join("/"));
188
- assertSupportedFilePath(finalPath);
189
- return;
190
- }
191
- if (parts.length < 4) {
192
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub fetch returned a non-file path");
193
- }
194
- const finalPath = assertCleanPath(parts.slice(3).join("/"));
195
- assertSupportedFilePath(finalPath);
196
- }
197
-
198
- export function normalizeGitHubSource(input: unknown): GitHubFileSource {
199
- const trimmed = typeof input === "string" ? input.trim() : "";
200
- if (!trimmed) {
201
- throw promptImportError("INVALID_GITHUB_SOURCE", "GitHub source is required");
202
- }
203
- return normalizeUrlInput(trimmed) ?? normalizeShorthand(trimmed);
204
- }
205
-
206
- interface GitHubFetchResult {
207
- text: string;
208
- finalUrl: string;
209
- etag: string | null;
210
- sizeBytes: number;
211
- contentHash: string;
212
- }
213
-
214
- export async function fetchGitHubSource(source: GitHubFileSource, limits: PromptImportLimits): Promise<GitHubFetchResult> {
215
- const controller = new AbortController();
216
- const timer = setTimeout(() => controller.abort(), limits.fetchTimeoutMs);
217
- try {
218
- const response = await fetch(source.rawUrl, { signal: controller.signal });
219
- validateFinalFetchUrl(response.url);
220
- if (!response.ok) {
221
- throw promptImportError("INVALID_GITHUB_SOURCE", `GitHub file fetch failed with ${response.status}`, 422);
222
- }
223
- const contentLength = Number(response.headers.get("content-length") || 0);
224
- if (contentLength > limits.maxFileBytesForPreview) {
225
- throw promptImportError("REMOTE_FILE_TOO_LARGE", "Remote file is too large", 413);
226
- }
227
- const buffer = await response.arrayBuffer();
228
- if (buffer.byteLength > limits.maxFileBytesForPreview) {
229
- throw promptImportError("REMOTE_FILE_TOO_LARGE", "Remote file is too large", 413);
230
- }
231
- const text = new TextDecoder("utf-8", { fatal: false }).decode(buffer);
232
- return {
233
- text,
234
- finalUrl: response.url,
235
- etag: response.headers.get("etag"),
236
- sizeBytes: buffer.byteLength,
237
- contentHash: createHash("sha256").update(Buffer.from(buffer)).digest("hex"),
238
- };
239
- } catch (error) {
240
- const err = errInfo(error);
241
- if (err.name === "AbortError") {
242
- throw promptImportError("REMOTE_FETCH_TIMEOUT", "GitHub fetch timed out", 504);
243
- }
244
- throw error;
245
- } finally {
246
- clearTimeout(timer);
247
- }
248
- }
249
-
250
- export async function fetchGitHubSourceText(source: GitHubFileSource, limits: PromptImportLimits): Promise<string> {
251
- const result = await fetchGitHubSource(source, limits);
252
- return result.text;
253
- }
254
-
255
- export function isSupportedPromptFileName(filename: string): boolean {
256
- return SUPPORTED_EXTENSIONS.has(extensionForPath(filename || ""));
257
- }
@@ -1,70 +0,0 @@
1
- const MODEL_HINTS = [
2
- ["gpt-image-2", /\bgpt[- ]?image[- ]?2\b/i],
3
- ["gpt-image", /\bgpt[- ]?image\b/i],
4
- ["nano-banana", /\bnano[- ]?banana\b/i],
5
- ["midjourney", /\bmidjourney\b/i],
6
- ["stable-diffusion", /\bstable[- ]?diffusion\b/i],
7
- ];
8
-
9
- const TASK_HINTS = [
10
- ["image_generation", /\b(image generation|generate an image|text to image)\b/i],
11
- ["reference-image", /\b(reference image|keep the same|preserve|consistent character|same face)\b/i],
12
- ["mask-edit", /\b(mask|inpaint|outpaint|replace only|change only)\b/i],
13
- ["typography", /\b(typography|headline|readable text|lettering|poster text|title text)\b/i],
14
- ["layout", /\b(layout|grid|composition|poster|diagram|infographic)\b/i],
15
- ["product-shot", /\b(product photo|product shot|packaging|label|reflection)\b/i],
16
- ];
17
-
18
- const SIZE_HINTS = [
19
- ["2k", /\b2k\b/i],
20
- ["4k", /\b4k\b/i],
21
- ["square", /\bsquare\b/i],
22
- ["portrait", /\bportrait|vertical\b/i],
23
- ["landscape", /\blandscape|horizontal\b/i],
24
- ];
25
-
26
- const QUALITY_HINTS = [
27
- ["low", /\blow\b/i],
28
- ["medium", /\bmedium\b/i],
29
- ["high", /\bhigh\b/i],
30
- ["auto", /\bauto\b/i],
31
- ["draft", /\bdraft|thumbnail|iteration\b/i],
32
- ["final", /\bfinal|production[- ]ready\b/i],
33
- ];
34
-
35
- type HintTuple = [string, RegExp];
36
-
37
- function matches(text: string, patterns: HintTuple[]): string[] {
38
- return patterns.filter(([, pattern]: HintTuple) => pattern.test(text)).map(([name]: HintTuple) => name);
39
- }
40
-
41
- export function extractGptImageHints(text: unknown) {
42
- const value = String(text || "");
43
- const modelHints = matches(value, MODEL_HINTS as HintTuple[]);
44
- const taskHints = matches(value, TASK_HINTS as HintTuple[]);
45
- const sizeHints = matches(value, SIZE_HINTS as HintTuple[]);
46
- const qualityHints = matches(value, QUALITY_HINTS as HintTuple[]);
47
- const warnings: string[] = [];
48
-
49
- if (/\btransparent|alpha channel|no background|cutout\b/i.test(value)) {
50
- warnings.push("transparent-unsupported-gpt-image-2");
51
- }
52
- if (/\bexact text|small text|dense text|legal copy\b/i.test(value)) {
53
- warnings.push("text-rendering-sensitive");
54
- }
55
- if (/\bcomplex layout|multi[- ]panel|precise diagram\b/i.test(value)) {
56
- warnings.push("layout-sensitive");
57
- }
58
- if (/\b4k|high resolution|ultra[- ]high\b/i.test(value)) {
59
- warnings.push("high-res-cost-warning");
60
- }
61
-
62
- return {
63
- modelHints,
64
- generationSurfaceHints: taskHints.includes("image_generation") ? ["responses-image-tool"] : [],
65
- taskHints,
66
- sizeHints,
67
- qualityHints,
68
- warnings,
69
- };
70
- }
@@ -1,179 +0,0 @@
1
- import { createHash } from "crypto";
2
- import type { PromptCandidate, PromptCandidateScoreHints, PromptCandidateSource, PromptImportLimits } from "./types.js";
3
-
4
- interface PushCandidateOptions {
5
- name: string;
6
- tags: string[];
7
- warnings?: string[];
8
- source: PromptCandidateSource;
9
- headingPath?: string | null;
10
- scoreHints?: PromptCandidateScoreHints;
11
- limits: PromptImportLimits;
12
- }
13
-
14
- interface ParseCommonOptions extends PushCandidateOptions {
15
- candidates: PromptCandidate[];
16
- baseName: string;
17
- }
18
-
19
- function normalizeWhitespace(text: string): string {
20
- return text.replace(/\r\n/g, "\n").replace(/[ \t]+\n/g, "\n").trim();
21
- }
22
-
23
- function stripFrontmatter(text: string): string {
24
- return text.replace(/^---\s*\n[\s\S]*?\n---\s*\n/, "");
25
- }
26
-
27
- function isBoilerplate(line: string): boolean {
28
- const trimmed = line.trim();
29
- return (
30
- !trimmed ||
31
- /^\[!\[.*\]\(.+\)\]\(.+\)$/.test(trimmed) ||
32
- /^!\[.*\]\(.+\)$/.test(trimmed) ||
33
- /^\[.*\]\(.+\)$/.test(trimmed)
34
- );
35
- }
36
-
37
- function titleFromFilename(filename: string): string {
38
- return (filename || "Imported prompt")
39
- .replace(/\.(txt|md|markdown)$/i, "")
40
- .replace(/[-_]+/g, " ")
41
- .trim() || "Imported prompt";
42
- }
43
-
44
- function candidateId(text: string, ordinal: number): string {
45
- return `candidate_${ordinal}_${createHash("sha256").update(text).digest("hex").slice(0, 10)}`;
46
- }
47
-
48
- function promptHash(text: string): string {
49
- return createHash("sha256").update(normalizeWhitespace(text).toLowerCase()).digest("hex");
50
- }
51
-
52
- function headingName(heading: string | undefined, fallback: string): string {
53
- return heading?.replace(/^#+\s*/, "").trim() || fallback;
54
- }
55
-
56
- function allowedCandidate(text: string, limits: PromptImportLimits): boolean {
57
- const length = text.trim().length;
58
- return length >= limits.minCandidateChars && length <= limits.maxCandidateChars;
59
- }
60
-
61
- function cleanMarkdownBody(text: string): string {
62
- return normalizeWhitespace(
63
- text
64
- .split("\n")
65
- .filter((line) => !isBoilerplate(line))
66
- .filter((line) => !/^\|.*\|$/.test(line.trim()))
67
- .join("\n"),
68
- );
69
- }
70
-
71
- function pushCandidate(candidates: PromptCandidate[], rawText: string, options: PushCandidateOptions): void {
72
- const text = normalizeWhitespace(rawText);
73
- if (!allowedCandidate(text, options.limits)) return;
74
- const ordinal = candidates.length + 1;
75
- const hash = promptHash(text);
76
- candidates.push({
77
- id: candidateId(text, ordinal),
78
- name: options.name,
79
- text,
80
- textPreview: text.slice(0, 220),
81
- tags: [...new Set(options.tags)],
82
- warnings: options.warnings ?? [],
83
- source: options.source,
84
- headingPath: options.headingPath ?? null,
85
- ordinal,
86
- promptHash: hash,
87
- scoreHints: options.scoreHints ?? {},
88
- });
89
- }
90
-
91
- function parseMarkdown(text: string, options: ParseCommonOptions): void {
92
- const source = stripFrontmatter(text).slice(0, options.limits.maxSourceCharsScanned);
93
- const fencePattern = /```([A-Za-z0-9_-]*)\n([\s\S]*?)```/g;
94
- const acceptedFenceLanguages = new Set(["", "prompt", "text", "markdown", "md"]);
95
- const ranges: Array<[number, number]> = [];
96
-
97
- for (const match of source.matchAll(fencePattern)) {
98
- const language = (match[1] || "").toLowerCase();
99
- if (!acceptedFenceLanguages.has(language)) continue;
100
- ranges.push([match.index ?? 0, (match.index ?? 0) + match[0].length]);
101
- pushCandidate(options.candidates, match[2], {
102
- ...options,
103
- name: `${options.baseName} ${options.candidates.length + 1}`,
104
- headingPath: options.headingPath ?? null,
105
- });
106
- if (options.candidates.length >= options.limits.maxPromptCandidatesPerFile) return;
107
- }
108
-
109
- const withoutFences = source
110
- .split("\n")
111
- .filter((line, index, lines) => {
112
- void line;
113
- const offset = lines.slice(0, index).join("\n").length + (index > 0 ? 1 : 0);
114
- return !ranges.some(([start, end]) => offset >= start && offset < end);
115
- })
116
- .join("\n");
117
- const sections = withoutFences.split(/(?=^#{1,4}\s+)/gm);
118
- for (const section of sections) {
119
- const heading = /^#{1,4}\s+(.+)$/m.exec(section)?.[1];
120
- const body = cleanMarkdownBody(section.replace(/^#{1,4}\s+.+$/m, ""));
121
- pushCandidate(options.candidates, body, {
122
- ...options,
123
- name: headingName(heading, `${options.baseName} ${options.candidates.length + 1}`),
124
- headingPath: headingName(heading, options.baseName),
125
- });
126
- if (options.candidates.length >= options.limits.maxPromptCandidatesPerFile) return;
127
- }
128
- }
129
-
130
- function splitTextPrompts(text: string): string[] {
131
- const normalized = normalizeWhitespace(text);
132
- const separatorBlocks = normalized.split(/\n\s*---+\s*\n/g).filter(Boolean);
133
- const blocks = separatorBlocks.length > 1
134
- ? separatorBlocks
135
- : normalized.split(/\n\s*\n+/g).filter(Boolean);
136
- const numbered = normalized.split(/(?=^\s*\d+[.)]\s+)/gm).filter(Boolean);
137
- const longLines = normalized.split("\n").map((line) => line.trim()).filter((line) => line.length >= 80);
138
- return blocks.length > 1 ? blocks : numbered.length > 1 ? numbered : longLines.length > 1 ? longLines : [normalized];
139
- }
140
-
141
- function parsePlainText(text: string, options: ParseCommonOptions): void {
142
- const chunks = splitTextPrompts(text.slice(0, options.limits.maxSourceCharsScanned));
143
- for (const chunk of chunks) {
144
- const clean = chunk.replace(/^\s*\d+[.)]\s+/, "");
145
- pushCandidate(options.candidates, clean, {
146
- ...options,
147
- name: `${options.baseName} ${options.candidates.length + 1}`,
148
- headingPath: `${options.baseName} ${options.candidates.length + 1}`,
149
- });
150
- if (options.candidates.length >= options.limits.maxPromptCandidatesPerFile) return;
151
- }
152
- }
153
-
154
- interface ParsePromptCandidatesInput {
155
- text: string;
156
- filename: string;
157
- source: PromptCandidateSource;
158
- tags?: string[];
159
- limits: PromptImportLimits;
160
- }
161
-
162
- export function parsePromptCandidates({ text, filename, source, tags = [], limits }: ParsePromptCandidatesInput): PromptCandidate[] {
163
- const candidates: PromptCandidate[] = [];
164
- const extension = (filename.split(".").pop() || "").toLowerCase();
165
- const baseName = titleFromFilename(filename);
166
- const common: ParseCommonOptions = {
167
- candidates,
168
- limits,
169
- baseName,
170
- tags,
171
- source,
172
- name: baseName,
173
- };
174
-
175
- if (extension === "txt") parsePlainText(text, common);
176
- else parseMarkdown(text, common);
177
-
178
- return candidates.slice(0, limits.maxPromptCandidatesPerFile);
179
- }