@artifactshare/cli 0.13.3 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import { cli, define, lazy } from "gunshi";
4
4
  import { generate } from "gunshi/generator";
5
5
  import { chmodSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, watch, writeFileSync } from "node:fs";
6
6
  import { pathToFileURL } from "node:url";
7
+ import { z } from "zod";
7
8
  import { execFile, spawn } from "node:child_process";
8
9
  import { appendFile, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
9
10
  import { arch, homedir, platform } from "node:os";
@@ -14,9 +15,602 @@ import { Blob, Buffer as Buffer$1 } from "node:buffer";
14
15
  import { EventEmitter } from "node:events";
15
16
  import { createServer } from "node:http";
16
17
  import { promisify } from "node:util";
18
+ //#region ../contract/dist/index.js
19
+ const CLI_DEVICE_CLIENT_ID = "artifactshare-cli";
20
+ const stringId = z.string().min(1);
21
+ const timestamp = z.string().min(1);
22
+ const url = z.string().url();
23
+ const nullableTimestamp = timestamp.nullable();
24
+ const ArtifactKindSchema = z.enum([
25
+ "markdown_page",
26
+ "html_page",
27
+ "static_site",
28
+ "spa",
29
+ "workspace_app"
30
+ ]);
31
+ const UploadArtifactKindSchema = z.enum([
32
+ "markdown_page",
33
+ "html_page",
34
+ "static_site"
35
+ ]);
36
+ const VisibilitySchema = z.enum([
37
+ "private",
38
+ "workspace",
39
+ "project",
40
+ "link"
41
+ ]);
42
+ const ProjectBaseVisibilitySchema = z.enum(["workspace", "private"]);
43
+ const ApiErrorSchema = z.object({
44
+ code: stringId,
45
+ message: z.string().min(1),
46
+ details: z.record(z.string(), z.unknown()).optional(),
47
+ why: z.string().optional(),
48
+ hint: z.string().optional(),
49
+ recovery: z.object({
50
+ kind: stringId,
51
+ command: z.string().optional()
52
+ }).optional()
53
+ });
54
+ const ApiErrorResponseSchema = z.object({ error: ApiErrorSchema });
55
+ /** OAuth device endpoints use the RFC 8628 string error envelope. */
56
+ const OAuthErrorResponseSchema = z.object({
57
+ error: stringId,
58
+ error_description: z.string().optional()
59
+ });
60
+ z.object({
61
+ error: ApiErrorSchema,
62
+ agent_recoverable: z.boolean(),
63
+ requires_human: z.boolean()
64
+ });
65
+ z.object({ id: stringId });
66
+ z.object({
67
+ id: stringId,
68
+ "*": stringId
69
+ });
70
+ z.object({ id: stringId });
71
+ z.object({
72
+ refresh_token: z.string().min(1).max(256),
73
+ /** Optional for CLIs released before refresh-credential rotation. */
74
+ rotation_request_id: z.string().min(1).max(128).optional()
75
+ });
76
+ z.object({ refresh_token: z.string().min(1).max(256) });
77
+ const LegacyCliAuthRefreshResponseSchema = z.object({
78
+ access_token: stringId,
79
+ token_type: z.string().min(1),
80
+ expires_at: timestamp
81
+ });
82
+ const RotatingCliAuthRefreshResponseSchema = z.object({
83
+ access_token: stringId,
84
+ token_type: z.string().min(1),
85
+ expires_at: timestamp,
86
+ refresh_token: stringId,
87
+ refresh_token_expires_at: timestamp
88
+ });
89
+ /**
90
+ * New servers return rotating credentials. The legacy response remains a
91
+ * valid read shape so a client can talk to a server during a rolling update.
92
+ */
93
+ const CliAuthRefreshResponseSchema = z.union([RotatingCliAuthRefreshResponseSchema, LegacyCliAuthRefreshResponseSchema]);
94
+ z.object({
95
+ device_name: z.string().max(100).nullable().optional(),
96
+ device_id: z.string().max(100).nullable().optional()
97
+ });
98
+ const CliAuthRefreshCredentialsResponseSchema = z.object({
99
+ refresh_token: stringId,
100
+ refresh_token_expires_at: timestamp
101
+ });
102
+ z.object({ refresh_token: z.string().min(1).max(256) });
103
+ z.object({ revoked: z.literal(true) });
104
+ const DeviceAuthorizationPresetSchema = z.enum(["unrestricted", "agent"]);
105
+ z.object({
106
+ client_id: z.literal(CLI_DEVICE_CLIENT_ID),
107
+ preset: DeviceAuthorizationPresetSchema.optional(),
108
+ device_name: z.string().max(100).nullable().optional(),
109
+ project_selector: z.string().refine((value) => {
110
+ const size = Array.from(value.trim()).length;
111
+ return size >= 1 && size <= 120;
112
+ }, "project_selector must contain 1 to 120 Unicode code points after trimming").optional()
113
+ }).superRefine((value, context) => {
114
+ if (value.preset !== "agent" && value.project_selector !== void 0) context.addIssue({
115
+ code: "custom",
116
+ path: ["project_selector"],
117
+ message: "project_selector requires the agent preset"
118
+ });
119
+ });
120
+ const DeviceCodeResponseSchema = z.object({
121
+ device_code: stringId,
122
+ user_code: stringId,
123
+ verification_uri: url,
124
+ /** Older auth responses may omit this convenience URL or return null. */
125
+ verification_uri_complete: url.nullable().optional(),
126
+ expires_in: z.number().int().nonnegative(),
127
+ interval: z.number().int().nonnegative()
128
+ });
129
+ z.object({
130
+ grant_type: z.literal("urn:ietf:params:oauth:grant-type:device_code"),
131
+ device_code: stringId,
132
+ client_id: z.literal(CLI_DEVICE_CLIENT_ID)
133
+ });
134
+ const DeviceTokenResponseSchema = z.object({
135
+ access_token: stringId,
136
+ token_type: z.string().min(1).refine((value) => value.toLowerCase() === "bearer", { message: "token_type must be Bearer" }),
137
+ expires_in: z.number().int().nonnegative().optional()
138
+ });
139
+ z.object({
140
+ userCode: stringId,
141
+ project_id: stringId.optional()
142
+ });
143
+ z.object({ user_code: stringId });
144
+ z.object({ status: z.string().optional() });
145
+ z.object({ userCode: stringId });
146
+ z.object({ user_code: stringId });
147
+ const FixedAgentApprovalProjectSchema = z.object({
148
+ id: stringId,
149
+ name: z.string(),
150
+ baseVisibility: ProjectBaseVisibilitySchema,
151
+ updatedAt: timestamp
152
+ });
153
+ const AgentApprovalSchema = z.object({
154
+ preset: z.literal("agent"),
155
+ deviceName: z.string().nullable(),
156
+ projectSelector: z.string().nullable(),
157
+ fixedProject: FixedAgentApprovalProjectSchema.nullable(),
158
+ fixedProjectError: z.boolean()
159
+ });
160
+ z.object({ agentApproval: AgentApprovalSchema.nullable() });
161
+ const CliUserSchema = z.object({
162
+ id: stringId,
163
+ email: z.string()
164
+ });
165
+ const CliWorkspaceSchema = z.object({
166
+ id: stringId,
167
+ hosted_domain: z.string().nullable()
168
+ });
169
+ const CliWhoamiResponseSchema = z.object({
170
+ user: CliUserSchema,
171
+ workspace: CliWorkspaceSchema,
172
+ auth: z.object({ kind: z.literal("bearer_or_session") }).optional()
173
+ });
174
+ const DoctorAuthoritySchema = z.object({
175
+ preset: DeviceAuthorizationPresetSchema,
176
+ project_id: stringId.nullable()
177
+ });
178
+ const DoctorUploadSchema = z.union([z.object({ ok: z.literal(true) }), z.object({
179
+ ok: z.literal(false),
180
+ code: stringId,
181
+ message: z.string()
182
+ })]);
183
+ const CliDoctorResponseSchema = z.object({
184
+ user: CliUserSchema.extend({ id: stringId.optional() }),
185
+ workspace: CliWorkspaceSchema.optional(),
186
+ auth: z.object({
187
+ kind: z.literal("bearer_or_session").optional(),
188
+ ok: z.literal(true),
189
+ authority: DoctorAuthoritySchema.optional()
190
+ }),
191
+ upload: DoctorUploadSchema
192
+ });
193
+ z.object({
194
+ publish_key: z.string().optional(),
195
+ expected_version: z.string().optional(),
196
+ artifact_kind: z.literal("static_site").optional(),
197
+ container_id: z.string().optional()
198
+ });
199
+ const VersionLabelSchema = z.string().refine((value) => Array.from(value).length >= 1 && Array.from(value).length <= 80 && /[^\p{Default_Ignorable_Code_Point}\p{Zs}]/u.test(value) && !/[^\p{L}\p{M}\p{N}\p{P}\p{S}\p{Zs}\u200D]/u.test(value), "Label must contain 1–80 Unicode code points using letters, marks, numbers, punctuation, symbols, spaces, or joined emoji.");
200
+ const VersionLabelInputSchema = z.string().transform((value) => value.normalize("NFC").replace(/^\p{Zs}+|\p{Zs}+$/gu, "")).pipe(VersionLabelSchema);
201
+ z.object({
202
+ label: VersionLabelInputSchema.optional(),
203
+ expected_version: z.string().optional(),
204
+ artifact_kind: z.literal("static_site").optional()
205
+ });
206
+ /** Preserve the file and its bytes without depending on a global File class. */
207
+ const MultipartFilePartSchema = z.custom((value) => {
208
+ if (typeof value !== "object" || value === null) return false;
209
+ return "name" in value && typeof value.name === "string" && "size" in value && typeof value.size === "number" && Number.isInteger(value.size) && value.size >= 0 && "type" in value && typeof value.type === "string" && "arrayBuffer" in value && typeof value.arrayBuffer === "function";
210
+ }, "Expected a multipart file part");
211
+ z.object({ file: z.array(MultipartFilePartSchema).min(1) }).extend({
212
+ visibility: VisibilitySchema.optional(),
213
+ grant_email: z.array(z.string()).optional(),
214
+ container_id: z.string().optional(),
215
+ link_expires_at: z.string().optional(),
216
+ slack_notify: z.string().optional()
217
+ });
218
+ const UploadWarningSchema = z.object({
219
+ code: z.literal("slack_reauthorization_required"),
220
+ message: z.string()
221
+ });
222
+ const ArtifactUploadResponseSchema = z.object({
223
+ id: stringId,
224
+ versionId: stringId,
225
+ artifactKind: UploadArtifactKindSchema,
226
+ visibility: VisibilitySchema.optional(),
227
+ link_expires_at: nullableTimestamp.optional(),
228
+ containerId: stringId.nullable().optional(),
229
+ shareUrl: url,
230
+ /** Present only for publish-key requests. */
231
+ created: z.boolean().optional(),
232
+ warnings: z.array(UploadWarningSchema).optional()
233
+ });
234
+ const ArtifactVersionUpdateResponseSchema = z.object({
235
+ number: z.number().int().positive().optional(),
236
+ label: VersionLabelSchema.nullable().optional(),
237
+ id: stringId.optional(),
238
+ versionId: stringId,
239
+ shareUrl: url.optional(),
240
+ /** Static-site replacement responses include this field. */
241
+ artifactKind: UploadArtifactKindSchema.optional()
242
+ });
243
+ z.object({
244
+ id: stringId,
245
+ currentVersionId: stringId.nullable()
246
+ });
247
+ z.object({
248
+ /** Empty string selects the unfiled home list. */
249
+ project_id: z.string().optional(),
250
+ query: z.string().optional(),
251
+ cursor: z.string().optional()
252
+ });
253
+ const ArtifactIncludeSchema = z.enum(["versions", "comments"]);
254
+ z.object({
255
+ offset: z.number().int().nonnegative().optional(),
256
+ include: z.array(ArtifactIncludeSchema).optional()
257
+ });
258
+ z.object({
259
+ offset: z.string().regex(/^\d+$/).optional(),
260
+ include: z.array(z.string()).optional().superRefine((values, context) => {
261
+ if (!values) return;
262
+ for (const [index, value] of values.entries()) for (const item of value.split(",")) {
263
+ const candidate = item.trim();
264
+ if (!candidate) continue;
265
+ if (!ArtifactIncludeSchema.safeParse(candidate).success) context.addIssue({
266
+ code: "custom",
267
+ path: [index],
268
+ message: "include must be versions or comments"
269
+ });
270
+ }
271
+ })
272
+ });
273
+ const ArtifactVersionSchema = z.object({
274
+ label: VersionLabelSchema.optional(),
275
+ version_id: stringId,
276
+ status: z.string(),
277
+ size_bytes: z.number().nonnegative(),
278
+ created_at: timestamp,
279
+ published_at: nullableTimestamp,
280
+ is_current: z.boolean(),
281
+ creator: z.object({
282
+ kind: z.enum(["human", "agent"]),
283
+ name: z.string(),
284
+ email: z.string().nullable(),
285
+ agent_profile_id: stringId.nullable()
286
+ }).nullable()
287
+ });
288
+ const ArtifactReadResponseSchema = z.object({
289
+ id: stringId,
290
+ share_url: url,
291
+ version_id: stringId,
292
+ format: z.enum(["html", "markdown"]),
293
+ content: z.string(),
294
+ size_bytes: z.number().nonnegative(),
295
+ truncated: z.boolean(),
296
+ next_offset: z.number().int().nonnegative().nullable(),
297
+ link_expires_at: nullableTimestamp.optional(),
298
+ project_id: stringId.nullable().optional(),
299
+ versions: z.array(ArtifactVersionSchema).optional(),
300
+ versions_has_more: z.boolean().optional(),
301
+ comments: z.array(z.lazy(() => CommentThreadSchema)).optional(),
302
+ comments_has_more: z.boolean().optional()
303
+ });
304
+ const ArtifactDeleteResponseSchema = z.object({
305
+ id: stringId,
306
+ deleted: z.literal(true)
307
+ });
308
+ z.object({ content: z.string().min(1) });
309
+ const ArtifactAppendResponseSchema = z.object({
310
+ id: stringId.optional(),
311
+ versionId: stringId,
312
+ shareUrl: url.optional(),
313
+ artifactKind: UploadArtifactKindSchema.optional()
314
+ });
315
+ const DownloadManifestFileSchema = z.object({
316
+ path: z.string().min(1),
317
+ size_bytes: z.number().int().nonnegative(),
318
+ content_type: z.string().min(1),
319
+ sha256: z.string()
320
+ });
321
+ const DownloadManifestResponseSchema = z.object({
322
+ id: stringId,
323
+ share_url: url,
324
+ version_id: stringId,
325
+ artifact_kind: UploadArtifactKindSchema,
326
+ files: z.array(DownloadManifestFileSchema),
327
+ total_size_bytes: z.number().int().nonnegative(),
328
+ project_id: stringId.nullable().optional()
329
+ });
330
+ const ArtifactsListEntrySchema = z.object({
331
+ id: stringId,
332
+ title: z.string(),
333
+ share_url: url,
334
+ visibility: VisibilitySchema,
335
+ link_expires_at: nullableTimestamp.optional(),
336
+ updated_at: timestamp,
337
+ project_id: stringId.nullable(),
338
+ owner_email: z.string().optional(),
339
+ artifact_kind: ArtifactKindSchema.optional()
340
+ });
341
+ const ArtifactsListResponseSchema = z.object({
342
+ artifacts: z.array(ArtifactsListEntrySchema),
343
+ limit: z.number().int().nonnegative(),
344
+ has_more: z.boolean(),
345
+ next_cursor: z.string().nullable()
346
+ });
347
+ const CommentAnchorSchema = z.union([z.object({
348
+ kind: z.literal("artifact"),
349
+ quoted_text: z.null(),
350
+ state: z.null()
351
+ }), z.object({
352
+ kind: z.literal("text"),
353
+ quoted_text: z.string(),
354
+ state: z.enum(["attached", "orphaned"])
355
+ })]);
356
+ const CommentMessageSchema = z.object({
357
+ message_id: stringId,
358
+ author_name: z.string().nullable(),
359
+ author_email: z.string(),
360
+ agent: z.string().nullable(),
361
+ body: z.string(),
362
+ created_at: timestamp,
363
+ updated_at: timestamp
364
+ });
365
+ const CommentThreadSchema = z.object({
366
+ id: stringId,
367
+ status: z.enum(["open", "resolved"]),
368
+ resolved_at: nullableTimestamp,
369
+ created_at: timestamp,
370
+ updated_at: timestamp,
371
+ anchor: CommentAnchorSchema,
372
+ messages: z.array(CommentMessageSchema)
373
+ });
374
+ const CommentPostRequestSchema = z.object({
375
+ action: z.never().optional(),
376
+ body: z.string().min(1).max(4e3),
377
+ reply_to: z.string().min(1).max(128).optional(),
378
+ quote: z.string().min(1).max(1e3).optional(),
379
+ quote_before: z.string().min(1).max(200).optional(),
380
+ quote_after: z.string().min(1).max(200).optional(),
381
+ agent: z.string().refine((value) => value.trim().length <= 30, "agent must contain at most 30 characters after trimming").optional()
382
+ }).superRefine((value, context) => {
383
+ if (value.reply_to !== void 0 && value.quote !== void 0) context.addIssue({
384
+ code: "custom",
385
+ path: ["quote"],
386
+ message: "A quote can only anchor a new thread, not a reply."
387
+ });
388
+ if (value.quote === void 0 && (value.quote_before !== void 0 || value.quote_after !== void 0)) context.addIssue({
389
+ code: "custom",
390
+ path: ["quote"],
391
+ message: "quote_before and quote_after require quote"
392
+ });
393
+ });
394
+ const CommentEditRequestSchema = z.object({
395
+ action: z.literal("edit"),
396
+ message_id: stringId.max(128),
397
+ body: z.string().min(1).max(4e3)
398
+ });
399
+ const CommentResolveRequestSchema = z.object({
400
+ action: z.literal("resolve"),
401
+ thread_id: stringId.max(128)
402
+ });
403
+ const CommentReopenRequestSchema = z.object({
404
+ action: z.literal("reopen"),
405
+ thread_id: stringId.max(128)
406
+ });
407
+ const CommentDeleteRequestSchema = z.object({
408
+ action: z.literal("delete"),
409
+ thread_id: stringId.max(128),
410
+ message_id: stringId.max(128).optional()
411
+ });
412
+ const CommentActionRequestSchema = z.union([
413
+ CommentEditRequestSchema,
414
+ CommentResolveRequestSchema,
415
+ CommentReopenRequestSchema,
416
+ CommentDeleteRequestSchema
417
+ ]);
418
+ z.union([CommentActionRequestSchema, CommentPostRequestSchema]);
419
+ const CommentsListResponseSchema = z.object({
420
+ artifact_id: stringId,
421
+ share_url: url.nullable().optional(),
422
+ comments: z.array(CommentThreadSchema),
423
+ has_more: z.boolean().optional()
424
+ });
425
+ const CommentPostResponseSchema = z.object({
426
+ artifact_id: stringId,
427
+ share_url: url.nullable().optional(),
428
+ thread_id: stringId,
429
+ reply: z.boolean(),
430
+ thread: CommentThreadSchema
431
+ });
432
+ const CommentActionResponseSchema = z.object({
433
+ artifact_id: stringId,
434
+ share_url: url.nullable().optional(),
435
+ thread_id: stringId,
436
+ thread: CommentThreadSchema
437
+ });
438
+ const CommentDeleteResponseSchema = z.object({
439
+ artifact_id: stringId,
440
+ share_url: url.nullable().optional(),
441
+ thread_id: stringId,
442
+ deleted: z.literal(true),
443
+ thread_deleted: z.boolean(),
444
+ thread: CommentThreadSchema.optional()
445
+ });
446
+ const ProjectListEntrySchema = z.object({
447
+ id: stringId,
448
+ name: z.string(),
449
+ description: z.string().nullable(),
450
+ base_visibility: z.string().min(1),
451
+ file_count: z.number().int().nonnegative().nullable(),
452
+ updated_at: timestamp.nullable()
453
+ });
454
+ const ProjectsListResponseSchema = z.object({ projects: z.array(ProjectListEntrySchema) });
455
+ z.object({
456
+ name: z.string().min(1),
457
+ description: z.string().nullable().optional(),
458
+ base_visibility: ProjectBaseVisibilitySchema.nullable().optional()
459
+ });
460
+ const ProjectCreateResponseSchema = z.object({ project: z.object({
461
+ id: stringId,
462
+ name: z.string(),
463
+ description: z.string().nullable(),
464
+ base_visibility: ProjectBaseVisibilitySchema
465
+ }) });
466
+ z.object({
467
+ name: z.string().optional(),
468
+ description: z.string().nullable().optional(),
469
+ base_visibility: ProjectBaseVisibilitySchema.nullable().optional(),
470
+ add_emails: z.array(z.string()).optional(),
471
+ remove_emails: z.array(z.string()).optional(),
472
+ archived: z.boolean().optional()
473
+ }).refine((value) => Object.keys(value).length > 0, { message: "At least one project edit field is required" });
474
+ const ProjectEditResponseSchema = z.object({
475
+ project: z.object({
476
+ id: stringId,
477
+ name: z.string(),
478
+ description: z.string().nullable(),
479
+ base_visibility: ProjectBaseVisibilitySchema,
480
+ file_count: z.number().int().nonnegative().nullable(),
481
+ archived: z.boolean()
482
+ }),
483
+ audience: z.array(z.string())
484
+ });
485
+ const CliEditableVisibilitySchema = z.enum([
486
+ "private",
487
+ "workspace",
488
+ "link"
489
+ ]);
490
+ const CliDestinationSchema = z.union([z.literal("home"), z.object({ project_id: stringId })]);
491
+ const CliEditDestinationSchema = z.union([z.literal("home"), z.object({ project_id: z.string().trim().min(1) })]);
492
+ z.object({
493
+ title: z.string().optional(),
494
+ visibility: CliEditableVisibilitySchema.optional(),
495
+ link_expires_at: z.string().nullable().optional(),
496
+ add_emails: z.array(z.string()).optional(),
497
+ remove_emails: z.array(z.string()).optional(),
498
+ destination: CliEditDestinationSchema.optional()
499
+ }).refine((value) => Object.keys(value).length > 0, { message: "At least one edit field is required" });
500
+ const CliArtifactReferenceSchema = z.object({
501
+ id: stringId,
502
+ url: url.nullable().optional()
503
+ });
504
+ const CliArtifactDestinationSchema = z.union([z.object({
505
+ type: z.literal("home"),
506
+ project_id: z.null()
507
+ }), z.object({
508
+ type: z.literal("project"),
509
+ project_id: stringId
510
+ })]);
511
+ const CliEditResponseSchema = z.object({
512
+ artifact: CliArtifactReferenceSchema,
513
+ title: z.string(),
514
+ destination: CliArtifactDestinationSchema,
515
+ share: z.object({
516
+ visibility: VisibilitySchema,
517
+ link_expires_at: nullableTimestamp.optional()
518
+ })
519
+ });
520
+ z.object({ destination: CliDestinationSchema });
521
+ const CliMoveResponseSchema = z.object({
522
+ artifact: CliArtifactReferenceSchema,
523
+ destination: CliArtifactDestinationSchema,
524
+ share: z.object({
525
+ visibility: VisibilitySchema,
526
+ project_audience_may_change: z.boolean()
527
+ })
528
+ });
529
+ z.object({ q: z.string().trim().min(1) });
530
+ const ResolveMatchSchema = z.object({
531
+ kind: z.enum([
532
+ "url",
533
+ "id",
534
+ "title",
535
+ "project_name"
536
+ ]),
537
+ confidence: z.enum(["exact", "candidate"])
538
+ });
539
+ const ArtifactResolveCandidateSchema = z.object({
540
+ kind: z.literal("artifact"),
541
+ id: stringId,
542
+ title: z.string(),
543
+ artifact_kind: ArtifactKindSchema,
544
+ visibility: VisibilitySchema,
545
+ project: z.object({
546
+ id: stringId,
547
+ name: z.string()
548
+ }).nullable(),
549
+ owner: z.object({
550
+ id: stringId,
551
+ email: z.string()
552
+ }),
553
+ updated_at: timestamp,
554
+ match: ResolveMatchSchema
555
+ });
556
+ const VersionResolveCandidateSchema = z.object({
557
+ kind: z.literal("version"),
558
+ id: stringId,
559
+ artifact_id: stringId,
560
+ version_id: stringId,
561
+ ordinal: z.number().int().nonnegative(),
562
+ is_current: z.boolean(),
563
+ published_at: nullableTimestamp,
564
+ size_bytes: z.number().nonnegative(),
565
+ match: ResolveMatchSchema
566
+ });
567
+ const ProjectResolveCandidateSchema = z.object({
568
+ kind: z.literal("project"),
569
+ id: stringId,
570
+ name: z.string(),
571
+ description: z.string().nullable(),
572
+ base_visibility: z.string().min(1),
573
+ file_count: z.number().int().nonnegative(),
574
+ updated_at: timestamp,
575
+ match: ResolveMatchSchema
576
+ });
577
+ const ResolveCandidateSchema = z.union([
578
+ ArtifactResolveCandidateSchema,
579
+ VersionResolveCandidateSchema,
580
+ ProjectResolveCandidateSchema
581
+ ]);
582
+ const ResolveResponseSchema = z.object({
583
+ query: z.string(),
584
+ candidates: z.array(ResolveCandidateSchema),
585
+ has_more: z.boolean()
586
+ });
587
+ const CLI_AUTH_REFRESH_RESPONSE_SCHEMA = CliAuthRefreshResponseSchema;
588
+ const CLI_AUTH_REFRESH_CREDENTIALS_RESPONSE_SCHEMA = CliAuthRefreshCredentialsResponseSchema;
589
+ const DEVICE_CODE_RESPONSE_SCHEMA = DeviceCodeResponseSchema;
590
+ const DEVICE_TOKEN_RESPONSE_SCHEMA = DeviceTokenResponseSchema;
591
+ const CLI_WHOAMI_RESPONSE_SCHEMA = CliWhoamiResponseSchema;
592
+ const CLI_DOCTOR_RESPONSE_SCHEMA = CliDoctorResponseSchema;
593
+ const ARTIFACT_UPLOAD_RESPONSE_SCHEMA = ArtifactUploadResponseSchema;
594
+ const ARTIFACT_VERSION_UPDATE_RESPONSE_SCHEMA = ArtifactVersionUpdateResponseSchema;
595
+ const ARTIFACT_READ_RESPONSE_SCHEMA = ArtifactReadResponseSchema;
596
+ const ARTIFACT_DELETE_RESPONSE_SCHEMA = ArtifactDeleteResponseSchema;
597
+ const ARTIFACT_APPEND_RESPONSE_SCHEMA = ArtifactAppendResponseSchema;
598
+ const ARTIFACTS_LIST_RESPONSE_SCHEMA = ArtifactsListResponseSchema;
599
+ const DOWNLOAD_MANIFEST_RESPONSE_SCHEMA = DownloadManifestResponseSchema;
600
+ const COMMENTS_LIST_RESPONSE_SCHEMA = CommentsListResponseSchema;
601
+ const COMMENT_POST_RESPONSE_SCHEMA = CommentPostResponseSchema;
602
+ const COMMENT_ACTION_RESPONSE_SCHEMA = CommentActionResponseSchema;
603
+ const COMMENT_DELETE_RESPONSE_SCHEMA = CommentDeleteResponseSchema;
604
+ const PROJECTS_LIST_RESPONSE_SCHEMA = ProjectsListResponseSchema;
605
+ const PROJECT_CREATE_RESPONSE_SCHEMA = ProjectCreateResponseSchema;
606
+ const PROJECT_EDIT_RESPONSE_SCHEMA = ProjectEditResponseSchema;
607
+ const CLI_EDIT_RESPONSE_SCHEMA = CliEditResponseSchema;
608
+ const CLI_MOVE_RESPONSE_SCHEMA = CliMoveResponseSchema;
609
+ const RESOLVE_RESPONSE_SCHEMA = ResolveResponseSchema;
610
+ //#endregion
17
611
  //#region src/constants.ts
18
612
  const DEFAULT_BASE_URL = "https://artifactshare.com";
19
- const DEVICE_CLIENT_ID = "artifactshare-cli";
613
+ const DEVICE_CLIENT_ID = CLI_DEVICE_CLIENT_ID;
20
614
  const CLI_INVOCATION = "npm exec --yes --package=@artifactshare/cli -- artifactshare";
21
615
  const AGENT_DOWNLOAD_OUTPUT = "./artifact";
22
616
  const TOKEN_ENV_VAR = "ARTIFACTSHARE_TOKEN";
@@ -56,6 +650,7 @@ const VALUE_FLAGS = /* @__PURE__ */ new Set([
56
650
  "grant-email",
57
651
  "include",
58
652
  "key",
653
+ "label",
59
654
  "link-expires-at",
60
655
  "message-id",
61
656
  "name",
@@ -113,7 +708,11 @@ const COMMAND_NAMES = /* @__PURE__ */ new Set([
113
708
  "preview stop"
114
709
  ]);
115
710
  const SUBCOMMANDS = {
116
- artifacts: ["list", "get"],
711
+ artifacts: [
712
+ "list",
713
+ "get",
714
+ "delete"
715
+ ],
117
716
  comments: [
118
717
  "list",
119
718
  "post",
@@ -157,6 +756,7 @@ const UPDATE_OPTION_KEYS = /* @__PURE__ */ new Set([
157
756
  "allowPlaintextTokenStore",
158
757
  "baseUrl",
159
758
  "expectedVersion",
759
+ "label",
160
760
  "help",
161
761
  "insecureLocalhost",
162
762
  "json",
@@ -176,6 +776,10 @@ function isProfileCredentialSource(source) {
176
776
  function isRecord$1(value) {
177
777
  return typeof value === "object" && value !== null && !Array.isArray(value);
178
778
  }
779
+ /** Validate a wire value with the shared public contract without rewriting it. */
780
+ function isContract(schema, value) {
781
+ return schema.safeParse(value).success;
782
+ }
179
783
  function nonEmpty(value) {
180
784
  if (typeof value !== "string") return void 0;
181
785
  const trimmed = value.trim();
@@ -185,14 +789,16 @@ function nonEmpty(value) {
185
789
  //#region src/errors.ts
186
790
  const PROJECTS_LIST_COMMAND = `${CLI_INVOCATION} projects list --json`;
187
791
  function apiError(body) {
188
- const error = body?.error;
792
+ const contracted = isContract(ApiErrorResponseSchema, body) ? body.error : void 0;
793
+ const record = isRecord$1(body) ? body : void 0;
794
+ const error = contracted ?? record?.error;
189
795
  if (typeof error === "string") return {
190
796
  code: error,
191
797
  message: void 0
192
798
  };
193
799
  return {
194
- code: normalizeApiCode(error?.code),
195
- message: error?.message
800
+ code: normalizeApiCode(isRecord$1(error) ? error.code : void 0),
801
+ message: isRecord$1(error) && typeof error.message === "string" ? error.message : void 0
196
802
  };
197
803
  }
198
804
  function mapApiError(status, body, options = {}) {
@@ -207,16 +813,6 @@ function mapApiError(status, body, options = {}) {
207
813
  }
208
814
  return tokenInvalidError();
209
815
  }
210
- if (apiCode === "upload-not-allowed") return cliError({
211
- code: "upload_not_allowed",
212
- message: "Sharing is temporarily unavailable.",
213
- why: "Artifact Share has paused sharing for now.",
214
- hint: "Contact Artifact Share support if you need sharing enabled.",
215
- agentRecoverable: false,
216
- requiresHuman: true,
217
- recovery: { kind: "ask_human" },
218
- details: { limit: "upload_access" }
219
- });
220
816
  if (apiCode === "self-upload-disabled") return cliError({
221
817
  code: "self_upload_disabled",
222
818
  message: "This account cannot upload its own files.",
@@ -246,7 +842,8 @@ function mapApiError(status, body, options = {}) {
246
842
  recovery: { kind: "ask_human" }
247
843
  });
248
844
  if (apiCode === "quota-exceeded") {
249
- const apiDetails = typeof body?.error === "object" && isRecord$1(body.error.details) ? body.error.details : void 0;
845
+ const rawError = isRecord$1(body) ? body.error : void 0;
846
+ const apiDetails = isRecord$1(rawError) && isRecord$1(rawError.details) ? rawError.details : void 0;
250
847
  const upgradeRequest = isRecord$1(apiDetails?.upgrade_request) ? apiDetails.upgrade_request : void 0;
251
848
  return cliError({
252
849
  code: "storage_limit_exceeded",
@@ -388,7 +985,8 @@ function mapApiError(status, body, options = {}) {
388
985
  "update",
389
986
  "share"
390
987
  ].includes(options.operation ?? "") && apiCode === "version_conflict") {
391
- const current = typeof body?.error === "object" ? body.error.details : void 0;
988
+ const rawError = isRecord$1(body) ? body.error : void 0;
989
+ const current = isRecord$1(rawError) ? rawError.details : void 0;
392
990
  const currentVersionId = isRecord$1(current) && typeof current.current_version_id === "string" ? current.current_version_id : null;
393
991
  return cliError({
394
992
  code: "version_conflict",
@@ -402,7 +1000,8 @@ function mapApiError(status, body, options = {}) {
402
1000
  });
403
1001
  }
404
1002
  if (apiCode === "project-limit-reached") {
405
- const apiDetails = typeof body?.error === "object" && isRecord$1(body.error.details) ? body.error.details : void 0;
1003
+ const rawError = isRecord$1(body) ? body.error : void 0;
1004
+ const apiDetails = isRecord$1(rawError) && isRecord$1(rawError.details) ? rawError.details : void 0;
406
1005
  const upgradeRequest = isRecord$1(apiDetails?.upgrade_request) ? apiDetails.upgrade_request : void 0;
407
1006
  return cliError({
408
1007
  code: "project_limit_reached",
@@ -415,6 +1014,24 @@ function mapApiError(status, body, options = {}) {
415
1014
  ...upgradeRequest ? { details: { upgrade_request: upgradeRequest } } : {}
416
1015
  });
417
1016
  }
1017
+ if (apiCode === "link-publish-rate-limited") return cliError({
1018
+ code: "link_publish_rate_limited",
1019
+ message: apiMessage ?? "This new workspace has reached its daily link share limit.",
1020
+ why: "New Free workspaces may publish a bounded number of links per day; the limit protects link sharing from abuse.",
1021
+ hint: "Share with specific people now and retry the link visibility after the window passes (about a day), or ask the owner about the workspace plan.",
1022
+ agentRecoverable: true,
1023
+ requiresHuman: false,
1024
+ recovery: { kind: "retry_later" }
1025
+ });
1026
+ if (apiCode === "link-sharing-plan-required" || apiCode === "link-sharing-disabled" || apiCode === "link-expiry-invalid") return cliError({
1027
+ code: apiCode.replaceAll("-", "_"),
1028
+ message: apiMessage ?? "The link sharing option is invalid.",
1029
+ why: apiCode === "link-sharing-plan-required" ? "Link sharing is unavailable for this workspace." : apiCode === "link-sharing-disabled" ? "Link sharing is paused for this workspace; the owner or a Team admin can resume it." : "The requested link expiry does not match the link sharing policy.",
1030
+ hint: apiCode === "link-expiry-invalid" ? "Pass a future RFC3339 UTC timestamp within the workspace maximum, or use --no-link-expiry when unlimited expiry is allowed." : "Ask a workspace owner or administrator to review the workspace plan or link sharing policy.",
1031
+ agentRecoverable: apiCode === "link-expiry-invalid",
1032
+ requiresHuman: apiCode !== "link-expiry-invalid",
1033
+ recovery: apiCode === "link-expiry-invalid" ? { kind: "change_input" } : { kind: "ask_human" }
1034
+ });
418
1035
  if (apiCode === "forbidden" || status === 403) return cliError({
419
1036
  code: "forbidden",
420
1037
  message: apiMessage ?? "You do not have permission to do that.",
@@ -472,15 +1089,6 @@ function mapApiError(status, body, options = {}) {
472
1089
  requiresHuman: false,
473
1090
  recovery: { kind: "change_input" }
474
1091
  });
475
- if (apiCode === "link-sharing-plan-required" || apiCode === "link-sharing-disabled" || apiCode === "link-expiry-invalid") return cliError({
476
- code: apiCode.replaceAll("-", "_"),
477
- message: apiMessage ?? "The link sharing option is invalid.",
478
- why: apiCode === "link-sharing-plan-required" ? "Link sharing is available only on Plus and Team plans." : apiCode === "link-sharing-disabled" ? "The Team workspace has disabled link sharing." : "The requested link expiry does not match the link sharing policy.",
479
- hint: apiCode === "link-expiry-invalid" ? "Pass a future RFC3339 UTC timestamp within the workspace maximum, or use --no-link-expiry when unlimited expiry is allowed." : "Ask a workspace owner or administrator to review the workspace plan or link sharing policy.",
480
- agentRecoverable: apiCode === "link-expiry-invalid",
481
- requiresHuman: apiCode !== "link-expiry-invalid",
482
- recovery: apiCode === "link-expiry-invalid" ? { kind: "change_input" } : { kind: "ask_human" }
483
- });
484
1092
  if ((options.editSettings || options.projectTarget) && apiCode === "too-many-grants") return cliError({
485
1093
  code: "too_many_grants",
486
1094
  message: apiMessage ?? "Too many people are shared.",
@@ -530,6 +1138,15 @@ function mapApiError(status, body, options = {}) {
530
1138
  requiresHuman: false,
531
1139
  recovery: { kind: "change_input" }
532
1140
  });
1141
+ if (options.artifactTarget && (options.operation === "update" || options.operation === "share") && status === 400 && apiCode === "expected-version-required") return cliError({
1142
+ code: "expected_version_required",
1143
+ message: apiMessage ?? "Agent updates require the current version id.",
1144
+ why: "Agent-preset updates require an expected version.",
1145
+ hint: "Retry update or share --key with --expected-version <version-id>, using data.version.id from the previous successful share or update output. If that output is unavailable, for single-file HTML and Markdown artifacts, artifacts get <target> --json returns the current version as data.version_id. For static sites, download <target> --json returns it as data.version.id. Check the returned current content (data.content, or the downloaded files for static sites) and reapply your changes to it if it differs from what you edited. Pass the returned value as --expected-version.",
1146
+ agentRecoverable: true,
1147
+ requiresHuman: false,
1148
+ recovery: { kind: "change_input" }
1149
+ });
533
1150
  if (status === 400) return cliError({
534
1151
  code: "validation_failed",
535
1152
  message: apiMessage ?? "The request input is invalid.",
@@ -539,15 +1156,6 @@ function mapApiError(status, body, options = {}) {
539
1156
  requiresHuman: false,
540
1157
  recovery: { kind: "change_input" }
541
1158
  });
542
- if (apiCode === "upload-policy-unavailable") return cliError({
543
- code: "service_unavailable",
544
- message: apiMessage ?? "Upload permission could not be checked.",
545
- why: "Artifact Share could not verify upload permission right now.",
546
- hint: "Retry later with the same command.",
547
- agentRecoverable: true,
548
- requiresHuman: false,
549
- recovery: { kind: "retry_later" }
550
- });
551
1159
  if (apiCode === "maintenance") return cliError({
552
1160
  code: "maintenance",
553
1161
  message: apiMessage ?? "Artifact Share is currently under maintenance.",
@@ -818,8 +1426,6 @@ function normalizeApiCode(value) {
818
1426
  }
819
1427
  function uploadBlockedHint(code) {
820
1428
  if (code === "self-upload-disabled") return "Sign in with Google or Microsoft on the Artifact Share website, then retry share.";
821
- if (code === "upload-not-allowed") return "Contact Artifact Share support; sharing is temporarily unavailable.";
822
- if (code === "upload-policy-unavailable") return "Retry doctor later; upload permission could not be checked.";
823
1429
  return "Resolve the upload issue, then retry share.";
824
1430
  }
825
1431
  function projectNotFoundByNameError() {
@@ -944,7 +1550,9 @@ function resolveArtifactId(input) {
944
1550
  } catch {
945
1551
  return null;
946
1552
  }
947
- const sandboxMatch = url.hostname.match(/^([A-Za-z0-9]+)\.sandbox\./);
1553
+ const linkHostMatch = url.hostname.match(/^([A-Za-z0-9]{10})(?:--v-[a-f0-9]+)?\.artifactshare\.link$/);
1554
+ if (linkHostMatch?.[1]) return linkHostMatch[1];
1555
+ const sandboxMatch = url.hostname.match(/^([A-Za-z0-9]+)(?:--v-[a-f0-9]+)?\.sandbox\./);
948
1556
  if (sandboxMatch?.[1]) return sandboxMatch[1];
949
1557
  const shareMatch = url.pathname.match(/^\/a\/([A-Za-z0-9]+)(?:\.data)?\/?$/);
950
1558
  if (shareMatch?.[1]) return shareMatch[1];
@@ -971,7 +1579,7 @@ function targetResolutionError(input, command) {
971
1579
  code: "target_not_found",
972
1580
  message: "Artifact target could not be resolved.",
973
1581
  why: `${TARGET_COMMAND_LABELS[command]} only accepts an artifact ID, share URL, or sandbox URL.`,
974
- hint: "Retry with an artifact ID, /a/<id> share URL, or sandbox URL. If you only have a title, resolve it to an ID first.",
1582
+ hint: "Retry with an artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL. If you only have a title, resolve it to an ID first.",
975
1583
  agentRecoverable: true,
976
1584
  requiresHuman: false,
977
1585
  recovery: { kind: "change_input" },
@@ -1079,7 +1687,10 @@ function commandNameFromArgv(argv) {
1079
1687
  const command = found?.command;
1080
1688
  if (found && command !== void 0 && SUBCOMMANDS[command]) {
1081
1689
  const sub = nextPositional(argv, found.index);
1082
- if (sub !== void 0 && SUBCOMMANDS[command].includes(sub)) return `${command} ${sub}`;
1690
+ if (sub !== void 0 && SUBCOMMANDS[command].includes(sub)) {
1691
+ if (command === "artifacts" && sub === "delete") return "delete";
1692
+ return `${command} ${sub}`;
1693
+ }
1083
1694
  }
1084
1695
  return command !== void 0 && COMMAND_NAMES.has(command) ? command : void 0;
1085
1696
  }
@@ -1359,31 +1970,26 @@ function updateSuccessFields(data) {
1359
1970
  };
1360
1971
  }
1361
1972
  function resolveSuccessFields(data) {
1362
- if (!isRecord$1(data)) return false;
1363
- return typeof data.query === "string" && Array.isArray(data.candidates) && typeof data.has_more === "boolean";
1973
+ return isContract(RESOLVE_RESPONSE_SCHEMA, data);
1364
1974
  }
1365
1975
  function artifactGetSuccessFields(data) {
1976
+ if (isContract(ARTIFACT_READ_RESPONSE_SCHEMA, data)) return true;
1366
1977
  if (!isRecord$1(data)) return false;
1367
1978
  return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && (data.format === "html" || data.format === "markdown") && typeof data.content === "string" && typeof data.size_bytes === "number" && typeof data.truncated === "boolean" && (typeof data.next_offset === "number" || data.next_offset === null) && (data.link_expires_at === void 0 || typeof data.link_expires_at === "string" || data.link_expires_at === null);
1368
1979
  }
1369
1980
  function artifactsListSuccessFields(data) {
1370
- if (!isRecord$1(data)) return false;
1371
- return Array.isArray(data.artifacts) && data.artifacts.every((item) => {
1372
- if (!isRecord$1(item)) return false;
1373
- return typeof item.id === "string" && typeof item.title === "string" && typeof item.share_url === "string" && typeof item.visibility === "string" && (item.link_expires_at === void 0 || typeof item.link_expires_at === "string" || item.link_expires_at === null) && typeof item.updated_at === "string" && (typeof item.project_id === "string" || item.project_id === null) && (item.owner_email === void 0 || typeof item.owner_email === "string") && (item.artifact_kind === void 0 || typeof item.artifact_kind === "string");
1374
- }) && typeof data.limit === "number" && typeof data.has_more === "boolean" && (typeof data.next_cursor === "string" || data.next_cursor === null);
1981
+ return isContract(ARTIFACTS_LIST_RESPONSE_SCHEMA, data);
1375
1982
  }
1376
1983
  function deleteSuccessFields(data) {
1377
- if (!isRecord$1(data)) return false;
1378
- return typeof data.id === "string" && data.deleted === true;
1984
+ return isContract(ARTIFACT_DELETE_RESPONSE_SCHEMA, data);
1379
1985
  }
1380
1986
  function downloadManifestFields(data) {
1987
+ if (isContract(DOWNLOAD_MANIFEST_RESPONSE_SCHEMA, data)) return true;
1381
1988
  if (!isRecord$1(data)) return false;
1382
- return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && typeof data.artifact_kind === "string" && Array.isArray(data.files) && data.files.every(downloadManifestFileFields) && typeof data.total_size_bytes === "number" && (data.project_id === void 0 || typeof data.project_id === "string" || data.project_id === null);
1383
- }
1384
- function downloadManifestFileFields(data) {
1385
- if (!isRecord$1(data)) return false;
1386
- return typeof data.path === "string" && typeof data.size_bytes === "number" && typeof data.content_type === "string" && typeof data.sha256 === "string";
1989
+ return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && typeof data.artifact_kind === "string" && Array.isArray(data.files) && data.files.every((file) => {
1990
+ if (!isRecord$1(file)) return false;
1991
+ return typeof file.path === "string" && typeof file.size_bytes === "number" && typeof file.content_type === "string" && typeof file.sha256 === "string";
1992
+ }) && typeof data.total_size_bytes === "number" && (data.project_id === void 0 || typeof data.project_id === "string" || data.project_id === null);
1387
1993
  }
1388
1994
  //#endregion
1389
1995
  //#region src/api.ts
@@ -2978,9 +3584,10 @@ async function issueCliRefreshCredential(token, deviceName, deviceId, options, i
2978
3584
  baseUrl: baseUrlOf(options)
2979
3585
  });
2980
3586
  if (result.error) return { error: result.error };
2981
- if (typeof result.body?.refresh_token === "string" && typeof result.body.refresh_token_expires_at === "string") return {
2982
- refresh_token: result.body.refresh_token,
2983
- refresh_token_expires_at: result.body.refresh_token_expires_at
3587
+ const refresh = CLI_AUTH_REFRESH_CREDENTIALS_RESPONSE_SCHEMA.safeParse(result.body);
3588
+ if (refresh.success) return {
3589
+ refresh_token: refresh.data.refresh_token,
3590
+ refresh_token_expires_at: refresh.data.refresh_token_expires_at
2984
3591
  };
2985
3592
  return { error: validationError("Refresh credential response was invalid.", "Retry login. If this repeats, report the response shape.", "service_error") };
2986
3593
  }
@@ -3023,18 +3630,24 @@ function loginProjectSelector(value) {
3023
3630
  return { value: selector };
3024
3631
  }
3025
3632
  function isDeviceCodeResponse(body) {
3026
- if (!isRecord$1(body)) return false;
3027
- return typeof body.device_code === "string" && typeof body.user_code === "string" && typeof body.verification_uri === "string" && (typeof body.verification_uri_complete === "string" || body.verification_uri_complete === void 0) && typeof body.expires_in === "number" && typeof body.interval === "number";
3633
+ return DEVICE_CODE_RESPONSE_SCHEMA.safeParse(body).success;
3028
3634
  }
3029
3635
  function isDeviceTokenResponse(body) {
3030
- if (!isRecord$1(body)) return false;
3031
- return typeof body.access_token === "string" && typeof body.token_type === "string" && body.token_type.toLowerCase() === "bearer" && (typeof body.expires_in === "number" || body.expires_in === void 0);
3636
+ return DEVICE_TOKEN_RESPONSE_SCHEMA.safeParse(body).success;
3032
3637
  }
3033
3638
  function deviceTokenError(body) {
3639
+ const contracted = OAuthErrorResponseSchema.safeParse(body);
3640
+ if (contracted.success) return contracted.data.error;
3034
3641
  if (!isRecord$1(body)) return null;
3035
3642
  return typeof body.error === "string" ? body.error : null;
3036
3643
  }
3037
3644
  function whoamiProfile(body) {
3645
+ const contracted = CliWhoamiResponseSchema.safeParse(body);
3646
+ if (contracted.success) return {
3647
+ email: contracted.data.user.email,
3648
+ workspace_id: contracted.data.workspace.id,
3649
+ hosted_domain: contracted.data.workspace.hosted_domain
3650
+ };
3038
3651
  const record = isRecord$1(body) ? body : null;
3039
3652
  const user = record && isRecord$1(record.user) ? record.user : null;
3040
3653
  const workspace = record && isRecord$1(record.workspace) ? record.workspace : null;
@@ -3165,25 +3778,28 @@ async function refreshStoredProfileSession(profile, refreshToken, options) {
3165
3778
  error: mapApiError(response.status, body, { baseUrl: baseUrlOf(options) })
3166
3779
  };
3167
3780
  }
3168
- if (typeof body?.access_token !== "string" || body.access_token.length === 0 || body.token_type?.toLowerCase() !== "bearer" || typeof body.expires_at !== "string" || typeof body.refresh_token !== "string" || !body.refresh_token || typeof body.refresh_token_expires_at !== "string") return {
3781
+ const refreshResponse = CLI_AUTH_REFRESH_RESPONSE_SCHEMA.safeParse(body);
3782
+ if (!refreshResponse.success || refreshResponse.data.token_type.toLowerCase() !== "bearer") return {
3169
3783
  ok: false,
3170
3784
  error: validationError("Refresh response was invalid.", "Run login again. If this repeats, report the response shape.", "service_error")
3171
3785
  };
3172
3786
  const { pending_rotation_id: _completedRotation, ...persistedCredential } = stored.credential;
3787
+ const rotatingResponse = "refresh_token" in refreshResponse.data ? refreshResponse.data : null;
3788
+ const nextRefreshToken = rotatingResponse ? rotatingResponse.refresh_token : stored.credential.refresh_token;
3173
3789
  if (!(await saveProfileSessionCredential(profile, {
3174
3790
  ...persistedCredential,
3175
3791
  kind: "session",
3176
- session_token: body.access_token,
3177
- refresh_token: body.refresh_token,
3178
- expires_at: body.expires_at,
3179
- refresh_credential_expires_at: body.refresh_token_expires_at
3792
+ session_token: refreshResponse.data.access_token,
3793
+ refresh_token: nextRefreshToken,
3794
+ expires_at: refreshResponse.data.expires_at,
3795
+ ...rotatingResponse ? { refresh_credential_expires_at: rotatingResponse.refresh_token_expires_at } : {}
3180
3796
  }, options)).ok) return {
3181
3797
  ok: false,
3182
3798
  error: tokenStoreUnavailableError(profile, "store_operation_failed")
3183
3799
  };
3184
3800
  return {
3185
3801
  ok: true,
3186
- token: body.access_token
3802
+ token: refreshResponse.data.access_token
3187
3803
  };
3188
3804
  }
3189
3805
  async function handleJsonPendingAuth(command, credential, options, mode, rerun) {
@@ -4255,7 +4871,8 @@ function createPreviewStore(annotationsPath) {
4255
4871
  async function fetchProjects(token, options, init, errorOptions = {}) {
4256
4872
  const result = await apiGet("/api/cli/projects", token, options, init, errorOptions);
4257
4873
  if (result.error) return { error: result.error };
4258
- return { projects: (Array.isArray(result.body?.projects) ? result.body.projects : []).filter(isRecord$1).flatMap((project) => {
4874
+ const contracted = PROJECTS_LIST_RESPONSE_SCHEMA.safeParse(result.body);
4875
+ return { projects: (contracted.success ? contracted.data.projects : isRecord$1(result.body) && Array.isArray(result.body.projects) ? result.body.projects : []).filter(isRecord$1).flatMap((project) => {
4259
4876
  const id = configString(project.id);
4260
4877
  if (!id) return [];
4261
4878
  return [{
@@ -4323,7 +4940,9 @@ async function runProjectsCreate(parsed, mode) {
4323
4940
  return created.error ? { error: created.error } : { data: created.body };
4324
4941
  });
4325
4942
  if (result.error) return writeFailure(command, result.error, mode, 1);
4326
- const project = isRecord$1(result.data?.project) ? result.data.project : null;
4943
+ const contracted = PROJECT_CREATE_RESPONSE_SCHEMA.safeParse(result.data);
4944
+ const rawProject = isRecord$1(result.data) ? result.data.project : void 0;
4945
+ const project = contracted.success ? contracted.data.project : isRecord$1(rawProject) ? rawProject : null;
4327
4946
  const id = configString(project?.id);
4328
4947
  if (!id) return writeFailure(command, serviceError("Project create succeeded but no project id was returned."), mode, 1);
4329
4948
  writeSuccess(command, {
@@ -4411,6 +5030,11 @@ function normalizedEmailOptions$1(value) {
4411
5030
  return { values };
4412
5031
  }
4413
5032
  function parseProjectsEditData(body) {
5033
+ const contracted = PROJECT_EDIT_RESPONSE_SCHEMA.safeParse(body);
5034
+ if (contracted.success) return {
5035
+ project: contracted.data.project,
5036
+ audience: contracted.data.audience
5037
+ };
4414
5038
  if (!isRecord$1(body) || !isRecord$1(body.project)) return null;
4415
5039
  const { project } = body;
4416
5040
  if (typeof project.id !== "string" || typeof project.archived !== "boolean" || !Array.isArray(body.audience) || body.audience.some((email) => typeof email !== "string")) return null;
@@ -4441,20 +5065,25 @@ async function postShareUpload(args, baseUrl, fallbackKind) {
4441
5065
  if ("networkError" in response) return { error: networkError(response.networkError) };
4442
5066
  const body = await readJson(response);
4443
5067
  if (!response.ok) return { error: mapApiError(response.status, body, args.errorOptions) };
4444
- const id = body?.id ?? null;
4445
- const url = body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null);
4446
- const warnings = Array.isArray(body?.warnings) ? body.warnings.flatMap((warning) => warning?.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [{
4447
- code: "slack_reauthorization_required",
4448
- message: warning.message
4449
- }] : []) : [];
5068
+ const contractBody = isContract(ARTIFACT_UPLOAD_RESPONSE_SCHEMA, body) ? body : null;
5069
+ const recordBody = isRecord$1(body) ? body : null;
5070
+ const id = contractBody?.id ?? (typeof recordBody?.id === "string" ? recordBody.id : null);
5071
+ const url = contractBody?.shareUrl ?? (typeof recordBody?.shareUrl === "string" ? recordBody.shareUrl : id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null);
5072
+ const warnings = contractBody?.warnings ? contractBody.warnings : Array.isArray(recordBody?.warnings) ? recordBody.warnings.flatMap((warning) => {
5073
+ if (!isRecord$1(warning)) return [];
5074
+ return warning.code === "slack_reauthorization_required" && typeof warning.message === "string" ? [{
5075
+ code: "slack_reauthorization_required",
5076
+ message: warning.message
5077
+ }] : [];
5078
+ }) : [];
4450
5079
  return { body: {
4451
5080
  id,
4452
5081
  url,
4453
- versionId: body?.versionId ?? null,
4454
- artifactKind: body?.artifactKind ?? fallbackKind,
4455
- visibility: body?.visibility ?? null,
4456
- linkExpiresAt: body?.link_expires_at ?? null,
4457
- created: body?.created ?? true,
5082
+ versionId: contractBody?.versionId ?? (typeof recordBody?.versionId === "string" ? recordBody.versionId : null),
5083
+ artifactKind: contractBody?.artifactKind ?? (typeof recordBody?.artifactKind === "string" ? recordBody.artifactKind : fallbackKind),
5084
+ visibility: contractBody?.visibility ?? (typeof recordBody?.visibility === "string" ? recordBody.visibility : null),
5085
+ linkExpiresAt: contractBody?.link_expires_at ?? (typeof recordBody?.link_expires_at === "string" || recordBody?.link_expires_at === null ? recordBody.link_expires_at : null),
5086
+ created: contractBody?.created ?? (typeof recordBody?.created === "boolean" ? recordBody.created : true),
4458
5087
  warnings
4459
5088
  } };
4460
5089
  }
@@ -4542,7 +5171,7 @@ const PREVIEW_MESSAGES = {
4542
5171
  "preview.shareDialog.shareFailed": "Sharing failed. Try again in a moment.",
4543
5172
  "preview.shareDialog.errorTokenInvalid": "The saved credential is no longer valid. Log in again, then reopen this dialog.",
4544
5173
  "preview.shareDialog.errorTokenInvalidExplicit": "The token supplied to this preview is invalid or expired. Stop the preview and start it again with a valid token.",
4545
- "preview.shareDialog.errorUploadNotAllowed": "Sharing is temporarily unavailable. Try again later.",
5174
+ "preview.shareDialog.errorSelfUploadDisabled": "This account cannot upload its own files. Sign in with Google or Microsoft to share files.",
4546
5175
  "preview.shareDialog.errorWorkspaceAccessRevoked": "This account no longer has access to that workspace.",
4547
5176
  "preview.shareDialog.errorStorageLimit": "The workspace has reached its storage limit.",
4548
5177
  "preview.shareDialog.snapshotFailed": "The file could not be read, so sharing is disabled. Reopen this dialog once it is available."
@@ -4628,7 +5257,7 @@ const PREVIEW_MESSAGES = {
4628
5257
  "preview.shareDialog.shareFailed": "共有に失敗しました。少し時間をおいて再試行してください。",
4629
5258
  "preview.shareDialog.errorTokenInvalid": "保存された認証情報が無効になりました。ログインし直してから、このダイアログを開き直してください。",
4630
5259
  "preview.shareDialog.errorTokenInvalidExplicit": "このプレビューに渡されたトークンが無効か期限切れです。プレビューを終了し、有効なトークンで起動し直してください。",
4631
- "preview.shareDialog.errorUploadNotAllowed": "現在共有できません。時間をおいて再試行してください。",
5260
+ "preview.shareDialog.errorSelfUploadDisabled": "このアカウントではファイルをアップロードできません。Google または Microsoft でログインして共有してください。",
4632
5261
  "preview.shareDialog.errorWorkspaceAccessRevoked": "このアカウントはそのワークスペースにアクセスできなくなりました。",
4633
5262
  "preview.shareDialog.errorStorageLimit": "ワークスペースの保存容量の上限に達しています。",
4634
5263
  "preview.shareDialog.snapshotFailed": "ファイルを読み取れないため共有できません。読み取れるようになってからこのダイアログを開き直してください。"
@@ -5320,7 +5949,7 @@ function renderPage(options) {
5320
5949
  var SHARE_ERROR_KEYS = {
5321
5950
  token_invalid: 'errorTokenInvalid',
5322
5951
  bot_token_invalid: 'errorTokenInvalid',
5323
- upload_not_allowed: 'errorUploadNotAllowed',
5952
+ self_upload_disabled: 'errorSelfUploadDisabled',
5324
5953
  workspace_access_revoked: 'errorWorkspaceAccessRevoked',
5325
5954
  storage_limit_exceeded: 'errorStorageLimit',
5326
5955
  };
@@ -5525,6 +6154,7 @@ const VIOLATION_REPORTER_TAG = `<script>${`(function () {
5525
6154
  var hasAttribute = Function.prototype.call.bind(Element.prototype.hasAttribute);
5526
6155
  var documentToken = '';
5527
6156
  var readyChallenge = '';
6157
+ var externalLinkPolicyMode = 'parent';
5528
6158
  var pendingLinkClicks = new WeakMap();
5529
6159
  function trusted(event) {
5530
6160
  try {
@@ -5752,7 +6382,7 @@ const VIOLATION_REPORTER_TAG = `<script>${`(function () {
5752
6382
  if (!pending) return;
5753
6383
  weakMapDelete(pendingLinkClicks, event);
5754
6384
  if (pending.artifactPrevented) return;
5755
- if (pending.openExternally) {
6385
+ if (pending.openExternally && externalLinkPolicyMode === 'direct') {
5756
6386
  openExternalLink(pending.href);
5757
6387
  return;
5758
6388
  }
@@ -7009,6 +7639,11 @@ const VIOLATION_REPORTER_TAG = `<script>${`(function () {
7009
7639
  onReadyCheck(event);
7010
7640
  textAnchorsEnabled = data.textAnchorsEnabled === true;
7011
7641
  setCommentLabels(data.commentLabels);
7642
+ } else if (
7643
+ data.kind === 'external-link-policy' &&
7644
+ (data.mode === 'parent' || data.mode === 'direct')
7645
+ ) {
7646
+ externalLinkPolicyMode = data.mode;
7012
7647
  } else if (data.kind === 'comment-highlights') {
7013
7648
  textAnchorsEnabled = data.textAnchorsEnabled === true;
7014
7649
  setCommentLabels(data.commentLabels);
@@ -7105,8 +7740,8 @@ function injectReadyReporter(html) {
7105
7740
  return `${html.slice(0, insertionPoint)}${VIOLATION_REPORTER_TAG}${html.slice(insertionPoint)}`;
7106
7741
  }
7107
7742
  //#endregion
7108
- //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.13_react@19.2.8/node_modules/@tanstack/markdown/dist/utils.js
7109
- const htmlEscapes = {
7743
+ //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.14_react@19.3.0/node_modules/@tanstack/markdown/dist/utils.js
7744
+ const htmlEscapes$1 = {
7110
7745
  "&": "&amp;",
7111
7746
  "<": "&lt;",
7112
7747
  ">": "&gt;",
@@ -7117,7 +7752,7 @@ function normalizeInput(value) {
7117
7752
  return value.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
7118
7753
  }
7119
7754
  function escapeHtml$5(value) {
7120
- return value.replace(/[&<>"']/g, (char) => htmlEscapes[char]);
7755
+ return value.replace(/[&<>"']/g, (char) => htmlEscapes$1[char]);
7121
7756
  }
7122
7757
  function escapeAttr(value) {
7123
7758
  return escapeHtml$5(value).replace(/`/g, "&#96;");
@@ -7137,41 +7772,58 @@ function plainText$1(nodes) {
7137
7772
  else if (node.type === "image") value += node.alt;
7138
7773
  return value;
7139
7774
  }
7140
- function createSlugger() {
7775
+ function createSlugger(normalize = headingSlug) {
7141
7776
  const seen = /* @__PURE__ */ new Map();
7142
7777
  return (value) => {
7143
- const base = value.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/&[a-z0-9#]+;/gi, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "section";
7144
- const count = seen.get(base) ?? 0;
7145
- seen.set(base, count + 1);
7146
- return count === 0 ? base : `${base}-${count + 1}`;
7778
+ const base = normalize(value);
7779
+ let count = seen.get(base) ?? 1;
7780
+ let id = base;
7781
+ while (seen.has(id)) id = `${base}-${++count}`;
7782
+ seen.set(base, count);
7783
+ seen.set(id, 1);
7784
+ return id;
7147
7785
  };
7148
7786
  }
7787
+ function headingSlug(value) {
7788
+ return value.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/&[a-z0-9#]+;/gi, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "section";
7789
+ }
7149
7790
  function sanitizeUrl(value) {
7150
- const trimmed = value.trim().replace(/[\u0000-\u001F\u007F\s]+/g, "");
7151
- if (!trimmed) return "";
7152
- if (/^(#|\/|\.\/|\.\.\/)/.test(trimmed)) return trimmed;
7153
- if (/^(https?:|mailto:|tel:)/i.test(trimmed)) return trimmed;
7154
- if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed)) return "";
7155
- return trimmed;
7791
+ const trimmed = value.replace(/[\u0000-\u001F\u007F\s]+/g, "");
7792
+ return /^(?!https?:|mailto:|tel:)[a-z][a-z0-9+.-]*:/i.test(trimmed) ? "" : trimmed;
7793
+ }
7794
+ function parseDestination(value) {
7795
+ const match = value.match(/^(?:<([^<>\n]*)>|([^<>\s]*?))(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);
7796
+ if (!match) return void 0;
7797
+ const href = match[1] ?? match[2];
7798
+ const title = match[3] ?? match[4] ?? match[5];
7799
+ return {
7800
+ href: href.replace(/\\([!-/:-@\[-`{-~])/g, "$1"),
7801
+ ...title ? { title } : {}
7802
+ };
7156
7803
  }
7157
7804
  function normalizeReferenceLabel(value) {
7158
- return value.trim().toLowerCase();
7805
+ return value.trim().replace(/\s+/g, " ").toLowerCase();
7159
7806
  }
7160
7807
  function footnoteId(label) {
7161
- return normalizeReferenceLabel(label).replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
7808
+ return normalizeReferenceLabel(label).replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "footnote";
7809
+ }
7810
+ function footnoteReferenceId(id, index = 1) {
7811
+ return index > 1 ? `${id}-${index}` : id;
7162
7812
  }
7163
7813
  //#endregion
7164
- //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.13_react@19.2.8/node_modules/@tanstack/markdown/dist/inline.js
7814
+ //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.14_react@19.3.0/node_modules/@tanstack/markdown/dist/inline.js
7165
7815
  function parseInline(value, options = {}) {
7166
- let result = mergeText(parseInlineRaw(value, options));
7816
+ let result = parseInlineRaw(value, options);
7167
7817
  for (const extension of options.extensions ?? []) result = extension.transformInline?.(result, { options }) ?? result;
7168
7818
  return result;
7169
7819
  }
7170
7820
  const maxInlineDepth = 32;
7171
7821
  const scansPerCharacter = 16;
7822
+ const inlineMarker = /[\\`!\[_*~<]/g;
7172
7823
  function parseInlineRaw(value, options, budget = {
7173
7824
  scans: Math.max(value.length * scansPerCharacter, 1024),
7174
- depth: 0
7825
+ depth: 0,
7826
+ links: 0
7175
7827
  }) {
7176
7828
  if (budget.depth >= maxInlineDepth) return value ? [{
7177
7829
  type: "text",
@@ -7200,7 +7852,7 @@ function parseInlineRaw(value, options, budget = {
7200
7852
  index += 2;
7201
7853
  continue;
7202
7854
  }
7203
- if (next && /[\\`*_[\]{}()#+\-.!|~<>]/.test(next)) {
7855
+ if (next && /[!-/:-@\[-`{-~]/.test(next)) {
7204
7856
  text += next;
7205
7857
  index += 2;
7206
7858
  continue;
@@ -7213,7 +7865,7 @@ function parseInlineRaw(value, options, budget = {
7213
7865
  pushText();
7214
7866
  nodes.push({
7215
7867
  type: "inlineCode",
7216
- value: value.slice(index + tickCount, close).replace(/\s+/g, " ").trim()
7868
+ value: value.slice(index + tickCount, close).replace(/\n/g, " ").replace(/^ (?! *$)(.*) $/s, "$1")
7217
7869
  });
7218
7870
  index = close + tickCount;
7219
7871
  continue;
@@ -7222,40 +7874,46 @@ function parseInlineRaw(value, options, budget = {
7222
7874
  index += tickCount;
7223
7875
  continue;
7224
7876
  }
7225
- if (char === "!" && next === "[") {
7226
- const parsed = parseLinkish(value, index + 1, options, budget);
7227
- if (parsed) {
7228
- pushText();
7229
- nodes.push({
7230
- type: "image",
7231
- src: sanitizeUrl(parsed.href),
7232
- alt: textFromMarkdown(parsed.label, budget),
7233
- ...parsed.title ? { title: parsed.title } : {}
7234
- });
7235
- index = parsed.end;
7236
- continue;
7237
- }
7238
- }
7239
- if (char === "[") {
7240
- const footnote = parseFootnoteReference(value, index, options, budget);
7877
+ if (char === "[" || char === "!" && next === "[") {
7878
+ const image = char === "!";
7879
+ const footnote = next === "^" && parseFootnoteReference(value, index, options, budget);
7241
7880
  if (footnote) {
7242
7881
  pushText();
7243
7882
  nodes.push(footnote.node);
7883
+ budget.links++;
7244
7884
  index = footnote.end;
7245
7885
  continue;
7246
7886
  }
7247
- const parsed = parseLinkish(value, index, options, budget);
7887
+ const parsed = parseLinkish(value, index + Number(image), options, budget);
7248
7888
  if (parsed) {
7889
+ const links = budget.links;
7890
+ const children = parseInlineRaw(parsed.label, image ? options.references ? { references: options.references } : {} : options, budget);
7891
+ const nested = !image && budget.links !== links;
7249
7892
  const href = sanitizeUrl(parsed.href);
7250
- pushText();
7251
- if (href) nodes.push({
7252
- type: "link",
7253
- href,
7254
- ...parsed.title ? { title: parsed.title } : {},
7255
- children: parseInlineRaw(parsed.label, options, budget)
7256
- });
7257
- else nodes.push(...parseInlineRaw(parsed.label, options, budget));
7258
- index = parsed.end;
7893
+ if (image || !nested && (href || !parsed.href)) {
7894
+ pushText();
7895
+ nodes.push({
7896
+ ...image ? {
7897
+ type: "image",
7898
+ src: href,
7899
+ alt: plainText$1(children)
7900
+ } : {
7901
+ type: "link",
7902
+ href,
7903
+ children
7904
+ },
7905
+ ...parsed.title ? { title: parsed.title } : {}
7906
+ });
7907
+ } else {
7908
+ if (nested) text += "[";
7909
+ for (const child of children) if (child.type === "text") text += child.value;
7910
+ else {
7911
+ pushText();
7912
+ nodes.push(child);
7913
+ }
7914
+ }
7915
+ budget.links = image ? links : budget.links + 1;
7916
+ index = nested ? index + parsed.label.length + 1 : parsed.end;
7259
7917
  continue;
7260
7918
  }
7261
7919
  }
@@ -7271,66 +7929,28 @@ function parseInlineRaw(value, options, budget = {
7271
7929
  continue;
7272
7930
  }
7273
7931
  }
7274
- if (char === "*" && next === "*" || char === "_" && next === "_") {
7275
- const close = char === "_" && !canUseUnderscore(value, index, 2, true) ? -1 : findDelimiter(value, index + 2, char + char, budget);
7276
- if (close !== -1) {
7277
- pushText();
7278
- nodes.push({
7279
- type: "strong",
7280
- children: parseInlineRaw(value.slice(index + 2, close), options, budget)
7281
- });
7282
- index = close + 2;
7283
- continue;
7284
- }
7285
- text += char + next;
7286
- index += 2;
7287
- continue;
7288
- }
7289
7932
  if (char === "~" && next === "~" && value[index + 2] === "~") {
7290
7933
  const run = countRun(value, index, "~");
7291
7934
  text += value.slice(index, index + run);
7292
7935
  index += run;
7293
7936
  continue;
7294
7937
  }
7295
- if (char === "~" && next === "~") {
7296
- const close = findDelimiter(value, index + 2, "~~", budget);
7938
+ if (char === "*" || char === "_" || char === "~") {
7939
+ const size = next === char ? 2 : 1;
7940
+ const close = char === "_" && !canUseUnderscore(value, index, size, true) ? -1 : findDelimiter(value, index + size, char.repeat(size), budget);
7297
7941
  if (close !== -1) {
7298
7942
  pushText();
7299
7943
  nodes.push({
7300
- type: "strike",
7301
- children: parseInlineRaw(value.slice(index + 2, close), options, budget)
7944
+ type: char === "~" ? "strike" : size === 2 ? "strong" : "emphasis",
7945
+ children: parseInlineRaw(value.slice(index + size, close), options, budget)
7302
7946
  });
7303
- index = close + 2;
7304
- continue;
7947
+ index = close + size;
7948
+ } else {
7949
+ text += char.repeat(size);
7950
+ index += size;
7305
7951
  }
7306
- text += "~~";
7307
- index += 2;
7308
7952
  continue;
7309
7953
  }
7310
- if (char === "~") {
7311
- const close = findSingleTildeDelimiter(value, index + 1, budget);
7312
- if (close !== -1) {
7313
- pushText();
7314
- nodes.push({
7315
- type: "strike",
7316
- children: parseInlineRaw(value.slice(index + 1, close), options, budget)
7317
- });
7318
- index = close + 1;
7319
- continue;
7320
- }
7321
- }
7322
- if (char === "*" || char === "_") {
7323
- const close = char === "_" && !canUseUnderscore(value, index, 1, true) ? -1 : findDelimiter(value, index + 1, char, budget);
7324
- if (close !== -1) {
7325
- pushText();
7326
- nodes.push({
7327
- type: "emphasis",
7328
- children: parseInlineRaw(value.slice(index + 1, close), options, budget)
7329
- });
7330
- index = close + 1;
7331
- continue;
7332
- }
7333
- }
7334
7954
  if (char === "<" && options.allowHtml) {
7335
7955
  const close = findCharacter(value, index + 1, ">", budget);
7336
7956
  if (close !== -1 && isInlineHtml(value.slice(index, close + 1))) {
@@ -7343,32 +7963,30 @@ function parseInlineRaw(value, options, budget = {
7343
7963
  continue;
7344
7964
  }
7345
7965
  }
7346
- text += char;
7347
- index++;
7966
+ inlineMarker.lastIndex = index + 1;
7967
+ const end = budget.scans > 0 ? inlineMarker.exec(value)?.index ?? value.length : value.indexOf("\\", index + 1);
7968
+ text += value.slice(index, end < 0 ? value.length : end);
7969
+ index = end < 0 ? value.length : end;
7348
7970
  }
7349
7971
  pushText();
7350
7972
  budget.depth--;
7351
7973
  return nodes;
7352
7974
  }
7353
7975
  function parseFootnoteReference(value, open, options, budget) {
7354
- if (value[open + 1] !== "^") return void 0;
7355
7976
  const close = findCharacter(value, open + 2, "]", budget);
7356
7977
  if (close === -1) return void 0;
7357
7978
  const key = normalizeReferenceLabel(value.slice(open + 2, close));
7358
7979
  const definition = options.footnotes?.[key];
7359
7980
  if (!definition || !options.footnoteOrder) return void 0;
7360
- let orderIndex = options.footnoteOrder.indexOf(key);
7361
- if (orderIndex === -1) {
7362
- options.footnoteOrder.push(key);
7363
- orderIndex = options.footnoteOrder.length - 1;
7364
- }
7981
+ let number = options.footnoteOrder.indexOf(key) + 1;
7982
+ if (!number) number = options.footnoteOrder.push(key);
7365
7983
  const referenceIndex = (options.footnoteCounts?.[key] ?? 0) + 1;
7366
7984
  if (options.footnoteCounts) options.footnoteCounts[key] = referenceIndex;
7367
7985
  return {
7368
7986
  node: {
7369
7987
  type: "footnoteReference",
7370
- id: definition.id ?? (footnoteId(definition.label) || "footnote"),
7371
- number: orderIndex + 1,
7988
+ id: definition.id ?? footnoteId(definition.label),
7989
+ number,
7372
7990
  ...referenceIndex > 1 ? { referenceIndex } : {}
7373
7991
  },
7374
7992
  end: close + 1
@@ -7378,58 +7996,37 @@ function parseLinkish(value, open, options, budget) {
7378
7996
  const closeBracket = findBalanced(value, open, "[", "]", budget);
7379
7997
  if (closeBracket === -1) return void 0;
7380
7998
  const label = value.slice(open + 1, closeBracket);
7381
- if (value[closeBracket + 1] === "(") {
7382
- const closeParen = findBalanced(value, closeBracket + 1, "(", ")", budget);
7999
+ let end = closeBracket + 1;
8000
+ let definition;
8001
+ if (value[end] === "(") {
8002
+ const closeParen = findBalanced(value, end, "(", ")", budget);
7383
8003
  if (closeParen === -1) return void 0;
7384
- const parsed = parseDestination(value.slice(closeBracket + 2, closeParen).trim());
7385
- if (!parsed) return void 0;
7386
- return {
7387
- label,
7388
- href: parsed.href,
7389
- ...parsed.title ? { title: parsed.title } : {},
7390
- end: closeParen + 1
7391
- };
7392
- }
7393
- if (value[closeBracket + 1] === "[") {
7394
- const closeReference = findBalanced(value, closeBracket + 1, "[", "]", budget);
8004
+ definition = parseDestination(value.slice(end + 1, closeParen).trim());
8005
+ end = closeParen + 1;
8006
+ } else if (value[end] === "[") {
8007
+ const closeReference = findBalanced(value, end, "[", "]", budget);
7395
8008
  if (closeReference === -1) return void 0;
7396
- const referenceLabel = value.slice(closeBracket + 2, closeReference);
7397
- const definition = options.references?.[normalizeReferenceLabel(referenceLabel || label)];
7398
- if (!definition) return void 0;
7399
- return {
7400
- label,
7401
- href: definition.href,
7402
- ...definition.title ? { title: definition.title } : {},
7403
- end: closeReference + 1
7404
- };
7405
- }
7406
- const definition = options.references?.[normalizeReferenceLabel(label)];
8009
+ definition = options.references?.[normalizeReferenceLabel(value.slice(end + 1, closeReference) || label)];
8010
+ end = closeReference + 1;
8011
+ } else definition = options.references?.[normalizeReferenceLabel(label)];
7407
8012
  if (definition) return {
8013
+ ...definition,
7408
8014
  label,
7409
- href: definition.href,
7410
- ...definition.title ? { title: definition.title } : {},
7411
- end: closeBracket + 1
8015
+ end
7412
8016
  };
7413
8017
  }
7414
8018
  function isInlineHtml(value) {
7415
- if (/^<!--(?:[\s\S]*--|-?)>$/.test(value)) return true;
7416
- if (/^<\?[\s\S]*\?>$/.test(value) || /^<![A-Z][\s\S]*>$/.test(value) || /^<!\[CDATA\[[\s\S]*\]\]>$/.test(value)) return true;
7417
- if (/^<\/[A-Za-z][\w:-]*\s*>$/.test(value)) return true;
7418
- return /^<[A-Za-z][\w:-]*(?:\s+[A-Za-z_:][\w:.-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?>$/.test(value);
7419
- }
7420
- function parseDestination(value) {
7421
- const match = value.match(/^(\S+)(?:\s+["']([^"']*)["'])?$/);
7422
- if (!match) return { href: value };
7423
- return {
7424
- href: match[1].replace(/^<|>$/g, ""),
7425
- ...match[2] ? { title: match[2] } : {}
7426
- };
8019
+ return /^<(?:!--(?:[\s\S]*--|-?)|\?[\s\S]*\?|![A-Z][\s\S]*|!\[CDATA\[[\s\S]*\]\]|\/[A-Za-z][\w:-]*\s*|[A-Za-z][\w:-]*(?:\s+[A-Za-z_:][\w:.-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?)>$/.test(value);
7427
8020
  }
7428
8021
  function findBalanced(value, openIndex, open, close, budget) {
8022
+ if (findCharacter(value, openIndex + 1, close, budget) === -1) return -1;
7429
8023
  let depth = 0;
7430
8024
  for (let index = openIndex; index < value.length; index++) {
7431
- if (!takeScan(budget)) return -1;
7432
- if (value[index - 1] === "\\") continue;
8025
+ if (--budget.scans < 0) return -1;
8026
+ if (value[index] === "\\") {
8027
+ index++;
8028
+ continue;
8029
+ }
7433
8030
  if (value[index] === open) depth++;
7434
8031
  if (value[index] === close) {
7435
8032
  depth--;
@@ -7441,92 +8038,58 @@ function findBalanced(value, openIndex, open, close, budget) {
7441
8038
  function countRun(value, index, char, budget) {
7442
8039
  let count = 0;
7443
8040
  while (value[index + count] === char) {
7444
- if (budget && !takeScan(budget)) break;
8041
+ if (budget && --budget.scans < 0) break;
7445
8042
  count++;
7446
8043
  }
7447
8044
  return count;
7448
8045
  }
7449
8046
  function findClosingRun(value, start, char, count, budget) {
7450
- for (let index = start; index < value.length; index++) {
7451
- if (!takeScan(budget)) return -1;
7452
- if (value[index] !== char) continue;
7453
- if (countRun(value, index, char, budget) >= count) return index;
8047
+ let index = start;
8048
+ while ((index = findCharacter(value, index, char, budget)) !== -1) {
8049
+ const size = countRun(value, index, char, budget);
8050
+ if (size === count) return index;
8051
+ index += size;
7454
8052
  }
7455
8053
  return -1;
7456
8054
  }
7457
8055
  function findDelimiter(value, start, delimiter, budget) {
8056
+ if (delimiter === "~" && /[\s\d]/.test(value[start] ?? "")) return -1;
7458
8057
  for (let index = start; index < value.length; index++) {
7459
- if (!takeScan(budget)) return -1;
7460
- if (value[index - 1] === "\\") continue;
8058
+ if (--budget.scans < 0) return -1;
8059
+ if (value[index] === "\\") {
8060
+ index++;
8061
+ continue;
8062
+ }
7461
8063
  if (!value.startsWith(delimiter, index)) continue;
7462
- if (value[index + 1] === delimiter) {
7463
- const close = findDelimiter(value, index + 2, delimiter + delimiter, budget);
7464
- if (close > index + 2) {
7465
- index = close + 1;
8064
+ if (delimiter[0] === "~") {
8065
+ if (value[index - 1] === "~" || value[index + delimiter.length] === "~") continue;
8066
+ if (delimiter === "~" && /\s/.test(value[index - 1] ?? "")) return -1;
8067
+ } else if (value[index + 1] === delimiter) {
8068
+ const size = countRun(value, index, delimiter, budget);
8069
+ const close = findDelimiter(value, index + size, delimiter.repeat(size), budget);
8070
+ if (close > index + size) {
8071
+ index = close + size - 1;
7466
8072
  continue;
7467
8073
  }
7468
8074
  }
7469
- if (delimiter === "~~" && (value[index - 1] === "~" || value[index + 2] === "~")) continue;
7470
8075
  if (delimiter[0] === "_" && !canUseUnderscore(value, index, delimiter.length, false)) continue;
7471
8076
  return index;
7472
8077
  }
7473
8078
  return -1;
7474
8079
  }
7475
- function findSingleTildeDelimiter(value, start, budget) {
7476
- if (isWhitespace(value[start] ?? "") || /\d/.test(value[start] ?? "")) return -1;
7477
- for (let index = start; index < value.length; index++) {
7478
- if (!takeScan(budget)) return -1;
7479
- if (value[index - 1] === "\\") continue;
7480
- if (value[index] !== "~") continue;
7481
- if (value[index - 1] === "~") continue;
7482
- if (value[index + 1] === "~") continue;
7483
- if (isWhitespace(value[index - 1] ?? "")) return -1;
7484
- return index;
7485
- }
7486
- return -1;
7487
- }
7488
8080
  function findCharacter(value, start, character, budget) {
7489
- for (let index = start; index < value.length; index++) {
7490
- if (!takeScan(budget)) return -1;
7491
- if (value[index] === character) return index;
7492
- }
7493
- return -1;
7494
- }
7495
- function takeScan(budget) {
7496
- if (budget.scans <= 0) return false;
7497
- budget.scans--;
7498
- return true;
8081
+ if (budget.scans <= 0) return -1;
8082
+ const index = value.indexOf(character, start);
8083
+ budget.scans -= (index < 0 ? value.length : index + 1) - start;
8084
+ return budget.scans < 0 ? -1 : index;
7499
8085
  }
7500
8086
  function canUseUnderscore(value, index, size, opening) {
7501
- const before = value[index - 1];
7502
- const after = value[index + size];
7503
- const leftFlanking = !isDelimiterWhitespace(after) && (!isPunctuation(after) || isDelimiterWhitespace(before) || isPunctuation(before));
7504
- const rightFlanking = !isDelimiterWhitespace(before) && (!isPunctuation(before) || isDelimiterWhitespace(after) || isPunctuation(after));
7505
- return opening ? leftFlanking && (!rightFlanking || isPunctuation(before)) : rightFlanking && (!leftFlanking || isPunctuation(after));
7506
- }
7507
- function isDelimiterWhitespace(value) {
7508
- return value === void 0 || /\s/.test(value);
7509
- }
7510
- function isPunctuation(value) {
7511
- return value !== void 0 && /[^\p{L}\p{N}\s]/u.test(value);
7512
- }
7513
- function isWhitespace(value) {
7514
- return /\s/.test(value);
7515
- }
7516
- function textFromMarkdown(value, budget) {
7517
- return parseInlineRaw(value, {}, budget).map((node) => node.type === "text" || node.type === "inlineCode" ? node.value : "").join("");
7518
- }
7519
- function mergeText(nodes) {
7520
- const result = [];
7521
- for (const node of nodes) {
7522
- const previous = result.at(-1);
7523
- if (previous?.type === "text" && node.type === "text") previous.value += node.value;
7524
- else result.push(node);
7525
- }
7526
- return result;
8087
+ const inside = value[opening ? index + size : index - 1];
8088
+ const outside = value[opening ? index - 1 : index + size];
8089
+ return inside !== void 0 && !/\s/.test(inside) && (outside === void 0 || /[^\p{L}\p{N}]/u.test(outside));
7527
8090
  }
7528
8091
  //#endregion
7529
- //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.13_react@19.2.8/node_modules/@tanstack/markdown/dist/parser.js
8092
+ //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.14_react@19.3.0/node_modules/@tanstack/markdown/dist/parser.js
7530
8093
  const maxBlockDepth = 64;
7531
8094
  function parseMarkdown(markdown, options = {}) {
7532
8095
  const normalized = normalizeInput(markdown);
@@ -7555,8 +8118,9 @@ function parseMarkdown(markdown, options = {}) {
7555
8118
  footnoteCounts
7556
8119
  } : {}
7557
8120
  } : options;
7558
- const children = new BlockParser(lines, parseOptions, createSlugger()).parse();
7559
- if (hasFootnotes && footnoteOrder.length > 0) children.push(createFootnotesBlock(definitions.footnotes, footnoteOrder, parseOptions));
8121
+ const slugger = createSlugger();
8122
+ const children = new BlockParser(lines, parseOptions, slugger).parse();
8123
+ if (hasFootnotes && footnoteOrder.length > 0) children.push(createFootnotesBlock(definitions.footnotes, footnoteOrder, parseOptions, slugger));
7560
8124
  let document = frontmatter === void 0 ? {
7561
8125
  type: "root",
7562
8126
  children
@@ -7574,6 +8138,7 @@ var BlockParser = class BlockParser {
7574
8138
  slugger;
7575
8139
  budget;
7576
8140
  index = 0;
8141
+ loose = false;
7577
8142
  constructor(lines, options, slugger, budget = { depth: 0 }) {
7578
8143
  this.lines = lines;
7579
8144
  this.options = options;
@@ -7593,6 +8158,7 @@ var BlockParser = class BlockParser {
7593
8158
  const nodes = [];
7594
8159
  while (this.index < this.lines.length) {
7595
8160
  if (isBlank(this.current())) {
8161
+ if (nodes.length) this.loose = true;
7596
8162
  this.index++;
7597
8163
  continue;
7598
8164
  }
@@ -7627,22 +8193,19 @@ var BlockParser = class BlockParser {
7627
8193
  }
7628
8194
  }
7629
8195
  parseFence() {
7630
- const match = this.current().match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
8196
+ const match = this.current().match(/^( {0,3})(`{3,}|~{3,})(.*)$/);
7631
8197
  if (!match) return void 0;
7632
- const fence = match[1];
7633
- const marker = fence[0];
7634
- const fenceSize = fence.length;
7635
- const info = match[2].trim();
8198
+ const fence = match[2];
8199
+ const info = match[3].trim();
7636
8200
  const code = [];
7637
8201
  this.index++;
7638
8202
  while (this.index < this.lines.length) {
7639
8203
  const line = this.current();
7640
- const close = line.match(/^ {0,3}(`{3,}|~{3,})\s*$/);
7641
- if (close && close[1][0] === marker && close[1].length >= fenceSize) {
8204
+ if (line.match(/^ {0,3}(`{3,}|~{3,})\s*$/)?.[1].startsWith(fence)) {
7642
8205
  this.index++;
7643
8206
  break;
7644
8207
  }
7645
- code.push(line);
8208
+ code.push(stripIndent(line, match[1].length));
7646
8209
  this.index++;
7647
8210
  }
7648
8211
  return {
@@ -7680,14 +8243,12 @@ var BlockParser = class BlockParser {
7680
8243
  const quoted = [];
7681
8244
  while (this.index < this.lines.length) {
7682
8245
  const line = this.current();
7683
- if (isBlank(line)) {
7684
- quoted.push("");
7685
- this.index++;
7686
- continue;
7687
- }
7688
8246
  const match = line.match(/^ {0,3}>\s?(.*)$/);
7689
- if (!match) break;
7690
- quoted.push(match[1]);
8247
+ if (!match) {
8248
+ if (!isBlank(line)) break;
8249
+ this.loose = true;
8250
+ }
8251
+ quoted.push(match?.[1] ?? "");
7691
8252
  this.index++;
7692
8253
  }
7693
8254
  return {
@@ -7701,11 +8262,10 @@ var BlockParser = class BlockParser {
7701
8262
  const items = [];
7702
8263
  const ordered = first.ordered;
7703
8264
  const baseIndent = first.indent;
7704
- const start = ordered ? first.number : void 0;
7705
8265
  let loose = false;
7706
8266
  while (this.index < this.lines.length) {
7707
8267
  const marker = listMarker(this.current());
7708
- if (!marker || !sameListType(marker, first) || marker.indent !== baseIndent) break;
8268
+ if (!marker || marker.marker !== first.marker || marker.indent !== baseIndent) break;
7709
8269
  let firstLine = marker.content;
7710
8270
  const task = firstLine.match(/^\[([ xX])\]\s+(.*)$/);
7711
8271
  const checked = task ? task[1].toLowerCase() === "x" : void 0;
@@ -7723,15 +8283,13 @@ var BlockParser = class BlockParser {
7723
8283
  if (following === void 0) break;
7724
8284
  const followingMarker = listMarker(following);
7725
8285
  if (followingMarker?.indent === baseIndent) {
7726
- if (!sameListType(followingMarker, first)) break;
8286
+ if (followingMarker.marker !== first.marker) break;
7727
8287
  loose = true;
7728
8288
  this.index = nextIndex;
7729
8289
  break;
7730
8290
  }
7731
8291
  if (leadingSpaces(following) < marker.contentIndent) break;
7732
- loose = true;
7733
- itemLines.push("");
7734
- this.index = nextIndex;
8292
+ while (this.index < nextIndex) itemLines.push(stripIndent(this.lines[this.index++], marker.contentIndent));
7735
8293
  continue;
7736
8294
  }
7737
8295
  if (leadingSpaces(line) >= marker.contentIndent) {
@@ -7743,9 +8301,12 @@ var BlockParser = class BlockParser {
7743
8301
  itemLines.push(line.trimStart());
7744
8302
  this.index++;
7745
8303
  }
8304
+ const parser = new BlockParser(itemLines, this.options, this.slugger, this.budget);
8305
+ const children = parser.parse();
8306
+ loose ||= parser.loose;
7746
8307
  const item = {
7747
8308
  type: "listItem",
7748
- children: new BlockParser(itemLines, this.options, this.slugger, this.budget).parse()
8309
+ children
7749
8310
  };
7750
8311
  if (checked !== void 0) item.checked = checked;
7751
8312
  items.push(item);
@@ -7753,7 +8314,7 @@ var BlockParser = class BlockParser {
7753
8314
  return {
7754
8315
  type: "list",
7755
8316
  ordered,
7756
- ...ordered && start !== void 0 ? { start } : {},
8317
+ ...ordered && { start: first.number },
7757
8318
  ...loose && { loose: true },
7758
8319
  items
7759
8320
  };
@@ -7839,7 +8400,7 @@ function parseCodeInfo(info) {
7839
8400
  const titleMatch = meta.match(/(?:^|\s)(?:title|file)=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/);
7840
8401
  const frameworkMatch = meta.match(/(?:^|\s)framework=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/);
7841
8402
  const rangeMatch = meta.match(/\{([^}]+)\}|(?:^|\s)lines=([^\s]+)/);
7842
- const highlightLines = parseLineRanges(rangeMatch?.[1] ?? rangeMatch?.[2] ?? "");
8403
+ const highlightLines = rangeMatch ? parseLineRanges(rangeMatch[1] ?? rangeMatch[2]) : [];
7843
8404
  const title = titleMatch ? titleMatch[1] ?? titleMatch[2] ?? titleMatch[3] : void 0;
7844
8405
  const framework = frameworkMatch ? frameworkMatch[1] ?? frameworkMatch[2] ?? frameworkMatch[3] : void 0;
7845
8406
  return {
@@ -7856,28 +8417,17 @@ function parseCodeInfo(info) {
7856
8417
  function extractDefinitions(lines) {
7857
8418
  const references = Object.create(null);
7858
8419
  const footnotes = Object.create(null);
7859
- const footnoteIds = /* @__PURE__ */ new Map();
8420
+ const footnoteIds = createSlugger(footnoteId);
7860
8421
  const remaining = [];
7861
- let fenceMarker;
7862
- let fenceSize = 0;
8422
+ let activeFence = "";
7863
8423
  let index = 0;
7864
8424
  while (index < lines.length) {
7865
8425
  const line = lines[index];
7866
- const fence = line.match(/^ {0,3}(`{3,}|~{3,})/);
8426
+ const fence = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
7867
8427
  if (fence) {
7868
- const marker = fence[1][0];
7869
- if (!fenceMarker) {
7870
- fenceMarker = marker;
7871
- fenceSize = fence[1].length;
7872
- } else if (marker === fenceMarker && fence[1].length >= fenceSize) {
7873
- fenceMarker = void 0;
7874
- fenceSize = 0;
7875
- }
7876
- remaining.push(line);
7877
- index++;
7878
- continue;
7879
- }
7880
- if (!fenceMarker) {
8428
+ if (!activeFence) activeFence = fence[1];
8429
+ else if (fence[1].startsWith(activeFence) && isBlank(fence[2])) activeFence = "";
8430
+ } else if (!activeFence) {
7881
8431
  const footnote = line.match(/^ {0,3}\[\^([^\]\n]+)\]:[ \t]*(.*)$/);
7882
8432
  if (footnote) {
7883
8433
  const label = footnote[1];
@@ -7890,25 +8440,17 @@ function extractDefinitions(lines) {
7890
8440
  index++;
7891
8441
  }
7892
8442
  const key = normalizeReferenceLabel(label);
7893
- if (!footnotes[key]) {
7894
- const baseId = footnoteId(label) || "footnote";
7895
- const count = (footnoteIds.get(baseId) ?? 0) + 1;
7896
- footnoteIds.set(baseId, count);
7897
- footnotes[key] = {
7898
- label,
7899
- content: content.join("\n"),
7900
- id: count === 1 ? baseId : `${baseId}-${count}`
7901
- };
7902
- }
8443
+ if (!footnotes[key]) footnotes[key] = {
8444
+ label,
8445
+ content: content.join("\n"),
8446
+ id: footnoteIds(label)
8447
+ };
7903
8448
  continue;
7904
8449
  }
7905
- const definition = line.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/);
7906
- if (definition) {
7907
- const title = definition[3] ?? definition[4] ?? definition[5];
7908
- references[normalizeReferenceLabel(definition[1])] = {
7909
- href: definition[2].replace(/^<|>$/g, ""),
7910
- ...title !== void 0 ? { title } : {}
7911
- };
8450
+ const definition = line.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S.*)$/);
8451
+ const destination = definition && parseDestination(definition[2].trimEnd());
8452
+ if (destination) {
8453
+ references[normalizeReferenceLabel(definition[1])] ??= destination;
7912
8454
  index++;
7913
8455
  continue;
7914
8456
  }
@@ -7922,15 +8464,15 @@ function extractDefinitions(lines) {
7922
8464
  footnotes
7923
8465
  };
7924
8466
  }
7925
- function createFootnotesBlock(footnotes, footnoteOrder, options) {
8467
+ function createFootnotesBlock(footnotes, footnoteOrder, options, slugger) {
7926
8468
  const items = [];
7927
8469
  for (let index = 0; index < footnoteOrder.length; index++) {
7928
8470
  const definition = footnotes[footnoteOrder[index]];
7929
8471
  if (!definition) continue;
7930
8472
  items.push({
7931
- id: definition.id ?? (footnoteId(definition.label) || "footnote"),
8473
+ id: definition.id ?? footnoteId(definition.label),
7932
8474
  number: index + 1,
7933
- children: new BlockParser(normalizeInput(definition.content).split("\n"), options, createSlugger()).parse()
8475
+ children: new BlockParser(normalizeInput(definition.content).split("\n"), options, slugger).parse()
7934
8476
  });
7935
8477
  }
7936
8478
  for (const item of items) {
@@ -7949,6 +8491,7 @@ function parseLineRanges(value) {
7949
8491
  if (!match) continue;
7950
8492
  const start = Number(match[1]);
7951
8493
  const end = Number(match[2] ?? match[1]);
8494
+ if (end > Number.MAX_SAFE_INTEGER) continue;
7952
8495
  for (let line = start; line <= end && line < start + 1e3; line++) lines.add(line);
7953
8496
  }
7954
8497
  return [...lines].sort((a, b) => a - b);
@@ -7967,15 +8510,12 @@ function listMarker(line) {
7967
8510
  content: match[4] ?? ""
7968
8511
  };
7969
8512
  }
7970
- function sameListType(left, right) {
7971
- return left.ordered === right.ordered && left.marker === right.marker;
7972
- }
7973
8513
  function leadingSpaces(line) {
7974
8514
  return line.match(/^ */)?.[0].length ?? 0;
7975
8515
  }
7976
8516
  function isBlockStart(line, next) {
7977
8517
  const marker = listMarker(line);
7978
- return /^ {0,3}(`{3,}|~{3,})/.test(line) || /^ {0,3}#{1,6}(?:\s+|$)/.test(line) || /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(line) || /^ {0,3}>\s?/.test(line) || marker !== void 0 && (!marker.ordered || marker.number === 1) || !!next && looksLikeTableHeader(line, next);
8518
+ return /^ {0,3}(?:`{3,}|~{3,}|#{1,6}(?:\s|$)|([-*_])(?:\s*\1){2,}\s*$|>)/.test(line) || marker !== void 0 && (!marker.ordered || marker.number === 1) || !!next && looksLikeTableHeader(line, next);
7979
8519
  }
7980
8520
  function looksLikeTableHeader(header, delimiter) {
7981
8521
  if (!header.includes("|")) return false;
@@ -7983,12 +8523,10 @@ function looksLikeTableHeader(header, delimiter) {
7983
8523
  return cells.length === splitTableRow(header).length && cells.every((cell) => /^:?-+:?$/.test(cell.trim()));
7984
8524
  }
7985
8525
  function splitTableRow(value) {
7986
- let row = value.trim();
7987
- if (row.startsWith("|")) row = row.slice(1);
7988
- if (row.endsWith("|")) row = row.slice(0, -1);
8526
+ const row = value.trim();
7989
8527
  const cells = [];
7990
8528
  let current = "";
7991
- for (let index = 0; index < row.length; index++) {
8529
+ for (let index = row.startsWith("|") ? 1 : 0; index < row.length; index++) {
7992
8530
  const char = row[index];
7993
8531
  if (char === "\\" && row[index + 1] === "|") {
7994
8532
  current += "|";
@@ -8002,7 +8540,7 @@ function splitTableRow(value) {
8002
8540
  }
8003
8541
  current += char;
8004
8542
  }
8005
- cells.push(current.trim());
8543
+ if (current || !row.endsWith("|") || !cells.length) cells.push(current.trim());
8006
8544
  return cells;
8007
8545
  }
8008
8546
  function parseAlign(value) {
@@ -8018,7 +8556,7 @@ function cell(value, options) {
8018
8556
  };
8019
8557
  }
8020
8558
  //#endregion
8021
- //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.13_react@19.2.8/node_modules/@tanstack/markdown/dist/html.js
8559
+ //#region ../../node_modules/.pnpm/@tanstack+markdown@0.0.14_react@19.3.0/node_modules/@tanstack/markdown/dist/html.js
8022
8560
  function renderHtml(input, options = {}) {
8023
8561
  return (typeof input === "string" ? parseMarkdown(input, options) : input).children.map((node) => renderBlock(node, options)).join("\n");
8024
8562
  }
@@ -8035,7 +8573,7 @@ function renderBlock(node, options = {}) {
8035
8573
  case "code": return renderCodeBlock(node, options);
8036
8574
  case "list": {
8037
8575
  const tag = node.ordered ? "ol" : "ul";
8038
- return `<${tag}${node.ordered && node.start && node.start !== 1 ? ` start="${node.start}"` : ""}>\n${node.items.map((item) => `<li>${renderListItemChildren(item.children, item.checked, node.loose, options)}</li>`).join("\n")}\n</${tag}>`;
8576
+ return `<${tag}${node.ordered && node.start !== void 0 && node.start !== 1 ? ` start="${node.start}"` : ""}>\n${node.items.map((item) => `<li>${renderListItemChildren(item.children, item.checked, node.loose, options)}</li>`).join("\n")}\n</${tag}>`;
8039
8577
  }
8040
8578
  case "blockquote": return `<blockquote>\n${node.children.map((child) => renderBlock(child, options)).join("\n")}\n</blockquote>`;
8041
8579
  case "table": return `<table>${`<thead><tr>${node.header.map((cell, index) => renderTableCell("th", cell, node.align[index], options)).join("")}</tr></thead>`}${node.rows.length ? `<tbody>${node.rows.map((row) => `<tr>${row.map((cell, index) => renderTableCell("td", cell, node.align[index], options)).join("")}</tr>`).join("")}</tbody>` : ""}</table>`;
@@ -8055,7 +8593,7 @@ function renderInline(node, options = {}) {
8055
8593
  case "strong": return `<strong>${renderInlines(node.children, options)}</strong>`;
8056
8594
  case "emphasis": return `<em>${renderInlines(node.children, options)}</em>`;
8057
8595
  case "strike": return `<del>${renderInlines(node.children, options)}</del>`;
8058
- case "footnoteReference": return `<sup><a id="user-content-fnref-${escapeAttr(footnoteReferenceId(node))}" data-footnote-ref="" aria-describedby="footnote-label" href="#user-content-fn-${escapeAttr(node.id)}">${node.number}</a></sup>`;
8596
+ case "footnoteReference": return `<sup><a id="user-content-fnref-${escapeAttr(footnoteReferenceId(node.id, node.referenceIndex))}" data-footnote-ref="" aria-describedby="footnote-label" href="#user-content-fn-${escapeAttr(node.id)}">${node.number}</a></sup>`;
8059
8597
  case "link": return `<a href="${escapeAttr(node.href)}"${node.title ? ` title="${escapeAttr(node.title)}"` : ""}>${renderInlines(node.children, options)}</a>`;
8060
8598
  case "image": return `<img src="${escapeAttr(node.src)}" alt="${escapeAttr(node.alt)}"${node.title ? ` title="${escapeAttr(node.title)}"` : ""}>`;
8061
8599
  case "break": return "<br>";
@@ -8067,13 +8605,7 @@ function renderInlines(nodes, options) {
8067
8605
  }
8068
8606
  function renderCodeBlock(node, options) {
8069
8607
  const lang = node.lang ?? "plaintext";
8070
- const preAttrs = [
8071
- `class="tm-code${options.codeLineNumbers ? " tm-code--line-numbers" : ""}"`,
8072
- `data-lang="${escapeAttr(lang)}"`,
8073
- node.title ? `data-code-title="${escapeAttr(node.title)}"` : "",
8074
- node.file ? `data-filename="${escapeAttr(node.file)}"` : "",
8075
- node.framework ? `data-framework="${escapeAttr(node.framework)}"` : ""
8076
- ].filter(Boolean).join(" ");
8608
+ const preAttrs = `class="tm-code${options.codeLineNumbers ? " tm-code--line-numbers" : ""}" data-lang="${escapeAttr(lang)}"` + (node.title ? ` data-code-title="${escapeAttr(node.title)}"` : "") + (node.file ? ` data-filename="${escapeAttr(node.file)}"` : "") + (node.framework ? ` data-framework="${escapeAttr(node.framework)}"` : "");
8077
8609
  const html = options.highlighter?.(node.value, lang, {
8078
8610
  ...node.highlightLines && { highlightLines: node.highlightLines },
8079
8611
  ...options.codeLineNumbers !== void 0 && { lineNumbers: options.codeLineNumbers }
@@ -8083,14 +8615,15 @@ function renderCodeBlock(node, options) {
8083
8615
  return `<figure class="tm-code-frame" data-lang="${escapeAttr(lang)}"><figcaption>${escapeHtml$5(node.title)}</figcaption>${pre}</figure>`;
8084
8616
  }
8085
8617
  function renderListItemChildren(children, checked, loose, options) {
8086
- const first = children[0];
8087
- const task = checked === void 0 ? "" : `<input type="checkbox" disabled${checked ? " checked" : ""}> `;
8088
- if (first?.type === "paragraph") {
8089
- const content = `${task}${renderInlines(first.children, options)}`;
8090
- const rest = children.length > 1 ? `\n${children.slice(1).map((child) => renderBlock(child, options)).join("\n")}` : "";
8091
- return `${loose ? `<p>${content}</p>` : content}${rest}`;
8618
+ let result = checked === void 0 ? "" : `<input type="checkbox" disabled${checked ? " checked" : ""}> `;
8619
+ for (let index = 0; index < children.length; index++) {
8620
+ const child = children[index];
8621
+ if (child.type === "paragraph" && (!loose || index === 0)) {
8622
+ result += renderInlines(child.children, options);
8623
+ if (loose) result = `<p>${result}</p>`;
8624
+ } else result += (index ? "\n" : "") + renderBlock(child, options);
8092
8625
  }
8093
- return `${task}${children.map((child) => renderBlock(child, options)).join("\n")}`;
8626
+ return result;
8094
8627
  }
8095
8628
  function renderCallout(node, options) {
8096
8629
  const kind = node.kind.toLowerCase();
@@ -8104,24 +8637,22 @@ function renderFootnotes(items, options) {
8104
8637
  function renderFootnoteItem(item, options) {
8105
8638
  const backref = renderFootnoteBackrefs(item);
8106
8639
  const lastIndex = item.children.length - 1;
8107
- if (lastIndex < 0) return `<p>${backref.trimStart()}</p>`;
8108
- return item.children.map((child, index) => {
8640
+ const result = item.children.map((child, index) => {
8109
8641
  if (index === lastIndex && child.type === "paragraph") return `<p>${renderInlines(child.children, options)}${backref}</p>`;
8110
8642
  return renderBlock(child, options);
8111
- }).join("\n");
8643
+ });
8644
+ if (item.children[lastIndex]?.type !== "paragraph") result.push(`<p>${backref.trimStart()}</p>`);
8645
+ return result.join("\n");
8112
8646
  }
8113
8647
  function renderFootnoteBackrefs(item) {
8114
8648
  let result = "";
8115
8649
  for (let index = 1; index <= (item.referenceCount ?? 1); index++) {
8116
- const referenceId = index === 1 ? item.id : `${item.id}-${index}`;
8650
+ const referenceId = footnoteReferenceId(item.id, index);
8117
8651
  const label = index === 1 ? `${item.number}` : `${item.number}-${index}`;
8118
8652
  result += ` <a data-footnote-backref="" aria-label="Back to reference ${label}" class="data-footnote-backref" href="#user-content-fnref-${escapeAttr(referenceId)}">&#8617;</a>`;
8119
8653
  }
8120
8654
  return result;
8121
8655
  }
8122
- function footnoteReferenceId(node) {
8123
- return node.referenceIndex && node.referenceIndex > 1 ? `${node.id}-${node.referenceIndex}` : node.id;
8124
- }
8125
8656
  function renderComponent(node, options) {
8126
8657
  const tag = node.tagName ?? "md-comment-component";
8127
8658
  return `<${tag}${renderComponentAttrs(node)}>${node.children.map((child) => renderBlock(child, options)).join("\n")}</${tag}>`;
@@ -8151,9 +8682,7 @@ function renderComponentAttrs(node) {
8151
8682
  props["data-component"] = node.name;
8152
8683
  if (!props["data-attributes"]) props["data-attributes"] = JSON.stringify(node.attributes);
8153
8684
  }
8154
- const entries = Object.entries(props);
8155
- if (!entries.length) return "";
8156
- return ` ${entries.map(([key, value]) => `${key}="${escapeAttr(value)}"`).join(" ")}`;
8685
+ return Object.entries(props).map(([key, value]) => ` ${key}="${escapeAttr(value)}"`).join("");
8157
8686
  }
8158
8687
  //#endregion
8159
8688
  //#region ../viewer-kit/src/markdown-autolink.ts
@@ -8331,7 +8860,7 @@ function escapeHtml$4(value) {
8331
8860
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#x27;");
8332
8861
  }
8333
8862
  //#endregion
8334
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/core.js
8863
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/core.js
8335
8864
  function defineLanguage(definition) {
8336
8865
  return definition;
8337
8866
  }
@@ -8375,7 +8904,7 @@ function createHighlighter({ fallbackLanguage = "plaintext", languages }) {
8375
8904
  const innerHtml = renderNodesToHtml(renderTokens(result.tokens, options));
8376
8905
  return {
8377
8906
  ...result,
8378
- html: `<pre class="th-code th-code--${escapeAttribute$1(result.lang)}${options.lineNumbers ? " th-code--line-numbers" : ""}" data-language="${escapeAttribute$1(result.lang)}"><code>${innerHtml}</code></pre>`
8907
+ html: `<pre class="th-code th-code--${escapeHtml$3(result.lang)}${options.lineNumbers ? " th-code--line-numbers" : ""}" data-language="${escapeHtml$3(result.lang)}"><code>${innerHtml}</code></pre>`
8379
8908
  };
8380
8909
  }
8381
8910
  function renderCodeBlockData({ code, decorations, lang, lineNumbers, title }) {
@@ -8407,11 +8936,17 @@ function createHighlighter({ fallbackLanguage = "plaintext", languages }) {
8407
8936
  };
8408
8937
  }
8409
8938
  function renderTokens(tokens, options = {}) {
8939
+ const rangeDecorations = [];
8940
+ const lineDecorations = [];
8941
+ for (const decoration of options.decorations || []) if (decoration.range) rangeDecorations.push(decoration);
8942
+ else lineDecorations.push(decoration);
8943
+ const wrapLines = Boolean(options.lineNumbers || lineDecorations.length);
8944
+ const cursor = {
8945
+ index: 0,
8946
+ offset: 0
8947
+ };
8948
+ if (!wrapLines) return renderTokenSlice(tokens, 0, Infinity, rangeDecorations, cursor);
8410
8949
  const code = tokens.map((token) => token.value).join("");
8411
- const decorations = options.decorations || [];
8412
- const rangeDecorations = decorations.filter(isRangeDecoration);
8413
- const lineDecorations = decorations.filter(isLineDecoration);
8414
- if (!Boolean(options.lineNumbers || lineDecorations.length)) return renderTokenSlice(tokens, 0, code.length, rangeDecorations);
8415
8950
  const nodes = [];
8416
8951
  const lineStarts = getLineStarts(code);
8417
8952
  for (let index = 0; index < lineStarts.length; index++) {
@@ -8428,7 +8963,7 @@ function renderTokens(tokens, options = {}) {
8428
8963
  ...mergeData(active),
8429
8964
  line: String(line)
8430
8965
  },
8431
- children: renderTokenSlice(tokens, start, end, rangeDecorations)
8966
+ children: renderTokenSlice(tokens, start, end, rangeDecorations, cursor)
8432
8967
  });
8433
8968
  if (hasNewline) nodes.push({
8434
8969
  type: "text",
@@ -8444,31 +8979,52 @@ function renderNodesToHtml(nodes) {
8444
8979
  html += escapeHtml$3(node.value);
8445
8980
  continue;
8446
8981
  }
8447
- const className = node.classNames.map(escapeAttribute$1).join(" ");
8448
- const data = Object.entries(node.data || {}).map(([key, value]) => ` data-${escapeAttribute$1(toKebabCase(key))}="${escapeAttribute$1(value)}"`).join("");
8982
+ const className = escapeHtml$3(node.classNames.join(" "));
8983
+ let data = "";
8984
+ if (node.data) for (const [key, value] of Object.entries(node.data)) data += ` data-${normalizeDataKey(key)}="${escapeHtml$3(value)}"`;
8449
8985
  html += `<span${className ? ` class="${className}"` : ""}${data}>${renderNodesToHtml(node.children)}</span>`;
8450
8986
  }
8451
8987
  return html;
8452
8988
  }
8989
+ const htmlEscapes = {
8990
+ "&": "&amp;",
8991
+ "<": "&lt;",
8992
+ ">": "&gt;",
8993
+ "\"": "&quot;",
8994
+ "'": "&#39;"
8995
+ };
8453
8996
  function escapeHtml$3(value) {
8454
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
8997
+ return value.replace(/[&<>"']/g, (character) => htmlEscapes[character]);
8455
8998
  }
8456
8999
  function normalizeName(value) {
8457
9000
  return value.trim().toLowerCase();
8458
9001
  }
8459
9002
  function normalizeTokenRanges(codeLength, input) {
8460
9003
  const ranges = [];
8461
- const candidates = input.map((candidate) => ({
8462
- ...candidate,
8463
- start: Math.max(0, Math.min(codeLength, candidate.start)),
8464
- end: Math.max(0, Math.min(codeLength, candidate.end))
8465
- })).sort((a, b) => a.start - b.start);
9004
+ let sorted = true;
9005
+ let previousStart = 0;
9006
+ for (const candidate of input) {
9007
+ if (!Number.isInteger(candidate.start) || !Number.isInteger(candidate.end)) continue;
9008
+ const start = Math.max(0, Math.min(codeLength, candidate.start));
9009
+ const end = Math.max(0, Math.min(codeLength, candidate.end));
9010
+ if (start >= end) continue;
9011
+ if (start < previousStart) sorted = false;
9012
+ previousStart = start;
9013
+ ranges.push({
9014
+ className: candidate.className,
9015
+ start,
9016
+ end
9017
+ });
9018
+ }
9019
+ if (!sorted) ranges.sort((a, b) => a.start - b.start);
8466
9020
  let end = 0;
8467
- for (const candidate of candidates) {
8468
- if (candidate.start >= candidate.end || candidate.start < end) continue;
8469
- ranges.push(candidate);
9021
+ let count = 0;
9022
+ for (const candidate of ranges) {
9023
+ if (candidate.start < end) continue;
9024
+ ranges[count++] = candidate;
8470
9025
  end = candidate.end;
8471
9026
  }
9027
+ ranges.length = count;
8472
9028
  return ranges;
8473
9029
  }
8474
9030
  function rangesToTokens(code, ranges) {
@@ -8485,22 +9041,26 @@ function rangesToTokens(code, ranges) {
8485
9041
  if (index < code.length) tokens.push({ value: code.slice(index) });
8486
9042
  return tokens;
8487
9043
  }
8488
- function renderTokenSlice(tokens, start, end, decorations) {
9044
+ function renderTokenSlice(tokens, start, end, decorations, cursor) {
8489
9045
  const nodes = [];
8490
- let tokenStart = 0;
8491
- for (const token of tokens) {
9046
+ for (; cursor.index < tokens.length; cursor.index++) {
9047
+ const token = tokens[cursor.index];
9048
+ const tokenStart = cursor.offset;
8492
9049
  const tokenEnd = tokenStart + token.value.length;
8493
9050
  const sliceStart = Math.max(start, tokenStart);
8494
9051
  const sliceEnd = Math.min(end, tokenEnd);
8495
9052
  if (sliceStart < sliceEnd) {
8496
- const boundaries = /* @__PURE__ */ new Set([sliceStart, sliceEnd]);
8497
- for (const decoration of decorations) {
8498
- const [decorationStart, decorationEnd] = decoration.range;
8499
- if (decorationEnd <= sliceStart || decorationStart >= sliceEnd) continue;
8500
- boundaries.add(Math.max(sliceStart, decorationStart));
8501
- boundaries.add(Math.min(sliceEnd, decorationEnd));
9053
+ let sorted = [sliceStart, sliceEnd];
9054
+ if (decorations.length) {
9055
+ const boundaries = new Set(sorted);
9056
+ for (const decoration of decorations) {
9057
+ const [decorationStart, decorationEnd] = decoration.range;
9058
+ if (decorationEnd <= sliceStart || decorationStart >= sliceEnd) continue;
9059
+ boundaries.add(Math.max(sliceStart, decorationStart));
9060
+ boundaries.add(Math.min(sliceEnd, decorationEnd));
9061
+ }
9062
+ sorted = [...boundaries].sort((a, b) => a - b);
8502
9063
  }
8503
- const sorted = [...boundaries].sort((a, b) => a - b);
8504
9064
  for (let index = 0; index < sorted.length - 1; index++) {
8505
9065
  const segmentStart = sorted[index];
8506
9066
  const segmentEnd = sorted[index + 1];
@@ -8513,27 +9073,23 @@ function renderTokenSlice(tokens, start, end, decorations) {
8513
9073
  classNames: ["th-token", `th-${token.className}`],
8514
9074
  children: [node]
8515
9075
  };
8516
- const active = decorations.filter((decoration) => decoration.range[0] <= segmentStart && decoration.range[1] >= segmentEnd);
8517
- for (const decoration of active) node = {
8518
- type: "element",
8519
- classNames: ["th-decoration", ...splitClassNames(decoration.className)],
8520
- data: stringifyData(decoration.data),
8521
- children: [node]
8522
- };
9076
+ for (const decoration of decorations) {
9077
+ if (decoration.range[0] > segmentStart || decoration.range[1] < segmentEnd) continue;
9078
+ node = {
9079
+ type: "element",
9080
+ classNames: ["th-decoration", ...splitClassNames(decoration.className)],
9081
+ data: stringifyData(decoration.data),
9082
+ children: [node]
9083
+ };
9084
+ }
8523
9085
  nodes.push(node);
8524
9086
  }
8525
9087
  }
8526
- tokenStart = tokenEnd;
8527
- if (tokenStart >= end) break;
9088
+ if (tokenEnd > end) break;
9089
+ cursor.offset = tokenEnd;
8528
9090
  }
8529
9091
  return nodes;
8530
9092
  }
8531
- function isRangeDecoration(decoration) {
8532
- return "range" in decoration;
8533
- }
8534
- function isLineDecoration(decoration) {
8535
- return "lines" in decoration;
8536
- }
8537
9093
  function getLineStarts(code) {
8538
9094
  const starts = [0];
8539
9095
  for (let index = 0; index < code.length; index++) if (code[index] === "\n" && index + 1 < code.length) starts.push(index + 1);
@@ -8560,17 +9116,13 @@ function splitClassNames(className) {
8560
9116
  function toKebabCase(value) {
8561
9117
  return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
8562
9118
  }
8563
- function escapeAttribute$1(value) {
8564
- return escapeHtml$3(value);
8565
- }
8566
9119
  //#endregion
8567
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/internal/patterns.js
9120
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/internal/patterns.js
8568
9121
  function patternTokenizer(patterns) {
8569
9122
  return (code) => collectPatternRanges(code, patterns);
8570
9123
  }
8571
- function collectPatternRanges(code, patterns, initial = []) {
9124
+ function collectPatternRanges(code, patterns, initial = [], occupied = new Uint8Array(code.length)) {
8572
9125
  const ranges = [...initial];
8573
- const occupied = new Uint8Array(code.length);
8574
9126
  for (const range of initial) occupied.fill(1, range.start, range.end);
8575
9127
  for (const pattern of patterns) {
8576
9128
  if ("collect" in pattern) {
@@ -8585,7 +9137,7 @@ function collectPatternRanges(code, patterns, initial = []) {
8585
9137
  if (!match[0].length) regex.lastIndex++;
8586
9138
  continue;
8587
9139
  }
8588
- const offset = pattern.group ? match[0].indexOf(value) : 0;
9140
+ const offset = pattern.group ? match[0].length - value.length : 0;
8589
9141
  const start = match.index + offset;
8590
9142
  addRange(ranges, occupied, {
8591
9143
  start,
@@ -8610,14 +9162,14 @@ function addRange(ranges, occupied, range) {
8610
9162
  return true;
8611
9163
  }
8612
9164
  function cloneRegex(regex) {
8613
- return new RegExp(regex.source, regex.flags.includes("g") ? regex.flags : `${regex.flags}g`);
9165
+ return new RegExp(regex.source, regex.global ? regex.flags : `${regex.flags}g`);
8614
9166
  }
8615
9167
  function hasOverlap(occupied, start, end) {
8616
9168
  for (let index = start; index < end; index++) if (occupied[index]) return true;
8617
9169
  return false;
8618
9170
  }
8619
9171
  //#endregion
8620
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/css.js
9172
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/css.js
8621
9173
  const css = defineLanguage({
8622
9174
  name: "css",
8623
9175
  tokenize: patternTokenizer([
@@ -8650,7 +9202,7 @@ const css = defineLanguage({
8650
9202
  ])
8651
9203
  });
8652
9204
  //#endregion
8653
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/diff.js
9205
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/diff.js
8654
9206
  const diff = defineLanguage({
8655
9207
  name: "diff",
8656
9208
  aliases: ["patch"],
@@ -8670,7 +9222,7 @@ const diff = defineLanguage({
8670
9222
  ])
8671
9223
  });
8672
9224
  //#endregion
8673
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/dockerfile.js
9225
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/dockerfile.js
8674
9226
  const dockerfile = defineLanguage({
8675
9227
  name: "dockerfile",
8676
9228
  aliases: ["docker"],
@@ -8698,12 +9250,16 @@ const dockerfile = defineLanguage({
8698
9250
  ])
8699
9251
  });
8700
9252
  //#endregion
8701
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/internal/markup.js
9253
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/internal/markup.js
9254
+ const rawTextClosing = {
9255
+ script: /<\/script(?=[\s/>])/gi,
9256
+ style: /<\/style(?=[\s/>])/gi
9257
+ };
8702
9258
  function collectMarkupRanges(code, context, mode = "html") {
8703
9259
  const ranges = [];
8704
9260
  const regions = [];
8705
9261
  let index = 0;
8706
- while (index < code.length) {
9262
+ while ((index = code.indexOf("<", index)) >= 0) {
8707
9263
  if (code.startsWith("<!--", index)) {
8708
9264
  const close = code.indexOf("-->", index + 4);
8709
9265
  const end = close < 0 ? code.length : close + 3;
@@ -8726,10 +9282,6 @@ function collectMarkupRanges(code, context, mode = "html") {
8726
9282
  index = close < 0 ? code.length : close + 2;
8727
9283
  continue;
8728
9284
  }
8729
- if (code[index] !== "<") {
8730
- index++;
8731
- continue;
8732
- }
8733
9285
  const closing = code[index + 1] === "/";
8734
9286
  const nameStart = index + (closing ? 2 : 1);
8735
9287
  const nameMatch = /^[A-Za-z][\w:.-]*/.exec(code.slice(nameStart));
@@ -8750,16 +9302,17 @@ function collectMarkupRanges(code, context, mode = "html") {
8750
9302
  });
8751
9303
  if (!closing) collectAttributes(code, nameStart + nameMatch[0].length, tagEnd, ranges);
8752
9304
  if (!closing && (tagName === "script" || tagName === "style")) {
8753
- const closingTag = `</${tagName}`;
8754
- const contentEnd = code.toLowerCase().indexOf(closingTag, tagEnd + 1);
8755
- if (contentEnd >= 0) {
8756
- const lang = getEmbeddedLanguage(tagName, code.slice(index, tagEnd + 1));
8757
- regions.push({
8758
- start: tagEnd + 1,
8759
- end: contentEnd,
8760
- lang
8761
- });
8762
- }
9305
+ const rawTextClose = rawTextClosing[tagName];
9306
+ rawTextClose.lastIndex = tagEnd + 1;
9307
+ const contentEnd = rawTextClose.exec(code)?.index ?? code.length;
9308
+ const lang = getEmbeddedLanguage(tagName, code.slice(index, tagEnd + 1));
9309
+ regions.push({
9310
+ start: tagEnd + 1,
9311
+ end: contentEnd,
9312
+ lang
9313
+ });
9314
+ index = contentEnd;
9315
+ continue;
8763
9316
  }
8764
9317
  index = tagEnd + 1;
8765
9318
  }
@@ -8850,7 +9403,7 @@ function findQuoteEnd(code, start, quote, limit) {
8850
9403
  return limit;
8851
9404
  }
8852
9405
  //#endregion
8853
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/html.js
9406
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/html.js
8854
9407
  const html = defineLanguage({
8855
9408
  name: "html",
8856
9409
  aliases: [
@@ -8861,7 +9414,7 @@ const html = defineLanguage({
8861
9414
  tokenize: (code, context) => collectMarkupRanges(code, context)
8862
9415
  });
8863
9416
  //#endregion
8864
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/internal/script.js
9417
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/internal/script.js
8865
9418
  const semanticPatterns = [
8866
9419
  {
8867
9420
  className: "function",
@@ -8886,7 +9439,7 @@ const semanticPatterns = [
8886
9439
  },
8887
9440
  {
8888
9441
  className: "function",
8889
- regex: /(^|[^.A-Za-z0-9_$])([A-Za-z_$][\w$]*)\s*(?=\()/g,
9442
+ regex: /(^|[^.A-Za-z0-9_$])([A-Za-z_$][\w$]*)(?=\s*\()/g,
8890
9443
  group: 2
8891
9444
  },
8892
9445
  {
@@ -8903,8 +9456,7 @@ function collectScriptRanges(code, jsx = false, jsxAtLineStart = false) {
8903
9456
  const jsxText = jsx ? new Uint8Array(code.length) : void 0;
8904
9457
  const initial = [];
8905
9458
  collectScriptInitialRanges(code, jsx, jsxAtLineStart, jsxText, initial);
8906
- const ranges = collectPatternRanges(code, semanticPatterns, initial);
8907
- return jsxText ? ranges.filter((range) => !jsxText[range.start]) : ranges;
9459
+ return collectPatternRanges(code, semanticPatterns, initial, jsxText);
8908
9460
  }
8909
9461
  function collectScriptInitialRanges(code, jsx, jsxAtLineStart, jsxText, ranges, index = 0, limit = code.length, tagBody = false) {
8910
9462
  const expressions = [];
@@ -9101,6 +9653,10 @@ function findInterpolationEnd(code, start) {
9101
9653
  index = close < 0 ? code.length : close + 2;
9102
9654
  continue;
9103
9655
  }
9656
+ if (character === "/" && isRegexStart(code, index)) {
9657
+ index = findRegexEnd(code, index);
9658
+ continue;
9659
+ }
9104
9660
  if (character === "{") depth++;
9105
9661
  if (character === "}" && --depth === 0) return index;
9106
9662
  index++;
@@ -9179,7 +9735,7 @@ function findLineEnd(code, start) {
9179
9735
  return end < 0 ? code.length : end;
9180
9736
  }
9181
9737
  //#endregion
9182
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/js.js
9738
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/js.js
9183
9739
  const js = defineLanguage({
9184
9740
  name: "js",
9185
9741
  aliases: [
@@ -9191,7 +9747,7 @@ const js = defineLanguage({
9191
9747
  tokenize: (code) => collectScriptRanges(code)
9192
9748
  });
9193
9749
  //#endregion
9194
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/json.js
9750
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/json.js
9195
9751
  const json = defineLanguage({
9196
9752
  name: "json",
9197
9753
  aliases: ["jsonc", "json5"],
@@ -9211,13 +9767,13 @@ const json = defineLanguage({
9211
9767
  ])
9212
9768
  });
9213
9769
  //#endregion
9214
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/jsx.js
9770
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/jsx.js
9215
9771
  const jsx = defineLanguage({
9216
9772
  name: "jsx",
9217
9773
  tokenize: (code) => collectScriptRanges(code, true)
9218
9774
  });
9219
9775
  //#endregion
9220
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/markdown.js
9776
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/markdown.js
9221
9777
  const markdown = defineLanguage({
9222
9778
  name: "markdown",
9223
9779
  aliases: ["md"],
@@ -9278,7 +9834,7 @@ function collectFencedCode(code, context) {
9278
9834
  function fillCodeRange(start, end, embedded) {
9279
9835
  const ranges = [];
9280
9836
  let index = start;
9281
- for (const range of [...embedded].sort((a, b) => a.start - b.start)) {
9837
+ for (const range of embedded) {
9282
9838
  if (range.start > index) ranges.push({
9283
9839
  start: index,
9284
9840
  end: range.start,
@@ -9295,46 +9851,44 @@ function fillCodeRange(start, end, embedded) {
9295
9851
  return ranges;
9296
9852
  }
9297
9853
  //#endregion
9298
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/python.js
9854
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/python.js
9299
9855
  const python = defineLanguage({
9300
9856
  name: "python",
9301
9857
  aliases: ["py"],
9302
- tokenize(code) {
9303
- return collectPatternRanges(code, [
9304
- {
9305
- className: (match) => match[0].startsWith("#") ? "comment" : "string",
9306
- regex: /#[^\n]*|(?:br|rb|fr|rf|[rubf])?(?:"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*')/gi
9307
- },
9308
- {
9309
- className: "keyword",
9310
- regex: /\b(?:and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g
9311
- },
9312
- {
9313
- className: "literal",
9314
- regex: /\b(?:False|None|True|NotImplemented|Ellipsis)\b/g
9315
- },
9316
- {
9317
- className: "function",
9318
- regex: /@[A-Za-z_][\w.]*/g
9319
- },
9320
- {
9321
- className: "function",
9322
- regex: /\bdef\s+([A-Za-z_]\w*)/g,
9323
- group: 1
9324
- },
9325
- {
9326
- className: "type",
9327
- regex: /\b(?:bool|bytes|dict|float|frozenset|int|list|object|set|str|tuple|type)\b/g
9328
- },
9329
- {
9330
- className: "number",
9331
- regex: /\b(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d[\d_]*)?j?)\b/gi
9332
- }
9333
- ]);
9334
- }
9858
+ tokenize: patternTokenizer([
9859
+ {
9860
+ className: (match) => match[0].startsWith("#") ? "comment" : "string",
9861
+ regex: /#[^\n]*|(?:br|rb|fr|rf|[rubf])?(?:"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*')/gi
9862
+ },
9863
+ {
9864
+ className: "keyword",
9865
+ regex: /\b(?:and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/g
9866
+ },
9867
+ {
9868
+ className: "literal",
9869
+ regex: /\b(?:False|None|True|NotImplemented|Ellipsis)\b/g
9870
+ },
9871
+ {
9872
+ className: "function",
9873
+ regex: /@[A-Za-z_][\w.]*/g
9874
+ },
9875
+ {
9876
+ className: "function",
9877
+ regex: /\bdef\s+([A-Za-z_]\w*)/g,
9878
+ group: 1
9879
+ },
9880
+ {
9881
+ className: "type",
9882
+ regex: /\b(?:bool|bytes|dict|float|frozenset|int|list|object|set|str|tuple|type)\b/g
9883
+ },
9884
+ {
9885
+ className: "number",
9886
+ regex: /\b(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d[\d_]*)?j?)\b/gi
9887
+ }
9888
+ ])
9335
9889
  });
9336
9890
  //#endregion
9337
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/shell.js
9891
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/shell.js
9338
9892
  const shell = defineLanguage({
9339
9893
  name: "shell",
9340
9894
  aliases: [
@@ -9344,32 +9898,34 @@ const shell = defineLanguage({
9344
9898
  "cmd",
9345
9899
  "console"
9346
9900
  ],
9347
- tokenize(code) {
9348
- return collectPatternRanges(code, [
9349
- { collect: collectShellLexicalRanges },
9350
- {
9351
- className: "variable",
9352
- regex: /\$[A-Za-z_][A-Za-z0-9_]*|\b[A-Z_][A-Z0-9_]*(?==)/g
9353
- },
9354
- {
9355
- className: "keyword",
9356
- regex: /\b(?:case|do|done|elif|else|esac|export|fi|for|function|if|in|select|then|time|until|while)\b/g
9357
- },
9358
- {
9359
- className: "command",
9360
- regex: /(^|[\n;|&])\s*([A-Za-z0-9_./-]+)(?=\s|$)/g,
9361
- group: 2
9362
- }
9363
- ]);
9364
- }
9901
+ tokenize: patternTokenizer([
9902
+ { collect: collectShellLexicalRanges },
9903
+ {
9904
+ className: "variable",
9905
+ regex: /\$[A-Za-z_][A-Za-z0-9_]*|\b[A-Z_][A-Z0-9_]*(?==)/g
9906
+ },
9907
+ {
9908
+ className: "keyword",
9909
+ regex: /\b(?:case|do|done|elif|else|esac|export|fi|for|function|if|in|select|then|time|until|while)\b/g
9910
+ },
9911
+ {
9912
+ className: "command",
9913
+ regex: /(^|[\n;|&])\s*([A-Za-z0-9_./-]+)(?=\s|$)/g,
9914
+ group: 2
9915
+ }
9916
+ ])
9365
9917
  });
9366
9918
  function collectShellLexicalRanges(code) {
9367
- const ranges = [];
9368
- collectHeredocs(code, ranges);
9919
+ const heredocs = [];
9920
+ collectHeredocs(code, heredocs);
9921
+ const ranges = [...heredocs];
9922
+ let heredocIndex = 0;
9369
9923
  let index = 0;
9370
9924
  while (index < code.length) {
9371
- if (insideRange(index, ranges)) {
9372
- index = ranges.find((range) => range.start <= index && range.end > index).end;
9925
+ while (heredocIndex < heredocs.length && heredocs[heredocIndex].end <= index) heredocIndex++;
9926
+ const heredoc = heredocs[heredocIndex];
9927
+ if (heredoc && heredoc.start <= index) {
9928
+ index = heredoc.end;
9373
9929
  continue;
9374
9930
  }
9375
9931
  const character = code[index];
@@ -9381,6 +9937,7 @@ function collectShellLexicalRanges(code) {
9381
9937
  end++;
9382
9938
  break;
9383
9939
  } else end++;
9940
+ end = Math.min(end, code.length);
9384
9941
  ranges.push({
9385
9942
  start: index,
9386
9943
  end,
@@ -9423,7 +9980,7 @@ function collectHeredocs(code, ranges) {
9423
9980
  const bodyStartLine = code.indexOf("\n", match.index + match[0].length);
9424
9981
  if (bodyStartLine < 0) continue;
9425
9982
  const bodyStart = bodyStartLine + 1;
9426
- const closingMatch = new RegExp(`^\\t*${escapeRegex(match[2])}\\s*$`, "m").exec(code.slice(bodyStart));
9983
+ const closingMatch = new RegExp(`^\\t*${match[2]}\\s*$`, "m").exec(code.slice(bodyStart));
9427
9984
  if (!closingMatch) {
9428
9985
  ranges.push({
9429
9986
  start: bodyStart,
@@ -9454,14 +10011,8 @@ function isInsideQuote(code, index) {
9454
10011
  else if (!quote && (code[cursor] === "\"" || code[cursor] === "'")) quote = code[cursor];
9455
10012
  return Boolean(quote);
9456
10013
  }
9457
- function insideRange(index, ranges) {
9458
- return ranges.some((range) => range.start <= index && range.end > index);
9459
- }
9460
- function escapeRegex(value) {
9461
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9462
- }
9463
10014
  //#endregion
9464
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/sql.js
10015
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/sql.js
9465
10016
  const sql = defineLanguage({
9466
10017
  name: "sql",
9467
10018
  tokenize: patternTokenizer([
@@ -9488,7 +10039,7 @@ const sql = defineLanguage({
9488
10039
  ])
9489
10040
  });
9490
10041
  //#endregion
9491
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/toml.js
10042
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/toml.js
9492
10043
  const toml = defineLanguage({
9493
10044
  name: "toml",
9494
10045
  tokenize: patternTokenizer([
@@ -9516,20 +10067,20 @@ const toml = defineLanguage({
9516
10067
  ])
9517
10068
  });
9518
10069
  //#endregion
9519
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/ts.js
10070
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/ts.js
9520
10071
  const ts = defineLanguage({
9521
10072
  name: "ts",
9522
10073
  aliases: ["typescript", "angular-ts"],
9523
10074
  tokenize: (code) => collectScriptRanges(code)
9524
10075
  });
9525
10076
  //#endregion
9526
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/tsx.js
10077
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/tsx.js
9527
10078
  const tsx = defineLanguage({
9528
10079
  name: "tsx",
9529
10080
  tokenize: (code) => collectScriptRanges(code, true)
9530
10081
  });
9531
10082
  //#endregion
9532
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/languages/yaml.js
10083
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/languages/yaml.js
9533
10084
  const yaml = defineLanguage({
9534
10085
  name: "yaml",
9535
10086
  aliases: ["yml"],
@@ -9635,7 +10186,7 @@ function collectYamlValues(code) {
9635
10186
  return ranges;
9636
10187
  }
9637
10188
  //#endregion
9638
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/theme.js
10189
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/theme.js
9639
10190
  const themeTokenClasses = [
9640
10191
  "token",
9641
10192
  "attr",
@@ -9689,27 +10240,7 @@ function createThemeBaseCss(options = {}) {
9689
10240
  color: var(--th-token);
9690
10241
  }
9691
10242
 
9692
- .th-token { color: var(--th-token); }
9693
- .th-keyword { color: var(--th-keyword); }
9694
- .th-string { color: var(--th-string); }
9695
- .th-comment { color: var(--th-comment); }
9696
- .th-function { color: var(--th-function); }
9697
- .th-type { color: var(--th-type); }
9698
- .th-property { color: var(--th-property); }
9699
- .th-tag { color: var(--th-tag); }
9700
- .th-attr { color: var(--th-attr); }
9701
- .th-literal { color: var(--th-literal); }
9702
- .th-number { color: var(--th-number); }
9703
- .th-variable { color: var(--th-variable); }
9704
- .th-operator { color: var(--th-operator); }
9705
- .th-inserted { color: var(--th-inserted); }
9706
- .th-deleted { color: var(--th-deleted); }
9707
- .th-meta { color: var(--th-meta); }
9708
- .th-heading { color: var(--th-heading); }
9709
- .th-link { color: var(--th-link); }
9710
- .th-code-inline { color: var(--th-code-inline); }
9711
- .th-selector { color: var(--th-selector); }
9712
- .th-command { color: var(--th-command); }
10243
+ ${themeTokenClasses.map((token) => `.th-${token} { color: var(--th-${token}); }`).join("\n")}
9713
10244
  .th-line { display: inline-block; min-width: 100%; width: max-content; }
9714
10245
  ${lineNumbersSelector} code { counter-reset: th-line; }
9715
10246
  ${lineNumbersSelector} .th-line::before {
@@ -9723,7 +10254,7 @@ ${lineNumbersSelector} .th-line::before {
9723
10254
  }`;
9724
10255
  }
9725
10256
  //#endregion
9726
- //#region ../../node_modules/.pnpm/@tanstack+highlight@0.0.10/node_modules/@tanstack/highlight/dist/themes/github-dark.js
10257
+ //#region ../../node_modules/.pnpm/@tanstack+highlight@0.1.0/node_modules/@tanstack/highlight/dist/themes/github-dark.js
9727
10258
  const githubDarkTheme = {
9728
10259
  background: "#0d1117",
9729
10260
  foreground: "#c9d1d9",
@@ -10586,6 +11117,8 @@ function renderPreviewShell(options) {
10586
11117
  const payload = readyPayload();
10587
11118
  postToFrame(payload);
10588
11119
  postToFrame({ kind: 'annotate-mode', enabled: annotateMode });
11120
+ // The CLI preview has no external-link interstitial; open links directly.
11121
+ postToFrame({ kind: 'external-link-policy', mode: 'direct' });
10589
11122
  readyBurstTimer = setInterval(() => {
10590
11123
  sent += 1;
10591
11124
  if (sent >= CONFIG.readyRepeat) {
@@ -10595,6 +11128,7 @@ function renderPreviewShell(options) {
10595
11128
  }
10596
11129
  postToFrame(payload);
10597
11130
  postToFrame({ kind: 'annotate-mode', enabled: annotateMode });
11131
+ postToFrame({ kind: 'external-link-policy', mode: 'direct' });
10598
11132
  }, CONFIG.readyIntervalMs);
10599
11133
  }
10600
11134
 
@@ -12104,12 +12638,14 @@ async function runCommentsList(parsed, mode) {
12104
12638
  return comments.error ? { error: comments.error } : { data: comments.body };
12105
12639
  });
12106
12640
  if (result.error) return writeFailure(command, result.error, mode, 1);
12107
- const comments = Array.isArray(result.data?.comments) ? result.data.comments : [];
12641
+ const contracted = COMMENTS_LIST_RESPONSE_SCHEMA.safeParse(result.data);
12642
+ const raw = isRecord$1(result.data) ? result.data : null;
12643
+ const comments = contracted.success ? contracted.data.comments : Array.isArray(raw?.comments) ? raw.comments : [];
12108
12644
  writeSuccess(command, {
12109
12645
  artifact_id: artifactId,
12110
- share_url: configString(result.data?.share_url),
12646
+ share_url: configString(contracted.success ? contracted.data.share_url : raw?.share_url),
12111
12647
  comments,
12112
- has_more: result.data?.has_more === true
12648
+ has_more: (contracted.success ? contracted.data.has_more : raw?.has_more) === true
12113
12649
  }, mode);
12114
12650
  if (!mode.json && comments.length === 0) writeText("No comments yet.\n");
12115
12651
  }
@@ -12147,14 +12683,16 @@ async function runCommentsPost(parsed, mode) {
12147
12683
  return posted.error ? { error: posted.error } : { data: posted.body };
12148
12684
  });
12149
12685
  if (result.error) return writeFailure(command, result.error, mode, 1);
12150
- const threadId = configString(result.data?.thread_id);
12686
+ const postedResponse = isContract(COMMENT_POST_RESPONSE_SCHEMA, result.data) ? result.data : null;
12687
+ const postedRaw = isRecord$1(result.data) ? result.data : null;
12688
+ const threadId = configString(postedResponse?.thread_id ?? postedRaw?.thread_id);
12151
12689
  if (!threadId) return writeFailure(command, serviceError("Comment was saved but the response had no thread id."), mode, 1);
12152
12690
  writeSuccess(command, {
12153
12691
  artifact_id: artifactId,
12154
- share_url: configString(result.data?.share_url),
12692
+ share_url: configString(postedResponse?.share_url ?? postedRaw?.share_url),
12155
12693
  thread_id: threadId,
12156
- reply: result.data?.reply === true,
12157
- thread: result.data?.thread ?? null
12694
+ reply: (postedResponse?.reply ?? postedRaw?.reply) === true,
12695
+ thread: postedResponse?.thread ?? postedRaw?.thread ?? null
12158
12696
  }, mode);
12159
12697
  }
12160
12698
  async function runCommentsEdit(parsed, mode) {
@@ -12171,13 +12709,16 @@ async function runCommentsEdit(parsed, mode) {
12171
12709
  body: body.value
12172
12710
  }, mode);
12173
12711
  if (!result) return;
12174
- const threadId = configString(result.thread_id);
12175
- if (!threadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
12712
+ const actionResponse = isContract(COMMENT_ACTION_RESPONSE_SCHEMA, result) ? result : null;
12713
+ const actionRaw = isRecord$1(result) ? result : null;
12714
+ const threadId = configString(actionResponse?.thread_id ?? actionRaw?.thread_id);
12715
+ const thread = actionResponse?.thread ?? actionRaw?.thread;
12716
+ if (!threadId || thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
12176
12717
  writeSuccess(command, {
12177
12718
  artifact_id: target.artifactId,
12178
- share_url: configString(result.share_url),
12719
+ share_url: configString(actionResponse?.share_url ?? actionRaw?.share_url),
12179
12720
  thread_id: threadId,
12180
- thread: result.thread
12721
+ thread
12181
12722
  }, mode);
12182
12723
  }
12183
12724
  async function runCommentsResolve(parsed, mode) {
@@ -12192,25 +12733,30 @@ async function runCommentsDelete(parsed, mode) {
12192
12733
  if (target.error) return writeFailure(command, target.error, mode, 1);
12193
12734
  const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
12194
12735
  if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
12195
- const payload = {
12736
+ let payload = {
12196
12737
  action: "delete",
12197
12738
  thread_id: threadId.value
12198
12739
  };
12199
12740
  if (parsed.options.messageId !== void 0) {
12200
12741
  if (!parsed.options.messageId.trim()) return writeFailure(command, validationError("--message-id cannot be empty.", "Run comments list and retry with a listed message_id."), mode, 1);
12201
- payload.message_id = parsed.options.messageId.trim();
12742
+ payload = {
12743
+ ...payload,
12744
+ message_id: parsed.options.messageId.trim()
12745
+ };
12202
12746
  }
12203
12747
  const result = await postCommentAction(parsed, command, target.artifactId, payload, mode);
12204
12748
  if (!result) return;
12205
- const responseThreadId = configString(result.thread_id);
12206
- if (!responseThreadId || result.deleted !== true) return writeFailure(command, serviceError("Comment was deleted but the response was incomplete."), mode, 1);
12749
+ const deleteResponse = isContract(COMMENT_DELETE_RESPONSE_SCHEMA, result) ? result : null;
12750
+ const deleteRaw = isRecord$1(result) ? result : null;
12751
+ const responseThreadId = configString(deleteResponse?.thread_id ?? deleteRaw?.thread_id);
12752
+ if (!responseThreadId || (deleteResponse?.deleted ?? deleteRaw?.deleted) !== true) return writeFailure(command, serviceError("Comment was deleted but the response was incomplete."), mode, 1);
12207
12753
  writeSuccess(command, {
12208
12754
  artifact_id: target.artifactId,
12209
- share_url: configString(result.share_url),
12755
+ share_url: configString(deleteResponse?.share_url ?? deleteRaw?.share_url),
12210
12756
  thread_id: responseThreadId,
12211
12757
  deleted: true,
12212
- thread_deleted: result.thread_deleted === true,
12213
- ...result.thread !== void 0 ? { thread: result.thread } : {}
12758
+ thread_deleted: (deleteResponse?.thread_deleted ?? deleteRaw?.thread_deleted) === true,
12759
+ ...(deleteResponse?.thread ?? deleteRaw?.thread) !== void 0 ? { thread: deleteResponse?.thread ?? deleteRaw?.thread } : {}
12214
12760
  }, mode);
12215
12761
  }
12216
12762
  async function runCommentsStatus(parsed, mode, command, action) {
@@ -12218,18 +12764,24 @@ async function runCommentsStatus(parsed, mode, command, action) {
12218
12764
  if (target.error) return writeFailure(command, target.error, mode, 1);
12219
12765
  const threadId = requiredOption(parsed.options.threadId, "--thread-id is required.", "Run comments list and retry with a listed thread_id.");
12220
12766
  if (threadId.error) return writeFailure(command, threadId.error, mode, 1);
12221
- const result = await postCommentAction(parsed, command, target.artifactId, {
12767
+ const result = await postCommentAction(parsed, command, target.artifactId, action === "resolve" ? {
12768
+ action,
12769
+ thread_id: threadId.value
12770
+ } : {
12222
12771
  action,
12223
12772
  thread_id: threadId.value
12224
12773
  }, mode);
12225
12774
  if (!result) return;
12226
- const responseThreadId = configString(result.thread_id);
12227
- if (!responseThreadId || result.thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
12775
+ const actionResponse = isContract(COMMENT_ACTION_RESPONSE_SCHEMA, result) ? result : null;
12776
+ const actionRaw = isRecord$1(result) ? result : null;
12777
+ const responseThreadId = configString(actionResponse?.thread_id ?? actionRaw?.thread_id);
12778
+ const thread = actionResponse?.thread ?? actionRaw?.thread;
12779
+ if (!responseThreadId || thread === void 0) return writeFailure(command, serviceError("Comment was changed but the response had no thread."), mode, 1);
12228
12780
  writeSuccess(command, {
12229
12781
  artifact_id: target.artifactId,
12230
- share_url: configString(result.share_url),
12782
+ share_url: configString(actionResponse?.share_url ?? actionRaw?.share_url),
12231
12783
  thread_id: responseThreadId,
12232
- thread: result.thread
12784
+ thread
12233
12785
  }, mode);
12234
12786
  }
12235
12787
  async function postCommentAction(parsed, command, artifactId, payload, mode) {
@@ -12414,17 +12966,21 @@ async function runDoctor(parsed, mode) {
12414
12966
  return writeSuccess(command, doctorDataWithNextCommand(data), mode);
12415
12967
  }
12416
12968
  data.network.ok = true;
12417
- const body = result.data.body;
12969
+ const rawBody = result.data.body;
12970
+ const body = isContract(CLI_DOCTOR_RESPONSE_SCHEMA, rawBody) ? rawBody : isRecord$1(rawBody) ? rawBody : null;
12418
12971
  if (!body) throw new Error("Doctor response was not valid JSON.");
12419
- data.auth.ok = body.auth?.ok ?? true;
12420
- data.auth.email = body.user?.email ?? null;
12421
- const authority = doctorAuthority(body.auth?.authority);
12972
+ const auth = isRecord$1(body.auth) ? body.auth : null;
12973
+ const user = isRecord$1(body.user) ? body.user : null;
12974
+ const upload = isRecord$1(body.upload) ? body.upload : null;
12975
+ data.auth.ok = typeof auth?.ok === "boolean" ? auth.ok : true;
12976
+ data.auth.email = typeof user?.email === "string" ? user.email : null;
12977
+ const authority = doctorAuthority(auth?.authority);
12422
12978
  if (authority) data.auth.authority = authority;
12423
12979
  applyAgentDestinationDiagnostic(data, authority);
12424
12980
  data.upload.checked = true;
12425
- data.upload.ok = body.upload?.ok ?? false;
12981
+ data.upload.ok = upload?.ok === true;
12426
12982
  if (!data.upload.ok) {
12427
- data.upload.code = normalizeApiCode(body.upload?.code);
12983
+ data.upload.code = normalizeApiCode(upload?.code);
12428
12984
  data.upload.hint = uploadBlockedHint(data.upload.code);
12429
12985
  }
12430
12986
  return writeSuccess(command, doctorDataWithNextCommand(data), mode);
@@ -12901,8 +13457,14 @@ async function runProjectDownload(parsed, mode, projectId, isRetry = false) {
12901
13457
  }),
12902
13458
  authFailure: response.status === 401
12903
13459
  };
12904
- if (!body || !Array.isArray(body.artifacts) || typeof body.has_more !== "boolean") return { error: serviceError("Artifact list response was invalid.") };
12905
- return { data: body };
13460
+ const contracted = ARTIFACTS_LIST_RESPONSE_SCHEMA.safeParse(body);
13461
+ const raw = isRecord$1(body) ? body : null;
13462
+ if (!contracted.success && (!raw || !Array.isArray(raw.artifacts) || typeof raw.has_more !== "boolean")) return { error: serviceError("Artifact list response was invalid.") };
13463
+ return { data: contracted.success ? contracted.data : {
13464
+ artifacts: raw.artifacts,
13465
+ has_more: raw.has_more,
13466
+ next_cursor: typeof raw.next_cursor === "string" || raw.next_cursor === null ? raw.next_cursor : void 0
13467
+ } };
12906
13468
  };
12907
13469
  const entries = [];
12908
13470
  let cursor;
@@ -13129,41 +13691,19 @@ function normalizedEmailOptions(value) {
13129
13691
  return { values };
13130
13692
  }
13131
13693
  function parseEditData(body) {
13132
- if (!isRecord$1(body)) return null;
13133
- const artifact = body.artifact;
13134
- const destination = body.destination;
13135
- const share = body.share;
13136
- if (!isRecord$1(artifact) || !isRecord$1(destination) || !isRecord$1(share)) return null;
13137
- if (typeof artifact.id !== "string" || typeof body.title !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string") return null;
13138
- const base = {
13694
+ const result = CLI_EDIT_RESPONSE_SCHEMA.safeParse(body);
13695
+ if (!result.success) return null;
13696
+ return {
13697
+ ...result.data,
13139
13698
  artifact: {
13140
- id: artifact.id,
13141
- url: typeof artifact.url === "string" ? artifact.url : null
13699
+ ...result.data.artifact,
13700
+ url: result.data.artifact.url ?? null
13142
13701
  },
13143
- title: body.title,
13144
13702
  share: {
13145
- visibility: share.visibility,
13146
- link_expires_at: typeof share.link_expires_at === "string" || share.link_expires_at === null ? share.link_expires_at : null
13703
+ ...result.data.share,
13704
+ link_expires_at: result.data.share.link_expires_at ?? null
13147
13705
  }
13148
13706
  };
13149
- if (destination.type === "project") {
13150
- if (typeof destination.project_id !== "string") return null;
13151
- return {
13152
- ...base,
13153
- destination: {
13154
- type: "project",
13155
- project_id: destination.project_id
13156
- }
13157
- };
13158
- }
13159
- if (destination.type === "home" && destination.project_id === null) return {
13160
- ...base,
13161
- destination: {
13162
- type: "home",
13163
- project_id: null
13164
- }
13165
- };
13166
- return null;
13167
13707
  }
13168
13708
  //#endregion
13169
13709
  //#region src/git-exclude.ts
@@ -13380,7 +13920,7 @@ async function runMove(parsed, mode) {
13380
13920
  const request = await requestConfig(parsed.options);
13381
13921
  if (request.error) return writeFailure(command, request.error, mode, 1);
13382
13922
  const result = await runAuthenticatedApi(credential, parsed.options, async (current) => {
13383
- const moved = await apiPost(`/api/cli/shareables/${encodeURIComponent(target.artifactId)}/move`, current.token, { destination: home ? "home" : { project_id: projectId } }, parsed.options, request.init, {
13923
+ const moved = await apiPost(`/api/cli/shareables/${encodeURIComponent(target.artifactId)}/move`, current.token, buildMovePayload(home, projectId), parsed.options, request.init, {
13384
13924
  artifactTarget: true,
13385
13925
  credentialSource: current.source,
13386
13926
  profile: current.profile,
@@ -13394,45 +13934,19 @@ async function runMove(parsed, mode) {
13394
13934
  if (!data) return writeFailure(command, serviceError("Move succeeded but the response did not include move data."), mode, 1);
13395
13935
  writeSuccess(command, data, mode);
13396
13936
  }
13937
+ function buildMovePayload(home, projectId) {
13938
+ return { destination: home ? "home" : { project_id: projectId } };
13939
+ }
13397
13940
  function parseMoveData(body) {
13398
- if (!isRecord$1(body)) return null;
13399
- const artifact = body.artifact;
13400
- const destination = body.destination;
13401
- const share = body.share;
13402
- if (!isRecord$1(artifact) || !isRecord$1(destination) || !isRecord$1(share)) return null;
13403
- if (typeof artifact.id !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string" || typeof share.project_audience_may_change !== "boolean") return null;
13404
- if (destination.type === "project") {
13405
- if (typeof destination.project_id !== "string") return null;
13406
- return {
13407
- artifact: {
13408
- id: artifact.id,
13409
- url: typeof artifact.url === "string" ? artifact.url : null
13410
- },
13411
- destination: {
13412
- type: "project",
13413
- project_id: destination.project_id
13414
- },
13415
- share: {
13416
- visibility: share.visibility,
13417
- project_audience_may_change: share.project_audience_may_change
13418
- }
13419
- };
13420
- }
13421
- if (destination.type === "home" && destination.project_id === null) return {
13941
+ const result = CLI_MOVE_RESPONSE_SCHEMA.safeParse(body);
13942
+ if (!result.success) return null;
13943
+ return {
13944
+ ...result.data,
13422
13945
  artifact: {
13423
- id: artifact.id,
13424
- url: typeof artifact.url === "string" ? artifact.url : null
13425
- },
13426
- destination: {
13427
- type: "home",
13428
- project_id: null
13429
- },
13430
- share: {
13431
- visibility: share.visibility,
13432
- project_audience_may_change: share.project_audience_may_change
13946
+ ...result.data.artifact,
13947
+ url: result.data.artifact.url ?? null
13433
13948
  }
13434
13949
  };
13435
- return null;
13436
13950
  }
13437
13951
  //#endregion
13438
13952
  //#region src/command-runners/profiles.ts
@@ -13580,16 +14094,17 @@ async function importBotTokenProfile(command, profile, token, parsed, mode) {
13580
14094
  if (response.status === 401) return writeFailure(command, botTokenInvalidError(profile), mode, 1);
13581
14095
  return writeFailure(command, mapApiError(response.status, body, { baseUrl: baseUrlOf(parsed.options) }), mode, 1);
13582
14096
  }
13583
- if (typeof body?.access_token !== "string" || body.access_token.length === 0 || typeof body.expires_at !== "string" || typeof body.refresh_token !== "string" || !body.refresh_token || typeof body.refresh_token_expires_at !== "string") return writeFailure(command, validationError("The refresh response was invalid.", "Ask a workspace administrator to reissue the bot token, then retry with the new token.", "service_error"), mode, 1);
14097
+ const refresh = RotatingCliAuthRefreshResponseSchema.safeParse(body);
14098
+ if (!refresh.success || refresh.data.token_type.toLowerCase() !== "bearer") return writeFailure(command, validationError("The refresh response was invalid.", "Ask a workspace administrator to reissue the bot token, then retry with the new token.", "service_error"), mode, 1);
13584
14099
  const saved = await saveProfileSessionCredential(profile, {
13585
14100
  kind: "session",
13586
- session_token: body.access_token,
13587
- refresh_token: body.refresh_token,
13588
- expires_at: body.expires_at,
13589
- refresh_credential_expires_at: body.refresh_token_expires_at
14101
+ session_token: refresh.data.access_token,
14102
+ refresh_token: refresh.data.refresh_token,
14103
+ expires_at: refresh.data.expires_at,
14104
+ refresh_credential_expires_at: refresh.data.refresh_token_expires_at
13590
14105
  }, parsed.options);
13591
14106
  if (!saved.ok) return writeFailure(command, validationError("The rotated bot credential could not be stored; the imported token is now consumed and lost.", "Fix the token store, ask a workspace administrator to reissue the bot token, and import the new token.", "token_store_unavailable"), mode, 1);
13592
- const whoamiResult = await apiGet("/api/cli/whoami", body.access_token, parsed.options, request.init, {
14107
+ const whoamiResult = await apiGet("/api/cli/whoami", refresh.data.access_token, parsed.options, request.init, {
13593
14108
  authenticated: true,
13594
14109
  baseUrl: baseUrlOf(parsed.options)
13595
14110
  });
@@ -13693,15 +14208,17 @@ async function runShare(parsed, mode, isRetry = false) {
13693
14208
  if (parsed.options.linkExpiresAt !== void 0) initialForm.set("link_expires_at", parsed.options.linkExpiresAt);
13694
14209
  else if (parsed.options.noLinkExpiry === true) initialForm.set("link_expires_at", "null");
13695
14210
  if (parsed.options.noSlackNotify === true) initialForm.set("slack_notify", "false");
13696
- const uploadUrl = apiUrl("/api/shareables/uploads", baseUrl);
13697
- if (shareKey !== null) uploadUrl.searchParams.set("publish_key", shareKey);
13698
- if (parsed.options.expectedVersion) uploadUrl.searchParams.set("expected_version", parsed.options.expectedVersion);
14211
+ const uploadQuery = {};
14212
+ if (shareKey !== null) uploadQuery.publish_key = shareKey;
14213
+ if (parsed.options.expectedVersion) uploadQuery.expected_version = parsed.options.expectedVersion;
13699
14214
  const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
13700
14215
  if (upload.error) return writeFailure(command, upload.error, mode, 1);
13701
14216
  if (upload.payload.kind === "static_site") {
13702
- uploadUrl.searchParams.set("artifact_kind", "static_site");
13703
- if (destination.containerId) uploadUrl.searchParams.set("container_id", destination.containerId);
14217
+ uploadQuery.artifact_kind = "static_site";
14218
+ if (destination.containerId) uploadQuery.container_id = destination.containerId;
13704
14219
  }
14220
+ const uploadUrl = apiUrl("/api/shareables/uploads", baseUrl);
14221
+ for (const [key, value] of Object.entries(uploadQuery)) if (value !== void 0) uploadUrl.searchParams.set(key, value);
13705
14222
  const uploaded = await postShareUpload({
13706
14223
  uploadUrl,
13707
14224
  token: credential.token,
@@ -13807,6 +14324,8 @@ async function runUpdate(parsed, mode, isRetry = false) {
13807
14324
  if (unsupportedOption) return writeFailure(command, validationError(`Update does not accept --${unsupportedOption}.`, "Update only adds a new version. Remove unsupported options and retry."), mode, 1);
13808
14325
  const artifactId = resolveArtifactId(artifactInput);
13809
14326
  if (!artifactId) return writeFailure(command, targetResolutionError(artifactInput, "update"), mode, 1);
14327
+ const label = VersionLabelInputSchema.optional().safeParse(parsed.options.label);
14328
+ if (!label.success) return writeFailure(command, validationError("Invalid version label.", label.error.issues[0]?.message ?? "Check the label and retry."), mode, 1);
13810
14329
  const credential = await resolveCredential(parsed.options, await resolveProjectConfig());
13811
14330
  if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
13812
14331
  const fileStat = await stat(targetPath).catch(() => null);
@@ -13816,9 +14335,11 @@ async function runUpdate(parsed, mode, isRetry = false) {
13816
14335
  if (request.error) return writeFailure(command, request.error, mode, 1);
13817
14336
  const upload = await prepareUploadPayload(targetPath, fileStat);
13818
14337
  if (upload.error) return writeFailure(command, upload.error, mode, 1);
14338
+ const updateQuery = label.data !== void 0 ? { label: label.data } : {};
14339
+ if (upload.payload.kind === "static_site") updateQuery.artifact_kind = "static_site";
14340
+ if (parsed.options.expectedVersion) updateQuery.expected_version = parsed.options.expectedVersion;
13819
14341
  const updateUrl = apiUrl(`/api/shareables/${encodeURIComponent(artifactId)}/versions`, baseUrl);
13820
- if (upload.payload.kind === "static_site") updateUrl.searchParams.set("artifact_kind", "static_site");
13821
- if (parsed.options.expectedVersion) updateUrl.searchParams.set("expected_version", parsed.options.expectedVersion);
14342
+ for (const [key, value] of Object.entries(updateQuery)) if (value !== void 0) updateUrl.searchParams.set(key, value);
13822
14343
  const response = await cliFetch(updateUrl, {
13823
14344
  method: "POST",
13824
14345
  headers: { Authorization: `Bearer ${credential.token}` },
@@ -13837,14 +14358,19 @@ async function runUpdate(parsed, mode, isRetry = false) {
13837
14358
  profileCredentialKind: credential.profileCredentialKind,
13838
14359
  botProfile: credential.botProfile
13839
14360
  }), credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
13840
- const id = body?.id ?? artifactId;
14361
+ const responseBody = isContract(ARTIFACT_VERSION_UPDATE_RESPONSE_SCHEMA, body) ? body : null;
14362
+ const id = responseBody?.id ?? artifactId;
13841
14363
  const result = {
13842
14364
  artifact: {
13843
14365
  id,
13844
- url: body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
13845
- kind: body?.artifactKind ?? upload.payload.kind
14366
+ url: responseBody?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
14367
+ kind: responseBody?.artifactKind ?? upload.payload.kind
14368
+ },
14369
+ version: {
14370
+ ...responseBody?.number !== void 0 ? { number: responseBody.number } : {},
14371
+ id: responseBody?.versionId ?? null,
14372
+ label: responseBody?.label !== void 0 ? responseBody.label : label.data ?? null
13846
14373
  },
13847
- version: { id: body?.versionId ?? null },
13848
14374
  result: { updated: true }
13849
14375
  };
13850
14376
  if (!updateSuccessFields(result)) return writeFailure(command, serviceError("Update succeeded but the response did not include an artifact id, URL, and version id."), mode, 1);
@@ -13894,13 +14420,14 @@ async function runAppend(parsed, mode, isRetry = false) {
13894
14420
  profileCredentialKind: credential.profileCredentialKind,
13895
14421
  botProfile: credential.botProfile
13896
14422
  }), credential, parsed.options, mode, () => runAppend(parsed, mode, true), isRetry);
14423
+ const responseBody = isContract(ARTIFACT_APPEND_RESPONSE_SCHEMA, body) ? body : null;
13897
14424
  const success = {
13898
14425
  artifact: {
13899
- id: body?.id ?? id,
13900
- url: body?.shareUrl ?? `${baseUrlOf(parsed.options)}/a/${id}`,
13901
- kind: body?.artifactKind
14426
+ id: responseBody?.id ?? id,
14427
+ url: responseBody?.shareUrl ?? `${baseUrlOf(parsed.options)}/a/${id}`,
14428
+ kind: responseBody?.artifactKind
13902
14429
  },
13903
- version: { id: body?.versionId },
14430
+ version: { id: responseBody?.versionId },
13904
14431
  result: { appended: true }
13905
14432
  };
13906
14433
  if (!updateSuccessFields(success)) return writeFailure(command, validationError("Append succeeded but the response was incomplete.", "Retry the command."), mode, 1);
@@ -13925,8 +14452,10 @@ async function runWhoami(parsed, mode) {
13925
14452
  });
13926
14453
  if (whoami.error) return writeFailure(command, whoami.error, mode, 1);
13927
14454
  const renewal = await renewalDetails(credential, parsed.options);
13928
- return writeSuccess(command, isRecord$1(whoami.data) ? {
13929
- ...whoami.data,
14455
+ const identity = CLI_WHOAMI_RESPONSE_SCHEMA.safeParse(whoami.data);
14456
+ const data = identity.success ? identity.data : isRecord$1(whoami.data) ? whoami.data : null;
14457
+ return writeSuccess(command, data ? {
14458
+ ...data,
13930
14459
  credential_source: credential.source,
13931
14460
  ...renewal
13932
14461
  } : {
@@ -14168,6 +14697,7 @@ async function logoutRunner(ctx) {
14168
14697
  }
14169
14698
  async function updateRunner(ctx) {
14170
14699
  const parsed = parsedArgsFromContext("update", ctx);
14700
+ if (ctx.tokens.filter((token) => token.kind === "option" && token.name === "label").length > 1) return writeFailure("update", validationError("Invalid version label.", "Pass --label once."), outputMode(parsed.options), 1);
14171
14701
  return await runWithSkillAutoUpdate(parsed, () => runUpdate(parsed, outputMode(parsed.options)));
14172
14702
  }
14173
14703
  async function appendRunner(ctx) {
@@ -14178,8 +14708,9 @@ async function editRunner(ctx) {
14178
14708
  const parsed = parsedArgsFromContext("edit", ctx);
14179
14709
  return await runWithSkillAutoUpdate(parsed, () => runEdit(parsed, outputMode(parsed.options)));
14180
14710
  }
14181
- async function deleteRunner(ctx) {
14182
- const parsed = parsedArgsFromContext("delete", ctx);
14711
+ async function deleteRunner(ctx, invocationPath = "delete") {
14712
+ const parsed = parsedArgsFromContext(invocationPath, ctx);
14713
+ parsed.command = "delete";
14183
14714
  return await runWithSkillAutoUpdate(parsed, () => runDelete(parsed, outputMode(parsed.options)));
14184
14715
  }
14185
14716
  async function resolveRunner(ctx) {
@@ -14524,7 +15055,7 @@ Common failures:
14524
15055
  auth_required Use ${TOKEN_ENV_VAR} or ${TOKEN_OPTION}; tokens are issued at ${DEFAULT_BASE_URL}/settings/tokens
14525
15056
  invalid_destination Choose --project-id <id> or --home
14526
15057
  target_not_found Use an artifact ID, share URL, or sandbox URL
14527
- upload_not_allowed Sharing is temporarily unavailable; contact Artifact Share support`,
15058
+ self_upload_disabled Sign in with Google or Microsoft to upload your own files`,
14528
15059
  run: () => {}
14529
15060
  });
14530
15061
  const loginDefinition = define({
@@ -14655,7 +15186,7 @@ For repeat jobs, use --key: first share creates the artifact, later runs add ver
14655
15186
 
14656
15187
  Common failures:
14657
15188
  auth_required Set ARTIFACTSHARE_TOKEN before share
14658
- upload_not_allowed Publishing is temporarily unavailable; contact Artifact Share support
15189
+ self_upload_disabled Sign in with Google or Microsoft to upload your own files
14659
15190
  file_too_large Reduce file or directory size and retry
14660
15191
  validation_failed Check file type (.html / .md for single files) and directory layout
14661
15192
  key_target_moved The artifact for --key moved; update it by ID or use a new key
@@ -14667,30 +15198,50 @@ const updateDefinition = define({
14667
15198
  toKebab: true,
14668
15199
  args: {
14669
15200
  ...commonArgs,
15201
+ json: {
15202
+ ...commonArgs.json,
15203
+ description: "Print stable JSON output; data.version.number matches the Viewer version number; data.version.label is the stored label or null when omitted"
15204
+ },
14670
15205
  artifactIdOrUrl: {
14671
15206
  type: "positional",
14672
15207
  toKebab: true,
14673
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15208
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14674
15209
  },
14675
15210
  path: {
14676
15211
  type: "positional",
14677
15212
  description: "File or directory to add as the new version"
14678
15213
  },
15214
+ label: {
15215
+ type: "string",
15216
+ description: "Optional version note (1–80 Unicode code points; NFC normalized, outer spaces trimmed)"
15217
+ },
14679
15218
  expectedVersion: {
14680
15219
  type: "string",
14681
15220
  toKebab: true,
14682
- description: "Only update when this is still the current version id"
15221
+ description: "Only update when this is still the current version id; required for agent-preset logins"
14683
15222
  }
14684
15223
  },
14685
15224
  examples: `Target:
14686
- Accepts an artifact ID, /a/<id> share URL, or <id>.sandbox.* URL.
15225
+ Accepts an artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL.
14687
15226
  Titles and project names are not updated directly; resolve them to an ID first.
14688
15227
 
15228
+ Access:
15229
+ You can update your own artifact or another artifact you have collaborative access to.
15230
+ A verified external viewer can update an artifact explicitly shared with their email
15231
+ when the artifact workspace allows external posting.
15232
+
15233
+ After login --preset agent, pass --expected-version <version-id> using
15234
+ data.version.id from the previous successful share or update output.
15235
+
15236
+ JSON output:
15237
+ Successful JSON includes the stored label at data.version.label, or null when omitted. data.version.number matches the Viewer version number (v{number}); older servers may omit it.
15238
+
14689
15239
  Common failures:
15240
+ expected_version_required Pass --expected-version <version-id>, using data.version.id from the previous successful share or update output.
14690
15241
  auth_required Set ARTIFACTSHARE_TOKEN before update
14691
15242
  target_not_found Retry with an artifact ID, share URL, or sandbox URL
14692
15243
  artifact_kind_mismatch Use a file for single-file artifacts or a directory for static sites
14693
- upload_not_allowed Publishing is temporarily unavailable; contact Artifact Share support
15244
+ self_upload_disabled Sign in with Google or Microsoft to upload your own files
14694
15245
  file_too_large Reduce file or directory size and retry
14695
15246
  validation_failed Check file type (.html / .md for single files) and directory layout`
14696
15247
  });
@@ -14721,7 +15272,7 @@ const editDefinition = define({
14721
15272
  artifactIdOrUrl: {
14722
15273
  type: "positional",
14723
15274
  toKebab: true,
14724
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15275
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14725
15276
  },
14726
15277
  title: {
14727
15278
  type: "string",
@@ -14793,7 +15344,7 @@ const deleteDefinition = define({
14793
15344
  artifactIdOrUrl: {
14794
15345
  type: "positional",
14795
15346
  toKebab: true,
14796
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15347
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14797
15348
  }
14798
15349
  },
14799
15350
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare delete abc123def4 --json
@@ -14839,7 +15390,7 @@ const downloadDefinition = define({
14839
15390
  type: "positional",
14840
15391
  toKebab: true,
14841
15392
  required: false,
14842
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15393
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14843
15394
  },
14844
15395
  projectId: {
14845
15396
  type: "string",
@@ -14879,7 +15430,7 @@ const openDefinition = define({
14879
15430
  artifactIdOrUrl: {
14880
15431
  type: "positional",
14881
15432
  toKebab: true,
14882
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15433
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14883
15434
  }
14884
15435
  },
14885
15436
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare open https://artifactshare.com/a/abc123def4 --json
@@ -14908,7 +15459,7 @@ const moveDefinition = define({
14908
15459
  artifactIdOrUrl: {
14909
15460
  type: "positional",
14910
15461
  toKebab: true,
14911
- description: "Artifact ID or /a/<id> share URL"
15462
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14912
15463
  },
14913
15464
  projectId: {
14914
15465
  type: "string",
@@ -14943,7 +15494,7 @@ const artifactsGetDefinition = define({
14943
15494
  artifactIdOrUrl: {
14944
15495
  type: "positional",
14945
15496
  toKebab: true,
14946
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15497
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
14947
15498
  },
14948
15499
  offset: {
14949
15500
  type: "string",
@@ -15012,18 +15563,21 @@ Common failures:
15012
15563
  });
15013
15564
  const artifactsDefinition = define({
15014
15565
  name: "artifacts",
15015
- description: "Read Artifact Share artifacts.",
15566
+ description: "List, read, and delete Artifact Share artifacts.",
15016
15567
  toKebab: true,
15017
15568
  args: commonArgs,
15018
15569
  subCommands: {
15019
15570
  list: lazyCommand(artifactsListDefinition, artifactsListRunner),
15020
- get: lazyCommand(artifactsGetDefinition, artifactsGetRunner)
15571
+ get: lazyCommand(artifactsGetDefinition, artifactsGetRunner),
15572
+ delete: lazyCommand(deleteDefinition, (ctx) => deleteRunner(ctx, "artifacts delete"))
15021
15573
  },
15022
15574
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts list --json
15023
15575
  npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts get <artifact-id-or-url> --json
15024
15576
 
15025
15577
  Use artifacts list to find IDs for update, edit, move, delete, artifacts get, and comments list.
15026
- Use artifacts get to read back Markdown or HTML before update.`,
15578
+ Use artifacts get to read back Markdown or HTML before update.
15579
+ Use artifacts delete as an alias of top-level delete:
15580
+ npm exec --yes --package=@artifactshare/cli -- artifactshare artifacts delete <artifact-id-or-url> --json`,
15027
15581
  run: parentCommandRunner("artifacts")
15028
15582
  });
15029
15583
  const commentsListDefinition = define({
@@ -15035,7 +15589,7 @@ const commentsListDefinition = define({
15035
15589
  artifactIdOrUrl: {
15036
15590
  type: "positional",
15037
15591
  toKebab: true,
15038
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15592
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15039
15593
  }
15040
15594
  },
15041
15595
  examples: `npm exec --yes --package=@artifactshare/cli -- artifactshare comments list abc123def4 --json
@@ -15056,7 +15610,7 @@ const commentsPostDefinition = define({
15056
15610
  artifactIdOrUrl: {
15057
15611
  type: "positional",
15058
15612
  toKebab: true,
15059
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15613
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15060
15614
  },
15061
15615
  body: {
15062
15616
  type: "string",
@@ -15108,7 +15662,7 @@ const commentThreadActionArgs = {
15108
15662
  artifactIdOrUrl: {
15109
15663
  type: "positional",
15110
15664
  toKebab: true,
15111
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15665
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15112
15666
  },
15113
15667
  threadId: {
15114
15668
  type: "string",
@@ -15121,7 +15675,7 @@ const commentMessageActionArgs = {
15121
15675
  artifactIdOrUrl: {
15122
15676
  type: "positional",
15123
15677
  toKebab: true,
15124
- description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
15678
+ description: "Artifact ID, /a/<id> share URL, artifactshare.link viewer/content URL, or sandbox URL"
15125
15679
  },
15126
15680
  messageId: {
15127
15681
  type: "string",
@@ -15608,7 +16162,7 @@ The response includes project.id and next_command for share --project-id.
15608
16162
 
15609
16163
  Common failures:
15610
16164
  auth_required Set ARTIFACTSHARE_TOKEN before projects create
15611
- upload_not_allowed Publishing is temporarily unavailable; contact Artifact Share support
16165
+ self_upload_disabled Sign in with Google or Microsoft to upload your own files
15612
16166
  project_name_conflict Choose another name or archive the existing project first
15613
16167
  validation_failed Pass a non-empty name and valid --visibility`
15614
16168
  });