@north-light/cli 0.3.706 → 0.3.708
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/api/client.d.ts +1 -2
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/human.d.ts +9 -6
- package/dist/api/dto/inbox.d.ts +2 -0
- package/dist/api/dto/review-comments.d.ts +12 -35
- package/dist/api/dto/reviews.d.ts +3 -10
- package/dist/api/routes.d.ts +0 -1
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/05-kinds/review/companion/00-base.md +2 -2
- package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
- package/dist/clients/attach/chrome/canvas-panels.d.ts +1 -1
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/chrome/status-line.js +1 -1
- package/dist/clients/attach/chrome/ticket-panel.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +0 -1
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/input/overlay-owner.d.ts +0 -1
- package/dist/clients/attach/input/overlay-owner.js +1 -1
- package/dist/clients/attach/session/keys.d.ts +0 -2
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/surface-host.d.ts +0 -5
- package/dist/clients/attach/session/surface-host.js +1 -1
- package/dist/clients/attach/viewer.js +545 -560
- package/dist/clients/editor-roundtrip.js +3 -0
- package/dist/clients/inbox/controller.d.ts +1 -6
- package/dist/clients/inbox/controller.js +1 -1
- package/dist/clients/inbox/dto-adapt.js +1 -1
- package/dist/clients/inbox/tui/page-body.js +1 -1
- package/dist/clients/inbox/tui/render.js +2 -2
- package/dist/clients/open-browser.d.ts +2 -0
- package/dist/clients/open-browser.js +1 -0
- package/dist/clients/surfaces/host.d.ts +0 -6
- package/dist/commands/human/review.js +1 -1
- package/dist/commands/sys/context/admin/shell.js +1 -1
- package/dist/core/canvas/schema-pg/025-review-anchors.sql +19 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/human/page-markdown.js +10 -12
- package/dist/core/human/tickets.js +1 -1
- package/dist/core/human/types.d.ts +4 -6
- package/dist/core/keybindings/attach-control.d.ts +0 -3
- package/dist/core/keybindings/attach-control.js +1 -1
- package/dist/core/keybindings/catalog.d.ts +1 -1
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/review/anchors.d.ts +28 -0
- package/dist/core/review/anchors.js +6 -0
- package/dist/core/review/comments.d.ts +2 -2
- package/dist/core/review/comments.js +7 -8
- package/dist/core/review/companion.d.ts +2 -1
- package/dist/core/review/companion.js +1 -1
- package/dist/core/review/document.d.ts +4 -17
- package/dist/core/review/document.js +1 -2
- package/dist/core/review/fork.js +2 -4
- package/dist/core/review/project.d.ts +1 -1
- package/dist/core/review/project.js +2 -2
- package/dist/core/review/realize.js +1 -1
- package/dist/core/review/stage.d.ts +2 -9
- package/dist/core/review/stage.js +1 -1
- package/dist/core/review/types.d.ts +16 -12
- package/dist/core/review/types.js +1 -1
- package/dist/core/runtime/broker/turn-replies.d.ts +1 -3
- package/dist/core/runtime/broker-cli.js +3 -3
- package/dist/core/runtime/broker-extension-render.js +1 -1
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/daemon/api/canvas-host.js +1 -1
- package/dist/daemon/api/document-page.d.ts +12 -1
- package/dist/daemon/api/document-page.js +6 -6
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/handlers/review-comments.js +1 -1
- package/dist/daemon/api/handlers/reviews.js +1 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/review-page.d.ts +3 -0
- package/dist/daemon/api/review-page.js +13 -0
- package/dist/daemon/broker-memory-cap.d.ts +9 -0
- package/dist/daemon/broker-memory-cap.js +2 -0
- package/dist/daemon/broker-signals/bus.d.ts +1 -1
- package/dist/daemon/broker-signals/bus.js +1 -1
- package/dist/daemon/crtrd.js +14 -14
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/review/comment-notify.js +2 -2
- package/dist/daemon/review/deliver.d.ts +2 -2
- package/dist/daemon/review/deliver.js +6 -2
- package/dist/daemon/review/finish.js +1 -1
- package/dist/doc-editor/Geist-Variable.woff2 +0 -0
- package/dist/doc-editor/GeistMono-Variable.woff2 +0 -0
- package/dist/doc-editor/editor.css +1 -1
- package/dist/doc-editor/review.css +2 -0
- package/dist/doc-editor/review.js +149 -0
- package/dist/pi-extensions/canvas-review-boundary.js +3 -3
- package/dist/shared/turn-replies.d.ts +3 -3
- package/dist/shared/turn-replies.js +3 -3
- package/docs/sdk/release-notes.md +6 -0
- package/package.json +13 -4
- package/packages/crouter-api/dist/api/client.js +0 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +0 -1
- package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +3 -3
- package/packages/crouter-api/dist/clients/attach/chrome/roster.js +9 -20
- package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -6
- package/packages/crouter-api/dist/clients/attach/chrome/ticket-panel.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/controller.js +0 -3
- package/packages/crouter-api/dist/clients/attach/input/overlay-owner.js +0 -7
- package/packages/crouter-api/dist/clients/attach/session/keys.js +0 -1
- package/packages/crouter-api/dist/clients/attach/session/surface-host.js +0 -17
- package/packages/crouter-api/dist/clients/attach/viewer.js +0 -37
- package/packages/crouter-api/dist/clients/{inbox/review/roundtrip.js → editor-roundtrip.js} +1 -1
- package/packages/crouter-api/dist/clients/inbox/controller.js +12 -31
- package/packages/crouter-api/dist/clients/inbox/dto-adapt.js +1 -0
- package/packages/crouter-api/dist/clients/inbox/tui/page-body.js +0 -7
- package/packages/crouter-api/dist/clients/inbox/tui/render.js +0 -7
- package/packages/crouter-api/dist/clients/open-browser.js +6 -0
- package/packages/crouter-api/dist/commands/human/review.js +17 -18
- package/packages/crouter-api/dist/commands/sys/context/admin/shell.js +1 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/human/page-markdown.js +2 -6
- package/packages/crouter-api/dist/core/human/tickets.js +2 -11
- package/packages/crouter-api/dist/core/keybindings/attach-control.js +0 -1
- package/packages/crouter-api/dist/core/keybindings/catalog.js +1 -3
- package/packages/crouter-api/dist/core/review/anchors.js +91 -0
- package/packages/crouter-api/dist/core/review/comments.js +27 -46
- package/packages/crouter-api/dist/core/review/companion.js +5 -9
- package/packages/crouter-api/dist/core/review/document.js +17 -89
- package/packages/crouter-api/dist/core/review/project.js +2 -1
- package/packages/crouter-api/dist/core/review/types.js +2 -2
- package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +0 -5
- package/packages/crouter-api/dist/daemon/api/map.js +2 -6
- package/packages/crouter-api/dist/daemon/broker-signals/bus.js +1 -1
- package/packages/crouter-api/dist/daemon/review/deliver.js +4 -3
- package/packages/crouter-api/dist/daemon/review/finish.js +26 -47
- package/packages/crouter-api/dist/shared/turn-replies.js +9 -14
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +1740 -505
- package/dist/clients/attach/overlays/file-review.d.ts +0 -10
- package/dist/clients/attach/overlays/file-review.js +0 -2
- package/dist/clients/inbox/review/anchors.d.ts +0 -41
- package/dist/clients/inbox/review/anchors.js +0 -1
- package/dist/clients/inbox/review/comments-client.d.ts +0 -74
- package/dist/clients/inbox/review/comments-client.js +0 -1
- package/dist/clients/inbox/review/companion-pane.d.ts +0 -47
- package/dist/clients/inbox/review/companion-pane.js +0 -1
- package/dist/clients/inbox/review/document-surface.d.ts +0 -212
- package/dist/clients/inbox/review/document-surface.js +0 -2
- package/dist/clients/inbox/review/frame.d.ts +0 -57
- package/dist/clients/inbox/review/frame.js +0 -1
- package/dist/clients/inbox/review/keys.d.ts +0 -69
- package/dist/clients/inbox/review/keys.js +0 -1
- package/dist/clients/inbox/review/launch.d.ts +0 -16
- package/dist/clients/inbox/review/launch.js +0 -1
- package/dist/clients/inbox/review/live-source.d.ts +0 -24
- package/dist/clients/inbox/review/live-source.js +0 -1
- package/dist/clients/inbox/review/nvim.d.ts +0 -15
- package/dist/clients/inbox/review/nvim.js +0 -1
- package/dist/clients/inbox/review/remap.d.ts +0 -51
- package/dist/clients/inbox/review/remap.js +0 -1
- package/dist/clients/inbox/review/review-client.d.ts +0 -43
- package/dist/clients/inbox/review/review-client.js +0 -1
- package/dist/clients/inbox/review/roundtrip.js +0 -3
- package/dist/clients/inbox/review/state.d.ts +0 -153
- package/dist/clients/inbox/review/state.js +0 -4
- package/dist/clients/inbox/review-adapter.d.ts +0 -17
- package/dist/clients/inbox/review-adapter.js +0 -1
- package/dist/core/review/remap.d.ts +0 -24
- package/dist/core/review/remap.js +0 -19
- package/dist/core/review/signal.d.ts +0 -5
- package/dist/core/review/signal.js +0 -1
- package/packages/crouter-api/dist/clients/attach/overlays/file-review.js +0 -146
- package/packages/crouter-api/dist/clients/inbox/review/anchors.js +0 -89
- package/packages/crouter-api/dist/clients/inbox/review/comments-client.js +0 -103
- package/packages/crouter-api/dist/clients/inbox/review/companion-pane.js +0 -109
- package/packages/crouter-api/dist/clients/inbox/review/document-surface.js +0 -1268
- package/packages/crouter-api/dist/clients/inbox/review/frame.js +0 -309
- package/packages/crouter-api/dist/clients/inbox/review/keys.js +0 -133
- package/packages/crouter-api/dist/clients/inbox/review/launch.js +0 -170
- package/packages/crouter-api/dist/clients/inbox/review/live-source.js +0 -160
- package/packages/crouter-api/dist/clients/inbox/review/nvim.js +0 -43
- package/packages/crouter-api/dist/clients/inbox/review/remap.js +0 -157
- package/packages/crouter-api/dist/clients/inbox/review/review-client.js +0 -125
- package/packages/crouter-api/dist/clients/inbox/review/state.js +0 -315
- package/packages/crouter-api/dist/clients/inbox/review-adapter.js +0 -43
- package/packages/crouter-api/dist/core/review/signal.js +0 -12
- package/packages/crouter-api/dist/core/termrender/code-doc.js +0 -92
- /package/dist/clients/{inbox/review/roundtrip.d.ts → editor-roundtrip.d.ts} +0 -0
|
@@ -8,22 +8,23 @@ export type ReviewState = 'binding' | 'open' | 'approved' | 'canceled';
|
|
|
8
8
|
export type ReviewOriginKind = 'ticket' | 'inline';
|
|
9
9
|
export type CommentStatus = 'open' | 'resolved' | 'deleted';
|
|
10
10
|
export type CommentAuthorKind = 'human' | 'node';
|
|
11
|
-
export type CommentEventKind = 'created' | 'edited' | 'resolved' | 'reopened' | 'deleted' | '
|
|
12
|
-
export type ReviewErrorCode = 'review_origin_missing' | 'review_origin_unforkable' | 'review_branch_unavailable' | 'branch_lost' | 'review_companion_unbound' | 'review_bridge_unsubscribed' | 'review_target_unreviewable' | 'source_unreadable' | 'delivery_unroutable' | 'unknown_review' | 'review_terminal' | 'review_required' | 'stale_document' | 'stale_revision' | 'unknown_comment' | 'comment_deleted' | 'invalid_anchor' | '
|
|
11
|
+
export type CommentEventKind = 'created' | 'edited' | 'resolved' | 'reopened' | 'deleted' | 'notified' | 'notify_failed';
|
|
12
|
+
export type ReviewErrorCode = 'review_origin_missing' | 'review_origin_unforkable' | 'review_branch_unavailable' | 'branch_lost' | 'review_companion_unbound' | 'review_bridge_unsubscribed' | 'review_target_unreviewable' | 'source_unreadable' | 'delivery_unroutable' | 'unknown_review' | 'review_terminal' | 'review_required' | 'stale_document' | 'stale_revision' | 'unknown_comment' | 'comment_deleted' | 'invalid_anchor' | 'quote_not_found' | 'text_too_long' | 'comment_limit_reached' | 'stale_comment';
|
|
13
13
|
/** Limits */
|
|
14
14
|
export declare const COMMENT_TEXT_MAX = 8000;
|
|
15
|
-
export declare const COMMENT_QUOTE_MAX =
|
|
16
|
-
export declare const
|
|
15
|
+
export declare const COMMENT_QUOTE_MAX = 2000;
|
|
16
|
+
export declare const ANCHOR_CONTEXT_MAX = 32;
|
|
17
17
|
export declare const LIVE_COMMENTS_MAX = 500;
|
|
18
18
|
export declare const COMMENT_EVENTS_PAGE_DEFAULT = 200;
|
|
19
19
|
export declare const COMMENT_EVENTS_PAGE_MAX = 1000;
|
|
20
20
|
export declare const COMPANION_BIND_DEADLINE_MS = 90000;
|
|
21
21
|
export interface CommentAnchor {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
22
|
+
/** Selected text in the rendered document (whitespace-collapsed). */
|
|
23
|
+
quote: string;
|
|
24
|
+
prefix: string;
|
|
25
|
+
suffix: string;
|
|
26
|
+
/** Character offset in the rendered text when created; a tie-breaker only. */
|
|
27
|
+
offset: number;
|
|
27
28
|
}
|
|
28
29
|
export interface ReviewRow {
|
|
29
30
|
review_id: string;
|
|
@@ -83,9 +84,6 @@ export interface ReviewComment {
|
|
|
83
84
|
revision: number;
|
|
84
85
|
text: string;
|
|
85
86
|
anchor: CommentAnchor;
|
|
86
|
-
anchor_state: 'live' | 'detached';
|
|
87
|
-
anchor_line_text: string;
|
|
88
|
-
anchor_doc_hash: string;
|
|
89
87
|
author: {
|
|
90
88
|
kind: CommentAuthorKind;
|
|
91
89
|
node_id: string | null;
|
|
@@ -118,6 +116,12 @@ export interface ReviewCommentEvent {
|
|
|
118
116
|
export interface ReviewResult {
|
|
119
117
|
schema: 'humanloop.review-response/v1';
|
|
120
118
|
review_id: string;
|
|
119
|
+
document: {
|
|
120
|
+
id: string;
|
|
121
|
+
name: string;
|
|
122
|
+
base_revision: string | null;
|
|
123
|
+
approved_revision: string | null;
|
|
124
|
+
} | null;
|
|
121
125
|
file: string;
|
|
122
126
|
submitted: true;
|
|
123
127
|
approved: true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var e=(o,t)=>_(o,"name",{value:t,configurable:!0});const s=8e3,N=2e3,T=32,c=500,n=200,O=1e3,p=9e4;class A extends Error{static{e(this,"ReviewOperationError")}code;detail;constructor(t,r,E){super(r),this.code=t,this.detail=E,this.name="ReviewOperationError"}}export{T as ANCHOR_CONTEXT_MAX,n as COMMENT_EVENTS_PAGE_DEFAULT,O as COMMENT_EVENTS_PAGE_MAX,N as COMMENT_QUOTE_MAX,s as COMMENT_TEXT_MAX,p as COMPANION_BIND_DEADLINE_MS,c as LIVE_COMMENTS_MAX,A as ReviewOperationError};
|
|
@@ -13,9 +13,7 @@ export interface TurnReplyTrackerOptions {
|
|
|
13
13
|
*
|
|
14
14
|
* The open turn is a projection of the bound session's branch, so anything that
|
|
15
15
|
* moves the leaf in place (a fault-retry rewind, `/tree`) must call `seed()`
|
|
16
|
-
* again: otherwise prose from the abandoned branch stays in every later rewrite
|
|
17
|
-
* and the viewer — which honours a rewrite only when all its sources are still
|
|
18
|
-
* in the turn — falls back to showing every message verbatim. */
|
|
16
|
+
* again: otherwise prose from the abandoned branch stays in every later rewrite. */
|
|
19
17
|
export declare class TurnReplyTracker {
|
|
20
18
|
private readonly nodeId;
|
|
21
19
|
private readonly broadcast;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var c=Object.defineProperty;var n=(e,r)=>c(e,"name",{value:r,configurable:!0});import{isSafeNodeId as d}from"../canvas/paths.js";import{emitEvent as p,flushBrokerLog as
|
|
2
|
-
`),process.exit(1)),
|
|
3
|
-
`)}n(i,"reportFatal"),process.on("uncaughtException",e=>{i("uncaughtException",e),s(1)}),process.on("unhandledRejection",e=>{i("unhandledRejection",e),s(1)}),
|
|
1
|
+
var c=Object.defineProperty;var n=(e,r)=>c(e,"name",{value:r,configurable:!0});import{isSafeNodeId as d}from"../canvas/paths.js";import{emitEvent as p,flushBrokerLog as f}from"../events/emit.js";import{mark as a,timingProc as u}from"../timing.js";import{configureDaemonHttpDispatcher as l}from"../../daemon/http-dispatcher.js";const m=process.hrtime.bigint(),h=new Date().toISOString(),t=process.argv.length>2?process.argv.at(-1):void 0;(t===void 0||!d(t))&&(process.stderr.write(`[broker] usage: broker-cli [--canvas-home <path>] [--epoch <id>] <nodeId>
|
|
2
|
+
`),process.exit(1)),u("broker"),a("broker.entry",{node:t}),l();const{runBroker:g,disposeActiveSession:k}=await import("./broker.js");a("broker.module_loaded");function s(e){try{k()}catch{}f().finally(()=>process.exit(e))}n(s,"disposeAndExit");function i(e,r){let o;try{o=p({level:"error",event:"broker.runtime.fatal",error:r,fields:{origin:e}})}catch{o=!1}o||process.stderr.write(`[broker] fatal (${e}): ${r instanceof Error?r.stack??r.message:String(r)}
|
|
3
|
+
`)}n(i,"reportFatal"),process.on("uncaughtException",e=>{i("uncaughtException",e),s(1)}),process.on("unhandledRejection",e=>{i("unhandledRejection",e),s(1)}),g(t,m,h).catch(e=>{i("run_failure",e),s(1)});
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var u=Object.defineProperty;var i=(e,r)=>u(e,"name",{value:r,configurable:!0});import{fullName as h}from"../canvas/labels.js";import{profileNote as f,renderGraphMap as p,buildIdentityAssertion as m,forkContextNote as g,orchestratorContextNote as w,worktreeNote as k}from"./bearings-render.js";function S(e){const r=(e.icon??"").trim(),t=e.name!==e.kind?e.name.trim():"",n=t!==""?t:(e.description??"").trim()||e.name;return r===""?n:`${r} ${n}`}i(S,"editorLabelForBrokerNode");function y(e){return f(e.cwd,e.profile_id)}i(y,"profileNote");function b(e){const{ancestors:r,children:t,node:n}=e;return p(n.node_id,n.kind,n.mode,r,t)}i(b,"graphMap");function v(e){const{node:r,fork_source:t}=e,n=t===null?r.fork_from??"":`${r.fork_from} ("${h(t)}")`;return m(r.node_id,r.kind,r.mode,r.fork_from,n)}i(v,"identity");function _(e){return k(e.managed_worktree)}i(_,"worktreeNote");function x(e){const r=e.review_binding;if(r==null)return"";if(r.kind==="page_feedback"){const t=r.review_id,n=r.target_file;return`You exist for one page's feedback conversation \u2014 ticket \`${t}\`, page source \`${n}\`. Think with the person about this one page and answer in a few plain sentences from the context you already carry. Revise the page in place with \`crtr human send --replace ${t} --page ${n}\` \u2014 it swaps in on their screen immediately \u2014 and briefly say what changed; a silent swap leaves them guessing. After dealing with an open feedback item \u2014 by revising the page or answering it here \u2014 resolve it with \`crtr human feedback resolve <comment_id>\`; \`crtr human feedback list ${t}\` shows each item's id and status. Never author feedback or resolve an item before dealing with it \u2014 a sent comment is immutable, and resolution is your report that the work is done. Asked to act beyond this page, give your advice and point the person at submitting it: the submitted answer is what reaches the task's owner, while work done here is invisible to it and ends when the ticket settles. When a question needs real exploration, delegate it to a child node and keep talking while it runs. The inherited conversation belongs to the origin node, not you \u2014 its task stays with it; carry only the context needed for this page. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see \u2014 never treat it as shared ground; when they ask about it, answer plainly in your own words rather than replaying it.`}return`You exist for one human review of \`${r.target_file}\`. The inherited conversation belongs to the origin node, not you \u2014 carry only the context needed for this review. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see.`}i(x,"reviewNote");function F(e,r=""){const{node:t,fork_source:n}=e,l=n?.status==="active"||n?.status==="idle"?`Source node ${n.node_id} ("${h(n)}") is still live and still holds the mandate from the copied conversation; do not resume that work here.`:"The source node\u2019s earlier graph position, lifecycle, children, schedules, worktree, situational context, and context-directory path do not carry over. Shared conversation, project, and operating context remain reference material.",o=["<crtr-bearings>",v(e),"",l,"","## Your node now",`Lifecycle: ${t.lifecycle}.`],s=b(e);if(o.push(...s===""?["Canvas: independent root with no parent or inherited graph edges."]:["",s]),o.push(g(t.node_id,t.grantee,t.fork_from??"")),(n===null||n.cwd!==t.cwd)&&o.push(`Working directory: \`${t.cwd}\`.`),n===null||n.profile_id!==t.profile_id){const a=y(t);a!==""&&o.push(a)}const
|
|
1
|
+
var u=Object.defineProperty;var i=(e,r)=>u(e,"name",{value:r,configurable:!0});import{fullName as h}from"../canvas/labels.js";import{profileNote as f,renderGraphMap as p,buildIdentityAssertion as m,forkContextNote as g,orchestratorContextNote as w,worktreeNote as k}from"./bearings-render.js";function S(e){const r=(e.icon??"").trim(),t=e.name!==e.kind?e.name.trim():"",n=t!==""?t:(e.description??"").trim()||e.name;return r===""?n:`${r} ${n}`}i(S,"editorLabelForBrokerNode");function y(e){return f(e.cwd,e.profile_id)}i(y,"profileNote");function b(e){const{ancestors:r,children:t,node:n}=e;return p(n.node_id,n.kind,n.mode,r,t)}i(b,"graphMap");function v(e){const{node:r,fork_source:t}=e,n=t===null?r.fork_from??"":`${r.fork_from} ("${h(t)}")`;return m(r.node_id,r.kind,r.mode,r.fork_from,n)}i(v,"identity");function _(e){return k(e.managed_worktree)}i(_,"worktreeNote");function x(e){const r=e.review_binding;if(r==null)return"";if(r.kind==="page_feedback"){const t=r.review_id,n=r.target_file;return`You exist for one page's feedback conversation \u2014 ticket \`${t}\`, page source \`${n}\`. Think with the person about this one page and answer in a few plain sentences from the context you already carry. Revise the page in place with \`crtr human send --replace ${t} --page ${n}\` \u2014 it swaps in on their screen immediately \u2014 and briefly say what changed; a silent swap leaves them guessing. After dealing with an open feedback item \u2014 by revising the page or answering it here \u2014 resolve it with \`crtr human feedback resolve <comment_id>\`; \`crtr human feedback list ${t}\` shows each item's id and status. Never author feedback or resolve an item before dealing with it \u2014 a sent comment is immutable, and resolution is your report that the work is done. Asked to act beyond this page, give your advice and point the person at submitting it: the submitted answer is what reaches the task's owner, while work done here is invisible to it and ends when the ticket settles. When a question needs real exploration, delegate it to a child node and keep talking while it runs. The inherited conversation belongs to the origin node, not you \u2014 its task stays with it; carry only the context needed for this page. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see \u2014 never treat it as shared ground; when they ask about it, answer plainly in your own words rather than replaying it.`}return`You exist for one human review of the canvas document \`${r.target_file}\`, which you revise with \`crtr doc edit\`. The inherited conversation belongs to the origin node, not you \u2014 carry only the context needed for this review. The person's visible transcript begins at the boundary marker above; everything earlier is context they cannot see.`}i(x,"reviewNote");function F(e,r=""){const{node:t,fork_source:n}=e,l=n?.status==="active"||n?.status==="idle"?`Source node ${n.node_id} ("${h(n)}") is still live and still holds the mandate from the copied conversation; do not resume that work here.`:"The source node\u2019s earlier graph position, lifecycle, children, schedules, worktree, situational context, and context-directory path do not carry over. Shared conversation, project, and operating context remain reference material.",o=["<crtr-bearings>",v(e),"",l,"","## Your node now",`Lifecycle: ${t.lifecycle}.`],s=b(e);if(o.push(...s===""?["Canvas: independent root with no parent or inherited graph edges."]:["",s]),o.push(g(t.node_id,t.grantee,t.fork_from??"")),(n===null||n.cwd!==t.cwd)&&o.push(`Working directory: \`${t.cwd}\`.`),n===null||n.profile_id!==t.profile_id){const a=y(t);a!==""&&o.push(a)}const c=_(t);c!==""&&o.push("","## Your managed worktree",c),t.mode==="orchestrator"&&o.push("",w());const d=x(t);return d!==""&&o.push("",d),o.push("","The first real user message after these bearings is your mandate.","</crtr-bearings>"),[o.join(`
|
|
2
2
|
`),r].filter(a=>a!=="").join(`
|
|
3
3
|
`)}i(F,"buildForkBearingsFromState");export{F as buildForkBearingsFromState,S as editorLabelForBrokerNode};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var u=(e,n)=>Y(e,"name",{value:n,configurable:!0});import{mkdtempSync as Z,rmSync as V,writeFileSync as ee}from"node:fs";import{tmpdir as O}from"node:os";import{join as M}from"node:path";import{ATTACH_CONTROL_BINDINGS as U,BINDING_CATALOG as _,BINDING_IDS as ne,encodeAttachControlInput as q,formatGesture as te,isAttachPaneBinding as re,resolveUserKeybindingSettings as G}from"../keybindings/index.js";import{normalizeTmuxPassthrough as ie}from"../config.js";import{withExclusiveDirectoryLock as oe}from"../exclusive-lock.js";import{surfaceTmuxStyleArgs as se}from"./surface-bg.js";import{runTmux as f,shellQuote as h}from"./tmux-driver.js";const A="@crtr_keybindings_manifest",p="root",ue={"crtr.tmux.menu.promote":{description:"promote to orchestrator",action:{kind:"keys",keys:"/promote"}},"crtr.tmux.menu.resume":{description:"find node",action:{kind:"keys",keys:"/resume"}},"crtr.tmux.menu.dashboard":{description:"dashboard",action:{kind:"direct",run:"surface dashboard --pane {pane}"}},"crtr.tmux.menu.fork":{description:"fork into idle root",action:{kind:"direct",run:"node fork --pane {pane}"}},"crtr.tmux.menu.demote-mode":{description:"demote to base node",action:{kind:"direct",run:"node config --mode base --pane {pane}"}},"crtr.tmux.menu.demote":{description:"demote to terminal (finish when done)",action:{kind:"direct",run:"node lifecycle demote --pane {pane}"}},"crtr.tmux.menu.make-resident":{description:"make resident (interactable)",action:{kind:"direct",run:"node config --lifecycle resident --pane {pane}"}},"crtr.tmux.menu.detach":{description:"demote + close viewer",action:{kind:"direct",run:"node lifecycle demote --pane {pane} --detach"}},"crtr.tmux.menu.close-subtree":{description:"close agent + subtree",action:{kind:"direct",run:"node lifecycle close --pane {pane}"}},"crtr.tmux.menu.background-bash":{description:"background running bash",action:{kind:"direct",run:"node bash background --pane {pane}"}},"crtr.tmux.menu.file-review":{description:"review a file",action:{kind:"raw-keys",keys:"M-S-r"}},"crtr.tmux.menu.metadata":{description:"metadata",action:{kind:"keys",keys:"/node-metadata"}},"crtr.tmux.menu.more-detail":{description:"more detail",action:{kind:"keys",keys:"/more-detail"}},"crtr.tmux.menu.less-detail":{description:"less detail",action:{kind:"keys",keys:"/less-detail"}},"crtr.tmux.menu.context":{description:"context + reports",action:{kind:"keys",keys:"/context"}},"crtr.tmux.menu.providers":{description:"settings",action:{kind:"popup",run:"sys settings",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.provider-options":{description:"provider options",action:{kind:"popup",run:"sys settings --page provider-options",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.plugins":{description:"plugins",action:{kind:"popup",run:"pkg browse",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.analytics":{description:"analytics",action:{kind:"popup",run:"canvas analytics --pane {pane}",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.context-admin":{description:"context surface",action:{kind:"popup",run:"sys context admin",size:{w:"98%",h:"96%"}}},"crtr.tmux.menu.graph":{description:"canvas graph",action:{kind:"keys",keys:"/graph"}},"crtr.tmux.menu.focus-manager":{description:"go to manager",action:{kind:"command",run:"surface node focus {manager}"}},"crtr.tmux.menu.copy-id":{description:"copy node id",action:{kind:"direct",run:"surface node id --pane {pane}"}},"crtr.tmux.menu.reload-viewer":{description:"reload viewer",action:{kind:"literal-input",input:q("crtr.attach.reload-viewer")}},"crtr.tmux.menu.recap":{description:"generate recap",action:{kind:"keys",keys:"/recap"}},"crtr.tmux.menu.pin":{description:"pin conversation",action:{kind:"direct",run:"surface node pin --pane {pane}"}},"crtr.tmux.menu.issue.idea":{description:"idea",action:{kind:"popup",run:"canvas issue new --type idea"}},"crtr.tmux.menu.issue.bug":{description:"bug",action:{kind:"popup",run:"canvas issue new --type bug"}}};function b(e){return e.replace(/#/g,"##")}u(b,"escapeTmuxFormats");function ce(e){return e.map(h).join(" ")}u(ce,"tmuxCommand");const ae={w:"60%",h:"50%"};function j(e,n=!1,t=ae){const r=`crtr canvas chord --pane '#{pane_id}' --run ${h(b(e))}${n?" --interactive":""}`;return n?{argv:["display-popup","-E","-w",t.w,"-h",t.h,"-d","#{pane_current_path}",r],menu:`display-popup -E -w ${t.w} -h ${t.h} -d "#{pane_current_path}" ${h(r)}`}:{argv:["run-shell",`${r} >/dev/null 2>&1`],menu:`run-shell ${h(`${r} >/dev/null 2>&1`)}`}}u(j,"chordCommand");function de(e){const t=`crtr ${b(e).replace("{pane}","#{pane_id}")} >/dev/null 2>&1`;return{argv:["run-shell","-b",t],menu:`run-shell -b ${h(t)}`}}u(de,"directCommand");function z(e){switch(e.kind){case"disabled":return null;case"separator":return null;case"dismiss":return{argv:["refresh-client"],menu:"refresh-client"};case"keys":{const n=b(e.keys);return{argv:["send-keys",n,"Enter"],menu:`send-keys -t '#{pane_id}' ${h(n)} Enter`}}case"raw-keys":{const n=b(e.keys);return{argv:["send-keys",n],menu:`send-keys -t '#{pane_id}' ${h(n)}`}}case"literal-input":{const n=b(e.input);return{argv:["send-keys","-l",n],menu:`send-keys -l -t '#{pane_id}' ${h(n)}`}}case"command":return j(e.run);case"direct":return de(e.run);case"popup":return j(e.run,!0,e.size);case"submenu":{const n=N(e.title,e.items);return{argv:n,menu:ce(n)}}}}u(z,"menuActionCommand");function me(e){return z(e)?.menu??""}u(me,"renderMenuAction");function pe(e){return e.replace(/#\[[^\]]*\]/g,"").length}u(pe,"menuItemWidth");function N(e,n){const t=b(e),r=n.reduce((o,c)=>Math.max(o,pe(c.description)),0),s=["display-menu","-T",`#[align=centre]${t}`,...se()];s.push("-x",`#{e|-:#{pane_right},${Math.max(t.length,r)+7}}`,"-y","#{e|+:#{pane_top},3}","--");for(const o of n){if(o.action.kind==="separator"){s.push("");continue}const c=o.action.kind==="disabled"?o.description:b(o.description);s.push(c,o.selector,me(o.action))}return s.push("","-esc / q to close","",""),s}u(N,"buildMenuArgs");const le={enter:"Enter",escape:"Escape",tab:"Tab",backspace:"BSpace",delete:"DC",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PPage",pagedown:"NPage",home:"Home",end:"End"};function F(e){if(e==="+")return{key:"+",modifiers:[]};if(e.endsWith("++"))return{key:"+",modifiers:e.slice(0,-2).split("+")};const n=e.split("+");return{key:n.pop(),modifiers:n}}u(F,"normalizedStrokeParts");function fe(e){return v(e)[0]}u(fe,"tmuxKey");function v(e){let{key:n,modifiers:t}=F(e);const r=new Set(t),s=u((o,c)=>[r.has("ctrl")?"C-":"",r.has("alt")?"M-":"",c?"S-":"",le[o]??o].join(""),"name");if(r.has("shift")&&n.length===1&&/[a-z]/.test(n)){const o=n.toUpperCase();return!r.has("ctrl")&&!r.has("alt")?[s(o,!1)]:[s(o,!0),s(o,!1),s(n,!0)]}return[s(n,r.has("shift"))]}u(v,"tmuxKeyNames");function ge(e){const{key:n,modifiers:t}=F(e);return t.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}u(ge,"menuSelector");function T(e,n,t){const r=[];for(const s of e){const o=n.get(s);if(o!==void 0)for(const c of t.gestures(s))r.push({description:o.description,selector:ge(c),action:o.action})}return r}u(T,"boundMenuItems");function K(e){const n=new Map;for(const[c,l]of Object.entries(ue))l!==void 0&&n.set(c,l);for(const{menuId:c,actionId:l}of U){const x=_.find(w=>w.id===l);if(x===void 0)throw new Error(`missing attach binding definition ${l}`);n.set(c,{description:x.name.toLowerCase(),action:{kind:"literal-input",input:q(l)}})}const t=T(U.map(({menuId:c})=>c),n,e);t.length>0&&n.set("crtr.tmux.menu.attach",{description:"attach viewer \u203A",action:{kind:"submenu",title:" attach viewer ",items:t}});const r=T(["crtr.tmux.menu.metadata","crtr.tmux.menu.context"],n,e);n.set("crtr.tmux.menu.show",{description:"inspect \u203A",action:{kind:"submenu",title:" inspect node ",items:r}});const s=T(["crtr.tmux.menu.more-detail","crtr.tmux.menu.less-detail"],n,e);n.set("crtr.tmux.menu.view-settings",{description:"display \u203A",action:{kind:"submenu",title:" display ",items:s}});const o=T(["crtr.tmux.menu.issue.idea","crtr.tmux.menu.issue.bug"],n,e);return n.set("crtr.tmux.menu.issues",{description:"create \u203A",action:{kind:"submenu",title:" create ",items:o}}),n}u(K,"resolvedMenuActions");function R(e,n){const t=u(c=>T(c,n,e),"boundItems"),r=[],s=u((c,l)=>{l.length!==0&&(r.length>0&&r.push({description:"",selector:"",action:{kind:"separator"}}),r.push({description:`-#[bold]${c}`,selector:"",action:{kind:"disabled"}},...l))},"addGroup");s("Explore",t(["crtr.tmux.menu.dashboard","crtr.tmux.menu.resume","crtr.tmux.menu.graph","crtr.tmux.menu.focus-manager","crtr.tmux.menu.show","crtr.tmux.menu.view-settings"])),s("Current node",t(["crtr.tmux.menu.attach","crtr.tmux.menu.background-bash","crtr.tmux.menu.file-review","crtr.tmux.menu.pin","crtr.tmux.menu.copy-id","crtr.tmux.menu.reload-viewer","crtr.tmux.menu.recap"])),s("Lifecycle",t(["crtr.tmux.menu.fork","crtr.tmux.menu.promote","crtr.tmux.menu.demote-mode","crtr.tmux.menu.demote","crtr.tmux.menu.make-resident","crtr.tmux.menu.detach","crtr.tmux.menu.close-subtree"])),s("System",t(["crtr.tmux.menu.providers","crtr.tmux.menu.provider-options","crtr.tmux.menu.plugins","crtr.tmux.menu.analytics","crtr.tmux.menu.context-admin","crtr.tmux.menu.issues"]));const o=e.gestures("crtr.tmux.menu.open");if(o.length>0&&r.length>0){r.push({description:"",selector:"",action:{kind:"separator"}});for(const c of o)r.push({description:`${te(c)} to close`,selector:fe(c),action:{kind:"dismiss"}})}return r}u(R,"menuItems");function Pe(e){const n=e??G().bindings;return N(" crtr ",R(n,K(n)))}u(Pe,"crouterMenuTmuxArgs");function S(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(t>=e.length)return null;let r=null,s="";for(;t<e.length;){const o=e[t];if(r===null&&/\s/.test(o))break;if(r===null&&(o==="'"||o==='"')){r=o,t+=1;continue}if(r===o){r=null,t+=1;continue}if(o==="\\"&&r!=="'"&&t+1<e.length){s+=e[t+1],t+=2;continue}s+=o,t+=1}return{value:s,end:t}}u(S,"readTmuxToken");function B(e){const n=S(e,0);if(n?.value!=="bind-key")return null;let t=n.end,r=!1;for(;;){const s=S(e,t);if(s===null)return null;if(t=s.end,s.value==="-r"){r=!0;continue}if(s.value!=="-T")continue;const o=S(e,t);if(o===null)return null;const c=S(e,o.end);return c===null?null:{table:o.value,key:c.value,command:e.slice(c.end).trimStart(),repeat:r}}}u(B,"parseTmuxBinding");function $(e,n){const t=f(["list-keys","-T",e]);return t.ok?t.stdout.split(`
|
|
1
|
+
var Y=Object.defineProperty;var u=(e,n)=>Y(e,"name",{value:n,configurable:!0});import{mkdtempSync as Z,rmSync as V,writeFileSync as ee}from"node:fs";import{tmpdir as O}from"node:os";import{join as M}from"node:path";import{ATTACH_CONTROL_BINDINGS as U,BINDING_CATALOG as _,BINDING_IDS as ne,encodeAttachControlInput as q,formatGesture as te,isAttachPaneBinding as re,resolveUserKeybindingSettings as G}from"../keybindings/index.js";import{normalizeTmuxPassthrough as ie}from"../config.js";import{withExclusiveDirectoryLock as oe}from"../exclusive-lock.js";import{surfaceTmuxStyleArgs as se}from"./surface-bg.js";import{runTmux as f,shellQuote as k}from"./tmux-driver.js";const A="@crtr_keybindings_manifest",p="root",ue={"crtr.tmux.menu.promote":{description:"promote to orchestrator",action:{kind:"keys",keys:"/promote"}},"crtr.tmux.menu.resume":{description:"find node",action:{kind:"keys",keys:"/resume"}},"crtr.tmux.menu.dashboard":{description:"dashboard",action:{kind:"direct",run:"surface dashboard --pane {pane}"}},"crtr.tmux.menu.fork":{description:"fork into idle root",action:{kind:"direct",run:"node fork --pane {pane}"}},"crtr.tmux.menu.demote-mode":{description:"demote to base node",action:{kind:"direct",run:"node config --mode base --pane {pane}"}},"crtr.tmux.menu.demote":{description:"demote to terminal (finish when done)",action:{kind:"direct",run:"node lifecycle demote --pane {pane}"}},"crtr.tmux.menu.make-resident":{description:"make resident (interactable)",action:{kind:"direct",run:"node config --lifecycle resident --pane {pane}"}},"crtr.tmux.menu.detach":{description:"demote + close viewer",action:{kind:"direct",run:"node lifecycle demote --pane {pane} --detach"}},"crtr.tmux.menu.close-subtree":{description:"close agent + subtree",action:{kind:"direct",run:"node lifecycle close --pane {pane}"}},"crtr.tmux.menu.background-bash":{description:"background running bash",action:{kind:"direct",run:"node bash background --pane {pane}"}},"crtr.tmux.menu.metadata":{description:"metadata",action:{kind:"keys",keys:"/node-metadata"}},"crtr.tmux.menu.more-detail":{description:"more detail",action:{kind:"keys",keys:"/more-detail"}},"crtr.tmux.menu.less-detail":{description:"less detail",action:{kind:"keys",keys:"/less-detail"}},"crtr.tmux.menu.context":{description:"context + reports",action:{kind:"keys",keys:"/context"}},"crtr.tmux.menu.providers":{description:"settings",action:{kind:"popup",run:"sys settings",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.provider-options":{description:"provider options",action:{kind:"popup",run:"sys settings --page provider-options",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.plugins":{description:"plugins",action:{kind:"popup",run:"pkg browse",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.analytics":{description:"analytics",action:{kind:"popup",run:"canvas analytics --pane {pane}",size:{w:"90%",h:"85%"}}},"crtr.tmux.menu.context-admin":{description:"context surface",action:{kind:"popup",run:"sys context admin",size:{w:"98%",h:"96%"}}},"crtr.tmux.menu.graph":{description:"canvas graph",action:{kind:"keys",keys:"/graph"}},"crtr.tmux.menu.focus-manager":{description:"go to manager",action:{kind:"command",run:"surface node focus {manager}"}},"crtr.tmux.menu.copy-id":{description:"copy node id",action:{kind:"direct",run:"surface node id --pane {pane}"}},"crtr.tmux.menu.reload-viewer":{description:"reload viewer",action:{kind:"literal-input",input:q("crtr.attach.reload-viewer")}},"crtr.tmux.menu.recap":{description:"generate recap",action:{kind:"keys",keys:"/recap"}},"crtr.tmux.menu.pin":{description:"pin conversation",action:{kind:"direct",run:"surface node pin --pane {pane}"}},"crtr.tmux.menu.issue.idea":{description:"idea",action:{kind:"popup",run:"canvas issue new --type idea"}},"crtr.tmux.menu.issue.bug":{description:"bug",action:{kind:"popup",run:"canvas issue new --type bug"}}};function b(e){return e.replace(/#/g,"##")}u(b,"escapeTmuxFormats");function ce(e){return e.map(k).join(" ")}u(ce,"tmuxCommand");const ae={w:"60%",h:"50%"};function j(e,n=!1,t=ae){const r=`crtr canvas chord --pane '#{pane_id}' --run ${k(b(e))}${n?" --interactive":""}`;return n?{argv:["display-popup","-E","-w",t.w,"-h",t.h,"-d","#{pane_current_path}",r],menu:`display-popup -E -w ${t.w} -h ${t.h} -d "#{pane_current_path}" ${k(r)}`}:{argv:["run-shell",`${r} >/dev/null 2>&1`],menu:`run-shell ${k(`${r} >/dev/null 2>&1`)}`}}u(j,"chordCommand");function de(e){const t=`crtr ${b(e).replace("{pane}","#{pane_id}")} >/dev/null 2>&1`;return{argv:["run-shell","-b",t],menu:`run-shell -b ${k(t)}`}}u(de,"directCommand");function z(e){switch(e.kind){case"disabled":return null;case"separator":return null;case"dismiss":return{argv:["refresh-client"],menu:"refresh-client"};case"keys":{const n=b(e.keys);return{argv:["send-keys",n,"Enter"],menu:`send-keys -t '#{pane_id}' ${k(n)} Enter`}}case"raw-keys":{const n=b(e.keys);return{argv:["send-keys",n],menu:`send-keys -t '#{pane_id}' ${k(n)}`}}case"literal-input":{const n=b(e.input);return{argv:["send-keys","-l",n],menu:`send-keys -l -t '#{pane_id}' ${k(n)}`}}case"command":return j(e.run);case"direct":return de(e.run);case"popup":return j(e.run,!0,e.size);case"submenu":{const n=N(e.title,e.items);return{argv:n,menu:ce(n)}}}}u(z,"menuActionCommand");function me(e){return z(e)?.menu??""}u(me,"renderMenuAction");function pe(e){return e.replace(/#\[[^\]]*\]/g,"").length}u(pe,"menuItemWidth");function N(e,n){const t=b(e),r=n.reduce((o,c)=>Math.max(o,pe(c.description)),0),s=["display-menu","-T",`#[align=centre]${t}`,...se()];s.push("-x",`#{e|-:#{pane_right},${Math.max(t.length,r)+7}}`,"-y","#{e|+:#{pane_top},3}","--");for(const o of n){if(o.action.kind==="separator"){s.push("");continue}const c=o.action.kind==="disabled"?o.description:b(o.description);s.push(c,o.selector,me(o.action))}return s.push("","-esc / q to close","",""),s}u(N,"buildMenuArgs");const le={enter:"Enter",escape:"Escape",tab:"Tab",backspace:"BSpace",delete:"DC",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PPage",pagedown:"NPage",home:"Home",end:"End"};function F(e){if(e==="+")return{key:"+",modifiers:[]};if(e.endsWith("++"))return{key:"+",modifiers:e.slice(0,-2).split("+")};const n=e.split("+");return{key:n.pop(),modifiers:n}}u(F,"normalizedStrokeParts");function fe(e){return v(e)[0]}u(fe,"tmuxKey");function v(e){let{key:n,modifiers:t}=F(e);const r=new Set(t),s=u((o,c)=>[r.has("ctrl")?"C-":"",r.has("alt")?"M-":"",c?"S-":"",le[o]??o].join(""),"name");if(r.has("shift")&&n.length===1&&/[a-z]/.test(n)){const o=n.toUpperCase();return!r.has("ctrl")&&!r.has("alt")?[s(o,!1)]:[s(o,!0),s(o,!1),s(n,!0)]}return[s(n,r.has("shift"))]}u(v,"tmuxKeyNames");function ge(e){const{key:n,modifiers:t}=F(e);return t.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}u(ge,"menuSelector");function T(e,n,t){const r=[];for(const s of e){const o=n.get(s);if(o!==void 0)for(const c of t.gestures(s))r.push({description:o.description,selector:ge(c),action:o.action})}return r}u(T,"boundMenuItems");function K(e){const n=new Map;for(const[c,l]of Object.entries(ue))l!==void 0&&n.set(c,l);for(const{menuId:c,actionId:l}of U){const x=_.find(w=>w.id===l);if(x===void 0)throw new Error(`missing attach binding definition ${l}`);n.set(c,{description:x.name.toLowerCase(),action:{kind:"literal-input",input:q(l)}})}const t=T(U.map(({menuId:c})=>c),n,e);t.length>0&&n.set("crtr.tmux.menu.attach",{description:"attach viewer \u203A",action:{kind:"submenu",title:" attach viewer ",items:t}});const r=T(["crtr.tmux.menu.metadata","crtr.tmux.menu.context"],n,e);n.set("crtr.tmux.menu.show",{description:"inspect \u203A",action:{kind:"submenu",title:" inspect node ",items:r}});const s=T(["crtr.tmux.menu.more-detail","crtr.tmux.menu.less-detail"],n,e);n.set("crtr.tmux.menu.view-settings",{description:"display \u203A",action:{kind:"submenu",title:" display ",items:s}});const o=T(["crtr.tmux.menu.issue.idea","crtr.tmux.menu.issue.bug"],n,e);return n.set("crtr.tmux.menu.issues",{description:"create \u203A",action:{kind:"submenu",title:" create ",items:o}}),n}u(K,"resolvedMenuActions");function R(e,n){const t=u(c=>T(c,n,e),"boundItems"),r=[],s=u((c,l)=>{l.length!==0&&(r.length>0&&r.push({description:"",selector:"",action:{kind:"separator"}}),r.push({description:`-#[bold]${c}`,selector:"",action:{kind:"disabled"}},...l))},"addGroup");s("Explore",t(["crtr.tmux.menu.dashboard","crtr.tmux.menu.resume","crtr.tmux.menu.graph","crtr.tmux.menu.focus-manager","crtr.tmux.menu.show","crtr.tmux.menu.view-settings"])),s("Current node",t(["crtr.tmux.menu.attach","crtr.tmux.menu.background-bash","crtr.tmux.menu.pin","crtr.tmux.menu.copy-id","crtr.tmux.menu.reload-viewer","crtr.tmux.menu.recap"])),s("Lifecycle",t(["crtr.tmux.menu.fork","crtr.tmux.menu.promote","crtr.tmux.menu.demote-mode","crtr.tmux.menu.demote","crtr.tmux.menu.make-resident","crtr.tmux.menu.detach","crtr.tmux.menu.close-subtree"])),s("System",t(["crtr.tmux.menu.providers","crtr.tmux.menu.provider-options","crtr.tmux.menu.plugins","crtr.tmux.menu.analytics","crtr.tmux.menu.context-admin","crtr.tmux.menu.issues"]));const o=e.gestures("crtr.tmux.menu.open");if(o.length>0&&r.length>0){r.push({description:"",selector:"",action:{kind:"separator"}});for(const c of o)r.push({description:`${te(c)} to close`,selector:fe(c),action:{kind:"dismiss"}})}return r}u(R,"menuItems");function Pe(e){const n=e??G().bindings;return N(" crtr ",R(n,K(n)))}u(Pe,"crouterMenuTmuxArgs");function S(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(t>=e.length)return null;let r=null,s="";for(;t<e.length;){const o=e[t];if(r===null&&/\s/.test(o))break;if(r===null&&(o==="'"||o==='"')){r=o,t+=1;continue}if(r===o){r=null,t+=1;continue}if(o==="\\"&&r!=="'"&&t+1<e.length){s+=e[t+1],t+=2;continue}s+=o,t+=1}return{value:s,end:t}}u(S,"readTmuxToken");function B(e){const n=S(e,0);if(n?.value!=="bind-key")return null;let t=n.end,r=!1;for(;;){const s=S(e,t);if(s===null)return null;if(t=s.end,s.value==="-r"){r=!0;continue}if(s.value!=="-T")continue;const o=S(e,t);if(o===null)return null;const c=S(e,o.end);return c===null?null:{table:o.value,key:c.value,command:e.slice(c.end).trimStart(),repeat:r}}}u(B,"parseTmuxBinding");function $(e,n){const t=f(["list-keys","-T",e]);return t.ok?t.stdout.split(`
|
|
2
2
|
`).find(r=>{const s=B(r);return s?.table===e&&s.key===n})??null:null}u($,"bindingAt");function Le(e){const n=f(["list-keys","-T",p]);if(!n.ok)return[];const t=new Set(n.stdout.split(`
|
|
3
|
-
`).flatMap(r=>{const s=B(r);return s?.table===p?[s.key]:[]}));return e.filter(r=>!r.includes(" > ")&&v(r).some(s=>t.has(s)))}u(Le,"occupiedTmuxRootGestures");function W(e){return typeof e=="object"&&e!==null&&typeof e.table=="string"&&typeof e.key=="string"}u(W,"isInstalledPair");function
|
|
4
|
-
`,"utf8"),f(["source-file",t])}finally{V(n,{recursive:!0,force:!0})}}u(be,"sourceBindingLine");function H(e){return e.original===null?f(["unbind-key","-T",p,C(e.key)]):be(e.original)}u(H,"restoreWrappedBinding");function we(){return["run-shell","-b",'crtr surface inbox --quiet --tmux-socket "#{socket_path}" --tmux-client "#{client_name}" --target-pane "#{pane_id}"']}u(we,"inboxToggleTmuxCommand");function ve(e){switch(e){case"crtr.tmux.node.next":return["run-shell","crtr surface node cycle --dir next --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.node.previous":return["run-shell","crtr surface node cycle --dir prev --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.inbox.toggle":return we();default:throw new Error(`no tmux command for ${e}`)}}u(ve,"actionCommand");function $e(){const e=process.env.TMUX?.split(",")[0]?.trim();if(e!==void 0&&e!=="")return`${e}.crtr-keybindings.lock`;const n=f(["display-message","-p","#{socket_path}"]);if(n.ok&&n.stdout!=="")return`${n.stdout}.crtr-keybindings.lock`;const t=typeof process.getuid=="function"?process.getuid():"user";return M(O(),`crtr-tmux-keybindings-${t}.lock`)}u($e,"tmuxBindingLockPath");function De(e,n=[]){return oe($e(),()=>Ie(e,n))}u(De,"installTmuxBindings");function Ie(e,n=[]){const t=e===void 0?G():void 0,r=e??t.bindings,s=e===void 0?t.tmuxPassthrough:ie(n),o=[],c=[],l=
|
|
3
|
+
`).flatMap(r=>{const s=B(r);return s?.table===p?[s.key]:[]}));return e.filter(r=>!r.includes(" > ")&&v(r).some(s=>t.has(s)))}u(Le,"occupiedTmuxRootGestures");function W(e){return typeof e=="object"&&e!==null&&typeof e.table=="string"&&typeof e.key=="string"}u(W,"isInstalledPair");function he(e){if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.bindingId=="string"&&ne.has(n.bindingId)&&typeof n.gesture=="string"&&typeof n.key=="string"&&(typeof n.original=="string"||n.original===null)&&typeof n.wrapper=="string"&&(n.state==="owned"||n.state==="relinquished")}u(he,"isWrappedRootBinding");function ke(){const e=f(["show-options","-s","-q",A]);if(!e.ok)return null;if(e.stdout==="")return{pairs:[],wrappers:[]};const n=f(["show-options","-s","-qv",A]);if(!n.ok)return null;try{const t=JSON.parse(n.stdout);if(Array.isArray(t))return t.every(W)?{pairs:t,wrappers:[]}:null;if(typeof t!="object"||t===null)return null;const r=t;return!Array.isArray(r.pairs)||!r.pairs.every(W)||!Array.isArray(r.wrappers)||!r.wrappers.every(he)?null:{pairs:r.pairs,wrappers:r.wrappers}}catch{return null}}u(ke,"readManifest");function X(e){return f(["set-option","-s",A,JSON.stringify(e)])}u(X,"writeManifest");function C(e){return e.replace(/\\/g,"\\\\").replace(/;/g,"\\;")}u(C,"tmuxKeyArgument");function xe(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/;/g,"\\;")}"`}u(xe,"tmuxCommandToken");function ye(e){let n=null,t="";for(let r=0;r<e.length;r+=1){const s=e[r];if(n===null&&(s==="'"||s==='"')){n=s,t+=s;continue}if(n===s){n=null,t+=s;continue}if(s==="\\"&&r+1<e.length){const o=e[r+1];n===null&&o===";"?t+=";":t+=s+o,r+=1;continue}t+=s}return t}u(ye,"bindingCommandForBranch");function be(e){const n=Z(M(O(),"crtr-tmux-binding-")),t=M(n,"binding.conf");try{return ee(t,`${e}
|
|
4
|
+
`,"utf8"),f(["source-file",t])}finally{V(n,{recursive:!0,force:!0})}}u(be,"sourceBindingLine");function H(e){return e.original===null?f(["unbind-key","-T",p,C(e.key)]):be(e.original)}u(H,"restoreWrappedBinding");function we(){return["run-shell","-b",'crtr surface inbox --quiet --tmux-socket "#{socket_path}" --tmux-client "#{client_name}" --target-pane "#{pane_id}"']}u(we,"inboxToggleTmuxCommand");function ve(e){switch(e){case"crtr.tmux.node.next":return["run-shell","crtr surface node cycle --dir next --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.node.previous":return["run-shell","crtr surface node cycle --dir prev --pane '#{pane_id}' >/dev/null 2>&1"];case"crtr.tmux.inbox.toggle":return we();default:throw new Error(`no tmux command for ${e}`)}}u(ve,"actionCommand");function $e(){const e=process.env.TMUX?.split(",")[0]?.trim();if(e!==void 0&&e!=="")return`${e}.crtr-keybindings.lock`;const n=f(["display-message","-p","#{socket_path}"]);if(n.ok&&n.stdout!=="")return`${n.stdout}.crtr-keybindings.lock`;const t=typeof process.getuid=="function"?process.getuid():"user";return M(O(),`crtr-tmux-keybindings-${t}.lock`)}u($e,"tmuxBindingLockPath");function De(e,n=[]){return oe($e(),()=>Ie(e,n))}u(De,"installTmuxBindings");function Ie(e,n=[]){const t=e===void 0?G():void 0,r=e??t.bindings,s=e===void 0?t.tmuxPassthrough:ie(n),o=[],c=[],l=ke();if(l===null)return o.push({code:"tmux-error",message:`tmux is unavailable or ${A} is malformed`}),{ok:!1,installed:c,diagnostics:o};const x=new Map;for(const i of s){const a=_.find(d=>d.id===i);if(!(a===void 0||!re(a))){for(const d of r.gestures(i))if(!d.includes(" > "))for(const m of v(d))x.has(m)||x.set(m,{bindingId:i,gesture:d})}}const w=new Set,I=[];for(const i of l.wrappers){const a=x.get(i.key),d=$(p,i.key);if(d!==null&&d===i.original)continue;if(i.state==="relinquished"||d!==i.wrapper){w.add(i.key),a!==void 0&&I.push({...i,...a,state:"relinquished"});continue}const m=H(i);m.ok||(w.add(i.key),I.push(i),o.push({code:"tmux-error",bindingId:i.bindingId,gesture:i.gesture,message:`could not restore tmux binding ${p}:${i.key}: ${m.stderr}`}))}for(const i of l.pairs){if(i.table===p&&w.has(i.key))continue;const a=f(["unbind-key","-T",i.table,C(i.key)]);!a.ok&&$(i.table,i.key)!==null&&o.push({code:"tmux-error",message:`could not remove crouter binding ${i.table}:${i.key}: ${a.stderr}`})}if(o.some(i=>i.code==="tmux-error")){const i=X({pairs:l.pairs,wrappers:I});return i.ok||o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${i.stderr}`}),{ok:!1,installed:c,diagnostics:o}}const E=u((i,a,d,m,h)=>{if($(i,a)!==null)return o.push({code:"occupied",bindingId:m,gesture:h,message:`${i}:${a} is already bound by tmux; ${m} was not installed`}),!1;const g=f(["bind-key","-T",i,C(a),...d]);return g.ok?(c.push({table:i,key:a}),!0):(o.push({code:"tmux-error",bindingId:m,gesture:h,message:`could not install ${m}: ${g.stderr}`}),!1)},"install"),P=K(r),J=N(" crtr ",R(r,P));for(const i of r.gestures("crtr.tmux.menu.open"))for(const a of v(i))E(p,a,J,"crtr.tmux.menu.open",i);for(const i of _){if(i.pair?.field!=="menu")continue;const a=_.find(y=>y.id===i.pair?.pairedId);if(a?.pair?.field!=="global")continue;const d=i.id,m=a.id,h=P.get(d),g=h===void 0?null:z(h.action);if(g===null)throw new Error(`no direct tmux action for paired menu binding ${d}`);for(const y of r.gestures(m))for(const Q of v(y))E(p,Q,g.argv,m,y)}for(const i of["crtr.tmux.node.next","crtr.tmux.node.previous","crtr.tmux.inbox.toggle"])for(const a of r.gestures(i))for(const d of v(a))E(p,d,ve(i),i,a);const L=[];for(const[i,a]of x){if(w.has(i))continue;const d=$(p,i);if(d===null)continue;const m=B(d);if(m===null||m.command===""){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not parse occupied tmux binding ${p}:${i}`});continue}const h=f(["bind-key",...m.repeat?["-r"]:[],"-T",p,C(i),"if-shell","-F","#{!=:#{@crtr_attach},}",`send-keys ${xe(i)}`,ye(m.command)]);if(!h.ok){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not wrap ${p}:${i}: ${h.stderr}`});continue}const g=$(p,i);if(g===null||!g.includes("@crtr_attach")){o.push({code:"tmux-error",bindingId:a.bindingId,gesture:a.gesture,message:`could not fingerprint wrapped tmux binding ${p}:${i}`});continue}const y={...a,key:i,original:d,wrapper:g,state:"owned"};I.push(y),L.push(y)}const D=X({pairs:c,wrappers:I});if(!D.ok){o.push({code:"tmux-error",message:`could not save crouter tmux ownership manifest: ${D.stderr}`});for(const i of L)$(p,i.key)===i.wrapper&&H(i)}return{ok:o.every(i=>i.code!=="tmux-error"),installed:c,diagnostics:o}}u(Ie,"reconcileTmuxBindings");export{Pe as crouterMenuTmuxArgs,we as inboxToggleTmuxCommand,De as installTmuxBindings,Le as occupiedTmuxRootGestures};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var W=Object.defineProperty;var a=(e,n)=>W(e,"name",{value:n,configurable:!0});import{createHash as $,createHmac as N,createPrivateKey as D,hkdfSync as B,randomBytes as v,randomUUID as M,sign as z,timingSafeEqual as F}from"node:crypto";import{readFileSync as G}from"node:fs";import{JwksCache as K,verifyIdToken as Y}from"@north-light/identity";import{withCanvasWrite as Z}from"../../core/canvas/db.js";import{isCloudRole as Q,runAsPerson as L}from"../../core/canvas/person.js";import{joinByEmail as X}from"../../core/graph/group-invites.js";import{directoryIssuer as q}from"../../core/directory/issuer.js";import{emitEvent as k}from"../../core/events/emit.js";import{ApiError as ee}from"../../api/errors.js";import{boundDaemonControl as ne}from"../control.js";import{loadPersonSettings as te}from"../../core/scoped-state/person-rows.js";import{personHasSnapshot as oe}from"../../core/scoped-state/person-store.js";import{escapeHtml as g}from"./vendor-signin.js";import{serveReviewApi as ie}from"./review-page.js";import{cookieValue as I,documentNotFound as re,documentShell as ae,error as _,messagePage as m,resolveDocument as se,serveDocumentApi as ce,setPageHeaders as de}from"./document-page.js";const S="/auth/callback",ue="/join-group",b=12*36e5,j=10*6e4,le=1e4;let w,O,C;function fe(){if(w!==void 0)return w;const e=process.env.CRTR_CANVAS_URL;if(!e)return w=null;const n=new URL(e),t=process.env.CRTR_CANVAS_CLIENT_ID,o=process.env.CRTR_CANVAS_JWK_FILE,r=q();if(!t||!o||r===null)throw new Error("CRTR_CANVAS_URL needs CRTR_CANVAS_CLIENT_ID, CRTR_CANVAS_JWK_FILE and CRTR_DIRECTORY_URL");const i=JSON.parse(G(o,"utf8"));if(i.kty!=="EC"||i.crv!=="P-256"||!i.d)throw new Error("CRTR_CANVAS_JWK_FILE must hold a private P-256 JWK");const s=Buffer.from(B("sha256",i.d,"crtr-canvas","canvas-session-cookies",32));return w={origin:n.origin,host:n.host,secure:n.protocol==="https:",clientId:t,jwk:i,issuer:r,key:s}}a(fe,"canvasConfig");function he(){const e=process.env.CRTR_CANVAS_URL;if(!(!Q()||!e))try{return new URL(e).origin}catch{return}}a(he,"canvasOrigin");function je(e){const n=he();return n!==void 0&&e.headers.host===new URL(n).host}a(je,"isCanvasRequest");const h=a(e=>e.toString("base64url"),"b64");function P(e,n,t,o){const r=h(Buffer.from(JSON.stringify({...t,purpose:n,exp:Date.now()+o})));return`${r}.${h(N("sha256",e.key).update(r).digest())}`}a(P,"seal");function U(e,n,t){if(!t)return null;const[o,r,i]=t.split(".");if(!o||!r||i!==void 0)return null;const s=a(d=>$("sha256").update(d).digest(),"digest");if(!F(s(r),s(h(N("sha256",e.key).update(o).digest()))))return null;try{const d=JSON.parse(Buffer.from(o,"base64url").toString("utf8"));return d.purpose===n&&typeof d.exp=="number"&&d.exp>Date.now()?d:null}catch{return null}}a(U,"open");const R=a((e,n)=>e.secure?`__Host-${n}`:n,"cookieName");function T(e,n,t,o){return`${R(e,n)}=${t}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(o/1e3)}${e.secure?"; Secure":""}`}a(T,"cookie");async function x(e,n){const t=await fetch(e,{...n,signal:AbortSignal.timeout(le)}),o=await t.json().catch(()=>({}));if(!t.ok)throw new Error(`directory ${new URL(e).pathname} answered ${t.status}: ${String(o.error_description??o.error??"")}`);return o}a(x,"directoryJson");function H(e){return C??=x(`${e.issuer}/.well-known/openid-configuration`).then(n=>{if(typeof n.authorization_endpoint!="string"||typeof n.token_endpoint!="string")throw new Error("directory discovery has no authorization or token endpoint");return n},n=>{throw C=void 0,n}),C}a(H,"discover");function pe(e,n){const t=Math.floor(Date.now()/1e3),o=h(Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",...e.jwk.kid?{kid:e.jwk.kid}:{}}))),r=h(Buffer.from(JSON.stringify({iss:e.clientId,sub:e.clientId,aud:n,iat:t,exp:t+60,jti:M()}))),i=z("sha256",Buffer.from(`${o}.${r}`),{key:D({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${o}.${r}.${h(i)}`}a(pe,"clientAssertion");async function J(e,n,t){return await x(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({...t,client_id:e.clientId,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:pe(e,n)})})}a(J,"directoryPost");async function V(e,n,t,o=!1){const r=await H(e),i={state:h(v(16)),verifier:h(v(32)),nonce:h(v(32)),next:t,...o?{join:!0}:{}},s=new URL(r.authorization_endpoint);s.search=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:`${e.origin}${S}`,scope:"openid email",state:i.state,nonce:i.nonce,code_challenge:h($("sha256").update(i.verifier).digest()),code_challenge_method:"S256"}).toString(),n.writeHead(303,{Location:s.href,"Set-Cookie":T(e,`crtr_canvas_login_${i.state}`,P(e,"login",i,j),j),"Cache-Control":"no-store"}),n.end()}a(V,"startSignIn");async function me(e,n,t,o){const r=o.searchParams.get("state"),i=r!==null&&/^[A-Za-z0-9_-]{22}$/.test(r)?`crtr_canvas_login_${r}`:void 0,s=i===void 0?null:U(e,"login",I(n.headers.cookie,R(e,i))),d=o.searchParams.get("code");if(o.searchParams.get("error")!==null)return m(t,400,"Sign-in did not finish",`Northlight answered <code>${g(o.searchParams.get("error").slice(0,100))}</code>. Open the document link again to retry.`);if(s===null||d===null||r!==s.state)return m(t,400,"Sign-in did not finish","This sign-in started in another browser or expired. Open the document link again.");const l=await H(e),f=await J(e,l.token_endpoint,{grant_type:"authorization_code",code:d,redirect_uri:`${e.origin}${S}`,code_verifier:s.verifier});if(typeof f.refresh_token=="string"&&l.revocation_endpoint!==void 0&&await J(e,l.revocation_endpoint,{token:f.refresh_token,token_type_hint:"refresh_token"}).catch(u=>k({level:"warn",event:"api.canvas.revoke_failed",error:u instanceof Error?u:new Error(String(u))})),typeof f.id_token!="string")throw new Error("the directory token response has no id_token");O??=new K(e.issuer);const c=await Y({token:f.id_token,jwks:O,issuer:e.issuer,audience:e.clientId});if(c.nonce!==s.nonce)return m(t,400,"Sign-in did not finish","The sign-in answer does not match this browser. Open the document link again.");const p=c.email_verified===!0&&typeof c.email=="string"?c.email:null;let y=[],A=!1;if(p!==null)try{y=await L(c.sub,()=>Z(u=>X(u,c.sub,p)))}catch(u){A=!0,k({level:"error",event:"api.canvas.join_failed",error:u instanceof Error?u:new Error(String(u))})}const E=[T(e,"crtr_canvas_session",P(e,"session",{sub:c.sub},b),b),T(e,i,"",0)];if(s.join===!0)return t.setHeader("Set-Cookie",E),A?m(t,500,"Group invite",`The invite for <code>${g(p)}</code> could not be checked. Try the link again in a moment.`):m(t,200,"Group invite",y.length===0?`No invite matched <code>${g(p??"an unverified email")}</code>, the email of the Northlight account you signed in with. Ask the group admin to invite that address, or sign in to Northlight as the invited account and open the link again.`:`You joined ${y.map(u=>`<code>${g(u)}</code>`).join(", ")}.`);t.writeHead(303,{Location:s.next,"Set-Cookie":E,"Cache-Control":"no-store"}),t.end()}a(me,"finishSignIn");async function Oe(e,n){try{await ge(e,n)}catch(t){k({level:"error",event:"api.canvas.failed",error:t instanceof Error?t:new Error(String(t)),fields:{method:e.method,path:e.url?.split("?")[0]}}),n.headersSent?n.destroy():m(n,500,"Something went wrong","The document could not be opened. Try again in a moment.")}}a(Oe,"serveCanvas");async function ge(e,n){const t=fe();if(t===null)throw new Error("CRTR_CANVAS_URL is unset");if(de(n),ne()?.startupBlock()!=null)return m(n,503,"Starting up","The canvas is starting. Try again in a moment.");const o=new URL(e.url??"/",t.origin);if(e.method==="POST"){if(e.headers.origin!==t.origin)return _(n,403,"forbidden","invalid Origin");if(e.headers["content-type"]!=="application/json")return _(n,415,"unsupported_media_type","Content-Type must be application/json")}if(e.method==="GET"&&o.pathname===S)return await me(t,e,n,o);if(e.method==="GET"&&o.pathname===ue)return await V(t,n,"/",!0);const r=e.method==="GET"&&(o.pathname.startsWith("/r/")||o.pathname.startsWith("/document/")||o.pathname.startsWith("/review/")),i=o.pathname.startsWith("/assets/")?null:U(t,"session",I(e.headers.cookie,R(t,"crtr_canvas_session")));if(i===null&&!o.pathname.startsWith("/assets/"))return r?await V(t,n,`${o.pathname}${o.search}`):_(n,401,"unauthorized","your sign-in expired: reload the page to sign in again");const s=i?.sub,d=a(l=>s===void 0?l():L(s,async()=>(oe()||await te(s),await l())),"asPerson");await d(async()=>{if(!await ie(e,n,o)){if(r){const l=o.pathname.startsWith("/r/")?"/r/":"/document/";let f;try{f=decodeURIComponent(o.pathname.slice(l.length))}catch{return _(n,400,"invalid_request","the address is not valid percent-encoding")}let c;try{c=f===""?null:await se(f)}catch(p){if(p instanceof ee&&p.code==="ambiguous_name")return m(n,409,"More than one document has this name",g(p.message));throw p}if(c===null||l==="/document/"&&c.id!==f)return re(n,f);if(l==="/r/"){n.writeHead(303,{Location:`/document/${encodeURIComponent(c.id)}`,"Cache-Control":"no-store"}),n.end();return}return ae(n,c.id,c)}if(!await ce(e,n,o,d))return e.method==="GET"&&o.pathname==="/"?m(n,404,"Northlight canvas","Open a document from its link in the viewer."):_(n,404,"not_found","route not found")}})}a(ge,"canvasRequest");export{S as CANVAS_CALLBACK_PATH,ue as CANVAS_JOIN_PATH,he as canvasOrigin,je as isCanvasRequest,Oe as serveCanvas};
|
|
@@ -6,13 +6,24 @@ export type AsPerson = <T>(fn: () => Promise<T>) => Promise<T>;
|
|
|
6
6
|
export declare function setPageHeaders(res: ServerResponse): void;
|
|
7
7
|
export declare function error(res: ServerResponse, status: number, code: string, message: string): void;
|
|
8
8
|
export declare function cookieValue(header: string | undefined, name: string): string | undefined;
|
|
9
|
+
export declare function json(res: ServerResponse, status: number, value: unknown): void;
|
|
9
10
|
/** A small HTML page with a heading and one paragraph of already-escaped HTML. */
|
|
10
11
|
export declare function messagePage(res: ServerResponse, status: number, title: string, html: string): void;
|
|
11
12
|
export declare function documentNotFound(res: ServerResponse, ref: string): void;
|
|
12
13
|
/** The editor's HTML shell; the editor reads `ref` from `#app[data-ref]` and calls the `/api/*` routes with it. */
|
|
13
|
-
export declare function documentShell(res: ServerResponse, ref: string, doc: ObjectRow): void;
|
|
14
|
+
export declare function documentShell(res: ServerResponse, ref: string, doc: ObjectRow, review?: string): void;
|
|
15
|
+
export declare function documentSnapshot(doc: ObjectRow): Promise<{
|
|
16
|
+
readonly_reason?: string | undefined;
|
|
17
|
+
id: string;
|
|
18
|
+
name: string;
|
|
19
|
+
revision: number;
|
|
20
|
+
heads_key: string;
|
|
21
|
+
body: string;
|
|
22
|
+
editable: boolean;
|
|
23
|
+
} | null>;
|
|
14
24
|
/** The live document `ref` names that the request's person can read, or null. */
|
|
15
25
|
export declare function resolveDocument(ref: string): Promise<ObjectRow | null>;
|
|
26
|
+
export declare function requestBody(req: IncomingMessage): Promise<unknown>;
|
|
16
27
|
/** Serve `/api/doc`, `/api/save`, `/api/events` and `/assets/<version>/…`. Answers false for any other route. The caller has already
|
|
17
28
|
* checked its gate, and for a POST the Origin and Content-Type. */
|
|
18
29
|
export declare function serveDocumentApi(req: IncomingMessage, res: ServerResponse, url: URL, asPerson: AsPerson): Promise<boolean>;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var i=(n,e)=>O(n,"name",{value:e,configurable:!0});import{readFileSync as A}from"node:fs";import{join as x,extname as $}from"node:path";import{fileURLToPath as P}from"node:url";import{withCanvasWrite as w}from"../../core/canvas/db.js";import{ApiError as R}from"../../api/errors.js";import{get as v}from"../../core/graph/bodies.js";import{canChange as E,isShipped as B}from"../../core/graph/access.js";import{documentRecord as S,editDocument as F,heads as T,withCurrentNames as _}from"../../core/graph/documents.js";import{getById as g}from"../../core/graph/objects.js";import{subscribeDocumentEvents as I}from"../../core/graph/events.js";import{emitEvent as J}from"../../core/events/emit.js";import{checkoutsForCwd as L}from"../../core/graph/repo-sync/repos.js";import{canonicalName as U}from"./handlers/docs.js";import{escapeHtml as u}from"./vendor-signin.js";import{readerFor as b,resolveRef as W,warmDocumentWatchers as G}from"./reader.js";import{mergeDocumentLines as z}from"./document-merge.js";import{crtrVersion as M}from"../../shared/crtr-version.js";const V="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",k={class:"person"},f=encodeURIComponent(M()),j=P(new URL("../../../dist/",import.meta.url));function pe(n){n.setHeader("Content-Security-Policy",V),n.setHeader("X-Content-Type-Options","nosniff")}i(pe,"setPageHeaders");function l(n,e,t,a){n.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),n.end(JSON.stringify({error:{code:t,message:a}}))}i(l,"error");function we(n,e){for(const t of(n??"").split(";")){const a=t.indexOf("=");if(a!==-1&&t.slice(0,a).trim()===e)return t.slice(a+1).trim()}}i(we,"cookieValue");function H(n,e,t){n.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),n.end(JSON.stringify(t))}i(H,"json");function X(n,e,t,a){n.writeHead(e,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),n.end(`<!doctype html><html><head><meta charset="utf-8"><title>${u(t)}</title><link rel="icon" href="data:,"></head><body style="font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>${u(t)}</h1><p>${a}</p></body></html>`)}i(X,"messagePage");function ve(n,e){X(n,404,"Document not found",`No document you can read is named <code>${u(e)}</code>.`)}i(ve,"documentNotFound");function _e(n,e,t,a){n.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"});const o=a===void 0?"":` data-review="${u(a)}"`,r=a===void 0?"":`<link rel="stylesheet" href="/assets/${f}/review.css">`,s=a===void 0?"":`<script type="module" src="/assets/${f}/review.js"><\/script>`;n.end(`<!doctype html><html><head><meta charset="utf-8"><title>${u(t.name)}</title><link rel="icon" href="data:,"><link rel="stylesheet" href="/assets/${f}/editor.css">${r}</head><body><div id="app" data-ref="${u(e)}"${o}></div><script type="module" src="/assets/${f}/editor.js"><\/script>${s}</body></html>`)}i(_e,"documentShell");async function N(n){return await w(async e=>{const t=await g(e,n.id);if(!t||t.deleted_at||t.type!=="document")return null;const a=await b(e,{principal:k}),o=await S(e,t),r=await T(e,t),s=await U(e,t),c=r.length===1&&await E(e,a,t);return{id:t.id,name:s,revision:o.revision,heads_key:o.heads_key,body:r.length===1?await _(e,t,await v(e,r[0].body_hash)):"",editable:c,...c?{}:{readonly_reason:r.length!==1?`has ${r.length} heads and needs a merge`:await B(e,t)?"shipped by a plugin":"you cannot change this document"}}})}i(N,"documentSnapshot");async function C(n){return await w(async e=>{const t=await b(e,{principal:k});try{const a=await W(e,t,n);return"deleted"in a||"remote"in a||a.type!=="document"?null:a}catch(a){if(a instanceof R&&a.code==="not_found")return null;throw a}})}i(C,"resolveDocument");async function Z(n){return await w(async e=>{const t=await g(e,n);return!t||t.type!=="document"||t.deleted_at!==null})}i(Z,"isDeleted");async function q(n){const e=[];let t=0;for await(const a of n){if(t+=a.length,t>2e6)throw new Error("request body exceeds 2 MB");e.push(a)}return JSON.parse(Buffer.concat(e).toString("utf8"))}i(q,"requestBody");async function K(n){return await G(n.id),await w(async t=>{const a=await b(t,{principal:k}),o=await g(t,n.id);if(!o||o.type!=="document"||o.deleted_at)return{status:404,value:{error:{code:"not_found",message:"document not found"}}};const r=await S(t,o),s=await T(t,o);if(s.length!==1||!await E(t,a,o))return{status:403,value:{error:{code:"forbidden",message:"document is read-only"}}};const c=await _(t,o,await v(t,s[0].body_hash)),m=await t.prepareUncached("SELECT body_hash FROM revisions WHERE document = ? AND rev_id = ?").get(o.id,n.base_heads_key);if(!m||await _(t,o,await v(t,m.body_hash))!==n.base_body)return{status:409,value:{saved:!1,conflict:{revision:r.revision,heads_key:r.heads_key,current_body:c,your_body:n.body}}};const p=n.base_heads_key!==r.heads_key,y=p?z(n.base_body,n.body,c):n.body;if(y===null)return{status:409,value:{saved:!1,conflict:{revision:r.revision,heads_key:r.heads_key,current_body:c,your_body:n.body}}};const d=await F(t,a,o,{body:y},n.rationale?.trim()||"edited by the person in the browser",r.heads_key,{},async(h,D)=>await L(t,h,D));return"stale"in d?{status:409,value:{saved:!1,conflict:{revision:d.stale.revision,heads_key:d.stale.heads_key,current_body:c,your_body:n.body}}}:{status:200,value:{saved:!0,revision:d.revision,heads_key:d.heads_key,body:y,merged:p}}})}i(K,"save");async function ge(n,e,t,a){if(n.method==="GET"&&t.pathname==="/api/doc"){const o=t.searchParams.get("ref"),r=o?await C(o):null,s=r&&await N(r);return s?H(e,200,{...s,ref:o}):l(e,404,"not_found","document not found"),!0}if(n.method==="POST"&&t.pathname==="/api/save"){const o=await q(n);if(!o||typeof o!="object"||Array.isArray(o))return l(e,400,"invalid_request","invalid save body"),!0;const r=o;if(typeof r.id!="string"||typeof r.base_heads_key!="string"||typeof r.base_body!="string"||typeof r.body!="string"||r.rationale!==void 0&&typeof r.rationale!="string")return l(e,400,"invalid_request","invalid save body"),!0;const s=await K(r);return H(e,s.status,s.value),!0}if(n.method==="GET"&&t.pathname==="/api/events"){const o=t.searchParams.get("id");if(!o||!await C(o))return l(e,404,"not_found","document not found"),!0;e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),e.write(`: connected
|
|
2
2
|
|
|
3
|
-
`);const
|
|
4
|
-
data: ${JSON.stringify({revision:
|
|
3
|
+
`);const r=i(async()=>{const d=await C(o),h=d&&await N(d);if(!e.writableEnded){if(h){e.write(`event: edited
|
|
4
|
+
data: ${JSON.stringify({revision:h.revision,heads_key:h.heads_key})}
|
|
5
5
|
|
|
6
|
-
`);return}await Z(
|
|
6
|
+
`);return}await Z(o)&&e.write(`event: deleted
|
|
7
7
|
data: {}
|
|
8
8
|
|
|
9
|
-
`),e.end()}},"notify");let s=!1,c=!1;const
|
|
9
|
+
`),e.end()}},"notify");let s=!1,c=!1;const m=i(()=>{if(s){c=!0;return}s=!0,a(r).catch(d=>{J({level:"error",event:"daemon.document_events.notify_failed",error:d}),e.end()}).finally(()=>{s=!1,c&&!e.writableEnded&&(c=!1,m())})},"wake"),p=await I(o,m),y=setInterval(()=>{e.writableEnded||e.write(`: keepalive
|
|
10
10
|
|
|
11
|
-
`)},3e4);return e.on("close",()=>{clearInterval(
|
|
11
|
+
`)},3e4);return e.on("close",()=>{clearInterval(y),p()}),!0}if(n.method==="GET"&&t.pathname.startsWith(`/assets/${f}/`)){const o=t.pathname.slice(`/assets/${f}/`.length);if(!/^[a-zA-Z0-9_.-]+$/.test(o))return l(e,404,"not_found","asset not found"),!0;const r=o==="mermaid.js"?x(j,"clients/attach/assets/mermaid.min.js"):x(j,"doc-editor",o);try{const s=A(r);e.writeHead(200,{"Content-Type":$(o)===".css"?"text/css; charset=utf-8":$(o)===".woff2"?"font/woff2":"text/javascript; charset=utf-8","Cache-Control":"public, max-age=31536000, immutable"}),e.end(s)}catch(s){if(s.code==="ENOENT")l(e,404,"not_found","asset not found");else throw s}return!0}return!1}i(ge,"serveDocumentApi");export{we as cookieValue,ve as documentNotFound,_e as documentShell,N as documentSnapshot,l as error,H as json,X as messagePage,q as requestBody,C as resolveDocument,ge as serveDocumentApi,pe as setPageHeaders};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var r=(e,n)=>y(e,"name",{value:n,configurable:!0});import{ApiError as t}from"../../../api/index.js";import{inboxPageProjection as T}from"./inbox-page.js";import{getRequestByInboxTicket as b}from"../../../core/human/requests.js";import{readableTicketIds as m}from"../router.js";import{readPageManifest as q}from"../../../core/human/page.js";import{scanInbox as I,scanPageHistory as x}from"../../../core/human/scan.js";import{readPageTicket as h,readTicketResult as k,selectedPageDir as A,validatePageTicketResponses as P,writePageProgress as E}from"../../../core/human/tickets.js";import{describePageAnswer as R}from"../../../core/human/answer.js";import{cancelHumanTicket as O,resolvePageTicket as S}from"../../human/finish.js";import{canvasOrigin as v}from"../canvas-host.js";const C="Canceled from the inbox.",D=1e3,N=/^[a-f0-9]{64}$/;async function c(e){const n=await b(e);return n===null?null:{ticketId:n.request_id,dir:n.request_dir,kind:n.kind}}r(c,"resolveTicket");function l(e){const n=e.ticket_id;if(n===void 0||!N.test(n))throw new t(400,"invalid_request","invalid ticket id");return n}r(l,"requireTicketId");function u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}r(u,"isPlainObject");function f(e,n){for(const o of Object.keys(e))if(!n.includes(o))throw new t(400,"invalid_request",`unexpected field: ${o}`)}r(f,"requireNoExtraKeys");function j(e){if(!u(e))throw new t(400,"invalid_request","respond body is required");if(f(e,["responses"]),!u(e.responses))throw new t(400,"invalid_request","`responses` must be an object");return{responses:e.responses}}r(j,"validateRespondRequest");function G(e){if(!u(e))throw new t(400,"invalid_request","progress body is required");if(f(e,["responses"]),!u(e.responses))throw new t(400,"invalid_request","`responses` must be an object");return{responses:e.responses}}r(G,"validateProgressRequest");function L(e){if(e===void 0)return{};if(!u(e))throw new t(400,"invalid_request","cancel body must be an object");if(f(e,["reason"]),e.reason===void 0)return{};const n=e.reason;if(typeof n!="string")throw new t(400,"invalid_request","`reason` must be a string");if(n.trim()===""||n.length>D)throw new t(400,"invalid_request","`reason` must be nonempty after trim and at most 1000 characters");return{reason:n}}r(L,"validateCancelRequest");const $=[/^slot ".*?" /,/^response names unknown or non-response-bearing slot id/,/^final page response is missing response-bearing slot id/];function _(e){return e instanceof Error&&$.some(n=>n.test(e.message))}r(_,"isSlotValidationError");function g(e){const n={request_id:e.id,request_dir:e.dir,ticket_id:e.inboxTicketId,kind:"page",title:e.title,placement:e.placement,dialect:e.dialect,steps:e.steps,emitted_at:e.emittedAt,source:e.source,slot_kinds:e.slotKinds,inbox:e.inbox,awaits_response:e.awaitsResponse,state:e.state};return e.subtitle!==""&&(n.subtitle=e.subtitle),e.answerDigest!==void 0&&(n.answer_digest=e.answerDigest),e.recommendedOptions.length>0&&(n.recommended_options=e.recommendedOptions.map(o=>({slot_id:o.slotId,option_id:o.optionId,label:o.label}))),e.fastAction!==void 0&&(n.fast_action={kind:e.fastAction.kind,responses:e.fastAction.responses}),n}r(g,"pageSummaryToDTO");async function H(e){const n=await I(),o=await m(e.principal,n.map(i=>i.inboxTicketId));return{status:200,body:{tickets:n.filter(i=>o.has(i.inboxTicketId)).map(i=>{if(i.kind==="page")return g(i);if(i.kind==="review")return{request_id:i.id,request_dir:i.dir,ticket_id:i.inboxTicketId,kind:"review",title:i.title,subtitle:i.subtitle,blocked_since:i.blockedSince,source:i.source,...v()===void 0?{}:{url:`${v()}/review/${i.id}`}};throw new Error(`unknown ticket kind: ${i.kind}`)}).sort((i,a)=>{const p=r(w=>w.kind==="page"?w.emitted_at:w.blocked_since,"pageTime"),d=Date.parse(p(a))-Date.parse(p(i));return d!==0?d:i.ticket_id.localeCompare(a.ticket_id)})}}}r(H,"handleList");const K=new Set(["pending","resolved","canceled","passive"]);async function M(e){const n=e.query.get("node_id");if(n==="")throw new t(400,"invalid_request","node_id must be nonempty when present");const o=e.query.get("state");if(o!==null&&!K.has(o))throw new t(400,"invalid_request","state must be one of pending, resolved, canceled, passive");const s=await x(n??void 0,o??void 0),i=await m(e.principal,s.map(d=>d.inboxTicketId));return{status:200,body:{tickets:s.filter(d=>i.has(d.inboxTicketId)).map(g)}}}r(M,"handleHistory");async function V(e){const n=l(e.params),o=await c(n);if(o===null)throw new t(404,"ticket_not_found","no matching ticket");if(o.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets have no page read operation");const s=await b(n);if(s===null||s.kind!=="page")throw new t(404,"ticket_not_found","no matching ticket");try{return{status:200,body:await T(s)}}catch{throw new t(500,"internal","the ticket could not be read")}}r(V,"handleGetPage");async function z(e){const n=l(e.params),o=j(e.body),s=await c(n);if(s===null)throw new t(404,"ticket_not_found","no matching ticket");if(s.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets submit through their own path");if((await h(s.dir)).state==="passive")throw new t(409,"page_has_no_response_lifecycle","this page has no response lifecycle");const i=await k(s.dir);if(i!==null&&i.kind!=="canceled")throw new t(409,"ticket_already_resolved","ticket was already resolved");if(i?.kind==="canceled")throw new t(409,"ticket_canceled","canceled tickets cannot be answered");try{await P(s.dir,o.responses)}catch(a){throw _(a)?new t(400,"invalid_ticket_response",a.message):new t(500,"internal","validation failed")}try{const a=await S(s.ticketId,o.responses);if(a.kind!=="page")throw new t(409,"ticket_kind_mismatch","unexpected result kind");return{status:200,body:a}}catch(a){throw a instanceof t?a:_(a)?new t(400,"invalid_ticket_response",a.message):new t(500,"internal","the ticket could not be finalized")}}r(z,"handleRespond");async function B(e){const n=l(e.params),o=G(e.body),s=await c(n);if(s===null)throw new t(404,"ticket_not_found","no matching ticket");if(s.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets do not support progress autosave");if((await h(s.dir)).state==="passive")throw new t(409,"page_has_no_response_lifecycle","this page has no response lifecycle");const i=await k(s.dir);if(i!==null&&i.kind!=="canceled")throw new t(409,"ticket_already_resolved","ticket was already resolved");try{return await E(s.dir,o.responses),{status:200,body:{}}}catch(a){throw _(a)?new t(400,"invalid_ticket_response",a.message):new t(500,"internal","progress could not be saved")}}r(B,"handleProgress");async function F(e){const n=l(e.params),o=L(e.body),s=await c(n);if(s===null)throw new t(404,"ticket_not_found","no matching ticket");if(s.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets have their own cancel path");if((await h(s.dir)).state==="passive")throw new t(409,"page_has_no_response_lifecycle","this page has no response lifecycle");try{const i=await O(s.ticketId,{reason:o.reason??C,actor:"human",disposition:"dismissed"});if(i.outcome==="already_settled"||i.result.kind!=="canceled")throw new t(409,"ticket_already_resolved","ticket was already resolved");return{status:200,body:i.result}}catch(i){throw i instanceof t?i:new t(500,"internal","the ticket could not be canceled")}}r(F,"handleCancel");async function U(e){const n=l(e.params),o=await c(n);if(o===null)throw new t(404,"ticket_not_found","no matching ticket");if(o.kind==="review")throw new t(409,"ticket_kind_unsupported","review tickets fetch responses through their own path");const s=await k(o.dir);if(s===null)throw new t(404,"ticket_pending","ticket has no response yet");if(s.kind==="canceled")throw new t(404,"ticket_canceled","canceled tickets have no response");if(s.kind!=="page")throw new t(409,"ticket_kind_mismatch","unexpected result kind");try{const i=await q(await A(o.dir));return{status:200,body:{...s,answer:R(i,s.responses,{completedAt:s.completedAt})}}}catch{throw new t(500,"internal","the ticket answer could not be read")}}r(U,"handleGetResponse");const oe=[{method:"GET",pattern:"/v1/human/inbox",handler:H},{method:"GET",pattern:"/v1/human/inbox/history",handler:M},{method:"GET",pattern:"/v1/human/inbox/:ticket_id",handler:V},{method:"GET",pattern:"/v1/human/inbox/:ticket_id/response",handler:U},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/respond",handler:z},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/progress",handler:B},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/cancel",handler:F}];export{oe as inboxRoutes,l as requireTicketId,c as resolveTicket};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var z=Object.defineProperty;var d=(n,t)=>z(n,"name",{value:t,configurable:!0});import{randomUUID as q}from"node:crypto";import{getNode as T}from"../../../core/canvas/canvas.js";import{isSafeNodeId as S}from"../../../core/canvas/paths.js";import{createComment as J,deleteComment as X,editComment as Y,getComment as A,listCommentEvents as Z,listComments as $,listReviewEvents as ee,reopenComment as ne,resolveComment as te}from"../../../core/review/comments.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{captureAnchorText as ie,requireCurrentDocumentLocked as oe}from"../../../core/review/document.js";import{forkReviewComment as re}from"../../../core/review/fork.js";import{applyRangeBatch as de}from"../../../core/review/remap.js";import{getReviewByCompanion as ae,requireVisibleReview as f}from"../../../core/review/store.js";import{ReviewOperationError as v}from"../../../core/review/types.js";import{notifyComment as se}from"../../review/comment-notify.js";import{toReviewCommentDTO as p,toReviewCommentEventDTO as x}from"../map.js";import{invalidRequest as ce,isRecord as I,objectBody as R,requireParam as D,requiredString as P}from"./validate.js";const j=/^[a-f0-9]{32}$/,L=/^[a-f0-9]{64}$/,ue=new Set(["open","resolved","deleted","all"]),me=new Set(["wake","quiet"]);function m(n){ce("review comment request",n)}d(m,"invalidRequest");function le(n,t,e){const i=n[t];if(i!==void 0){if(typeof i!="string"||!L.test(i)){e.push({field:t,problem:"must be a lowercase SHA-256 hex digest",received:i});return}return i}}d(le,"optionalSha256");function M(n,t,e){const i=n[t];if(typeof i!="string"||!L.test(i)){e.push({field:t,problem:"must be a lowercase SHA-256 hex digest",...i===void 0?{}:{received:i}});return}return i}d(M,"requiredSha256");function B(n,t){const e=n.deliver;if(e!==void 0){if(typeof e!="string"||!me.has(e)){t.push({field:"deliver",problem:"must be wake or quiet",received:e});return}return e}}d(B,"optionalDeliver");function fe(n,t){const e=n.if_revision;if(e!==void 0){if(!Number.isSafeInteger(e)||e<0){t.push({field:"if_revision",problem:"must be a non-negative safe integer",received:e});return}return e}}d(fe,"optionalRevision");function F(n,t){const e=n.actor_node_id;return e==null?{kind:"human",node_id:null}:typeof e!="string"||!S(e)?(t.push({field:"actor_node_id",problem:"must be a safe node id or null",received:e}),null):{kind:"node",node_id:e}}d(F,"actorFrom");async function G(n,t,e){await T(n)===null&&e.push({field:t,problem:"must name an existing node",received:n})}d(G,"requireKnownNode");async function N(n,t){n.node_id!==null&&await G(n.node_id,"actor_node_id",t)}d(N,"requireKnownActor");function H(n,t,e){if(!I(n)){e.push({field:t,problem:"must be an anchor object",received:n});return}const i=["line","end_line","col_start","col_end","quote"];for(const r of Object.keys(n))i.includes(r)||e.push({field:`${t}.${r}`,problem:"is not allowed",received:n[r]});const o=n.line,a=n.end_line;typeof o!="number"&&e.push({field:`${t}.line`,problem:"must be a number",...o===void 0?{}:{received:o}}),typeof a!="number"&&e.push({field:`${t}.end_line`,problem:"must be a number",...a===void 0?{}:{received:a}});for(const r of["col_start","col_end"]){const s=n[r];s!==void 0&&typeof s!="number"&&e.push({field:`${t}.${r}`,problem:"must be a number",received:s})}if(n.quote!==void 0&&typeof n.quote!="string"&&e.push({field:`${t}.quote`,problem:"must be a string",received:n.quote}),!(typeof o!="number"||typeof a!="number"))return{line:o,end_line:a,...typeof n.col_start=="number"?{col_start:n.col_start}:{},...typeof n.col_end=="number"?{col_end:n.col_end}:{},...typeof n.quote=="string"?{quote:n.quote}:{}}}d(H,"anchorFrom");function w(n,t){return D(n,"review_id","must be a safe review id",S,t)}d(w,"requireReviewId");function C(n,t){return D(n,"comment_id","must be a 32-character lowercase hexadecimal id",e=>j.test(e),t)}d(C,"requireCommentId");async function b(n){const t=await f(n);if(t.state!=="open")throw new v("review_terminal","review already has a terminal outcome",{state:t.state,requested:"comment",review:t});return t}d(b,"requireOpenReview");async function U(n){const t=n===null?void 0:(await T(n))?.review_binding?.review_id,e=n===null?null:await ae(n)??(t===void 0?null:await f(t));if(e===null||e.state!=="open")throw new v("review_required","an open review is required when no review id is supplied",{actor_node_id:n});return e}d(U,"requireCompanionReview");async function he(n){return{comment:p(n),events:(await Z(n.comment_id)).map(x)}}d(he,"toDetail");function _e(n,t){return{attempted:!0,target_node_id:n.companion_node_id,status:"failed",woke:!1,error:t instanceof Error?t.message:String(t)}}d(_e,"deliveryFailure");async function V(n){if(!n.changed)return{comment:p(n.comment),changed:!1};let t;try{t=await se({review:n.review,comment:n.comment,verb:n.verb,actor_node_id:n.actor.node_id,deliver:n.deliver,operation_id:n.operationId})}catch(e){t=_e(n.review,e)}return{comment:p(n.comment),changed:!0,delivery:t}}d(V,"mutationResult");async function ve(n,t){const e=[],i=R(n.body,["text","anchor","doc_hash","actor_node_id","deliver"],e),o=t==="review"?(()=>{const u=w(n,e);return u===void 0?void 0:{kind:"review",review_id:u}})():{kind:"self"},a=P(i,"text",e),r=H(i.anchor,"anchor",e),s=le(i,"doc_hash",e),c=F(i,e),h=B(i,e);return c!==null&&await N(c,e),(e.length>0||o===void 0||a===void 0||r===void 0||c===null)&&m(e),{selector:o,text:a,anchor:r,...s===void 0?{}:{doc_hash:s},actor:c,...h===void 0?{}:{deliver:h}}}d(ve,"parseCreate");async function pe(n,t){const e=[],i=R(n.body,t?["text","actor_node_id","deliver","if_revision"]:["actor_node_id","deliver","if_revision"],e),o=C(n,e),a=t?P(i,"text",e):void 0,r=F(i,e),s=B(i,e),c=fe(i,e);return r!==null&&await N(r,e),(e.length>0||o===void 0||r===null||t&&a===void 0)&&m(e),{comment_id:o,...a===void 0?{}:{text:a},actor:r,...s===void 0?{}:{deliver:s},...c===void 0?{}:{if_revision:c}}}d(pe,"parseAction");function we(n){const t=[],e=R(n.body,["from_doc_hash","to_doc_hash","entries"],t),i=w(n,t),o=M(e,"from_doc_hash",t),a=M(e,"to_doc_hash",t),r=e.entries,s=[];return Array.isArray(r)?r.forEach((c,h)=>{const u=`entries[${h}]`;if(!I(c)){t.push({field:u,problem:"must be an object",received:c});return}for(const g of Object.keys(c))["comment_id","anchor","detached"].includes(g)||t.push({field:`${u}.${g}`,problem:"is not allowed",received:c[g]});const l=c.comment_id;if(typeof l!="string"||!j.test(l)){t.push({field:`${u}.comment_id`,problem:"must be a 32-character lowercase hexadecimal id",received:l});return}const W=c.anchor!==void 0,_=c.detached;_!==void 0&&_!==!0&&t.push({field:`${u}.detached`,problem:"must be true when present",received:_});const E=_===!0;if(W===E){t.push({field:u,problem:"must provide exactly one of anchor or detached: true"});return}if(E){s.push({comment_id:l,detached:!0});return}const O=H(c.anchor,`${u}.anchor`,t);O!==void 0&&s.push({comment_id:l,anchor:O})}):t.push({field:"entries",problem:"must be an array",received:r}),(t.length>0||i===void 0||o===void 0||a===void 0||!Array.isArray(r))&&m(t),{review_id:i,request:{from_doc_hash:o,to_doc_hash:a,entries:s}}}d(we,"parseRangeBatch");async function be(n,t,e){for(const[r,s]of n.query)r!=="status"&&(r!=="actor_node_id"||t!=="self")&&e.push({field:r,problem:"is not allowed",received:s});const i=n.query.getAll("status");(i.length>1||i.length===1&&!ue.has(i[0]))&&e.push({field:"status",problem:"must be open, resolved, deleted, or all",received:i.length>1?i:i[0]});const o=n.query.getAll("actor_node_id");let a=null;if(o.length>1)e.push({field:"actor_node_id",problem:"must appear at most once",received:o});else if(o.length===1){const r=o[0];S(r)?(a=r,await G(r,"actor_node_id",e)):e.push({field:"actor_node_id",problem:"must be a safe node id",received:r})}return{...i.length===0?{}:{status:i[0]},actor_node_id:a}}d(be,"parseListQuery");function ye(n,t){const e={};for(const[i,o]of n.query)i!=="since_seq"&&i!=="limit"&&t.push({field:i,problem:"is not allowed",received:o});for(const i of["since_seq","limit"]){const o=n.query.getAll(i);if(o.length>1){t.push({field:i,problem:"must appear at most once",received:o});continue}if(o.length===0)continue;const a=o[0],r=Number(a);if(!Number.isSafeInteger(r)||r<0||String(r)!==a){t.push({field:i,problem:"must be a non-negative safe integer",received:a});continue}e[i]=r}return e.limit!==void 0&&e.limit<1&&t.push({field:"limit",problem:"must be at least 1",received:e.limit}),e}d(ye,"parseEventQuery");async function Q(n,t){const e=await ve(n,t),i=q(),o=await k(async a=>{const r=e.selector.kind==="review"?await b(e.selector.review_id):await b((await U(e.actor.node_id)).review_id),s=await oe(a,r.review_id,e.doc_hash??r.anchor_base_sha256),c=await J({review_id:r.review_id,text:e.text,anchor:e.anchor,line_text:ie(s.lines,e.anchor),doc_hash:s.sha256,actor:e.actor,operation_id:i});return{review:r,mutation:c}});return{status:200,body:await V({review:o.review,...o.mutation,verb:"create",actor:e.actor,deliver:e.deliver,operationId:i})}}d(Q,"handleCreate");async function K(n,t){const e=[],i=t==="review"?(()=>{const s=w(n,e);return s===void 0?void 0:{kind:"review",review_id:s}})():{kind:"self"},o=await be(n,t,e);(e.length>0||i===void 0)&&m(e);const a=i.kind==="review"?await f(i.review_id):await U(o.actor_node_id);return{status:200,body:{review_id:a.review_id,comments:(await $(a.review_id,o)).map(p)}}}d(K,"handleList");async function ge(n){const t=[],e=w(n,t),i=ye(n,t);(t.length>0||e===void 0)&&m(t);const o=await f(e),a=await ee(o.review_id,i);return{status:200,body:{review_id:o.review_id,events:a.events.map(x),next_since_seq:a.events.length===0?null:a.next_since_seq}}}d(ge,"handleEvents");async function qe(n){const{review_id:t,request:e}=we(n),i=q(),o=await k(async()=>{const r=await b(t),s=(await $(r.review_id)).length,c=await de({review_id:r.review_id,...e,actor:{kind:"human",node_id:null},operation_id:i});return{review:r,nondeleted:s,applied:c}});return{status:200,body:{review_id:o.review.review_id,anchor_base_sha256:o.applied.anchor_base_sha256,updated:o.applied.updated,detached:o.applied.detached,unchanged:o.nondeleted-o.applied.updated}}}d(qe,"handleRanges");async function Se(n){const t=[],e=C(n,t);(t.length>0||e===void 0)&&m(t);const i=await A(e);if(i===null)throw new v("unknown_comment","comment was not found",{received:e});return await f(i.review_id),{status:200,body:await he(i)}}d(Se,"handleDetail");async function y(n,t){const e=await pe(n,t==="edit"),i=q(),o=await k(async()=>{const a=await A(e.comment_id);if(a===null)throw new v("unknown_comment","comment was not found",{received:e.comment_id});const r=await b(a.review_id),s=t==="edit"?await Y(e.comment_id,{text:e.text,actor:e.actor,operation_id:i,if_revision:e.if_revision}):t==="resolve"?await te(e.comment_id,{actor:e.actor,operation_id:i,if_revision:e.if_revision}):t==="reopen"?await ne(e.comment_id,{actor:e.actor,operation_id:i,if_revision:e.if_revision}):await X(e.comment_id,{actor:e.actor,operation_id:i,if_revision:e.if_revision});return{review:r,mutation:s}});return{status:200,body:await V({review:o.review,...o.mutation,verb:t,actor:e.actor,deliver:e.deliver,operationId:i})}}d(y,"handleAction");async function ke(n){const t=[],e=C(n,t);(t.length>0||e===void 0)&&m(t);const i=await re(e);return{status:200,body:{comment_id:e,node_id:i.node_id,cwd:i.cwd}}}d(ke,"handleFork");const Be=[{method:"POST",pattern:"/v1/human/reviews/self/comments",handler:d(n=>Q(n,"self"),"handler")},{method:"GET",pattern:"/v1/human/reviews/self/comments",handler:d(async n=>await K(n,"self"),"handler")},{method:"POST",pattern:"/v1/human/reviews/:review_id/comments",handler:d(n=>Q(n,"review"),"handler")},{method:"GET",pattern:"/v1/human/reviews/:review_id/comments",handler:d(async n=>await K(n,"review"),"handler")},{method:"GET",pattern:"/v1/human/reviews/:review_id/comment-events",handler:ge},{method:"POST",pattern:"/v1/human/reviews/:review_id/comment-ranges",handler:qe},{method:"GET",pattern:"/v1/human/comments/:comment_id",handler:Se},{method:"POST",pattern:"/v1/human/comments/:comment_id/edit",handler:d(n=>y(n,"edit"),"handler")},{method:"POST",pattern:"/v1/human/comments/:comment_id/resolve",handler:d(n=>y(n,"resolve"),"handler")},{method:"POST",pattern:"/v1/human/comments/:comment_id/reopen",handler:d(n=>y(n,"reopen"),"handler")},{method:"POST",pattern:"/v1/human/comments/:comment_id/delete",handler:d(n=>y(n,"delete"),"handler")},{method:"POST",pattern:"/v1/human/comments/:comment_id/fork",handler:ke}];export{Be as reviewCommentRoutes};
|
|
1
|
+
var j=Object.defineProperty;var r=(n,t)=>j(n,"name",{value:t,configurable:!0});import{randomUUID as b}from"node:crypto";import{getNode as g}from"../../../core/canvas/canvas.js";import{isSafeNodeId as w}from"../../../core/canvas/paths.js";import{createComment as F,deleteComment as G,editComment as L,getComment as q,listCommentEvents as N,listComments as H,listReviewEvents as U,reopenComment as B,resolveComment as Q}from"../../../core/review/comments.js";import{withCanvasWrite as S}from"../../../core/canvas/db.js";import{anchorInDocument as V}from"../../../core/review/anchors.js";import{currentReviewTextLocked as K}from"../../../core/review/document.js";import{forkReviewComment as W}from"../../../core/review/fork.js";import{getReviewByCompanion as z,requireVisibleReview as m}from"../../../core/review/store.js";import{ReviewOperationError as f}from"../../../core/review/types.js";import{notifyComment as J}from"../../review/comment-notify.js";import{toReviewCommentDTO as l,toReviewCommentEventDTO as k}from"../map.js";import{invalidRequest as X,isRecord as Y,objectBody as C,requireParam as x,requiredString as R}from"./validate.js";const Z=/^[a-f0-9]{32}$/,E=/^[a-f0-9]{64}$/,ee=new Set(["open","resolved","deleted","all"]),ne=new Set(["wake","quiet"]);function u(n){X("review comment request",n)}r(u,"invalidRequest");function Re(n,t,e){const i=n[t];if(i!==void 0){if(typeof i!="string"||!E.test(i)){e.push({field:t,problem:"must be a lowercase SHA-256 hex digest",received:i});return}return i}}r(Re,"optionalSha256");function Ee(n,t,e){const i=n[t];if(typeof i!="string"||!E.test(i)){e.push({field:t,problem:"must be a lowercase SHA-256 hex digest",...i===void 0?{}:{received:i}});return}return i}r(Ee,"requiredSha256");function T(n,t){const e=n.deliver;if(e!==void 0){if(typeof e!="string"||!ne.has(e)){t.push({field:"deliver",problem:"must be wake or quiet",received:e});return}return e}}r(T,"optionalDeliver");function te(n,t){const e=n.if_revision;if(e!==void 0){if(!Number.isSafeInteger(e)||e<0){t.push({field:"if_revision",problem:"must be a non-negative safe integer",received:e});return}return e}}r(te,"optionalRevision");function O(n,t){const e=n.actor_node_id;return e==null?{kind:"human",node_id:null}:typeof e!="string"||!w(e)?(t.push({field:"actor_node_id",problem:"must be a safe node id or null",received:e}),null):{kind:"node",node_id:e}}r(O,"actorFrom");async function I(n,t,e){await g(n)===null&&e.push({field:t,problem:"must name an existing node",received:n})}r(I,"requireKnownNode");async function A(n,t){n.node_id!==null&&await I(n.node_id,"actor_node_id",t)}r(A,"requireKnownActor");function ie(n,t,e){if(!Y(n)){e.push({field:t,problem:"must be an anchor object",received:n});return}for(const o of Object.keys(n))["quote","prefix","suffix","offset"].includes(o)||e.push({field:`${t}.${o}`,problem:"is not allowed",received:n[o]});const i=n.quote;if(typeof i!="string"||i.trim()===""){e.push({field:`${t}.quote`,problem:"must be a non-empty string",...i===void 0?{}:{received:i}});return}for(const o of["prefix","suffix"])n[o]!==void 0&&typeof n[o]!="string"&&e.push({field:`${t}.${o}`,problem:"must be a string",received:n[o]});return n.offset!==void 0&&typeof n.offset!="number"&&e.push({field:`${t}.offset`,problem:"must be a number",received:n.offset}),{quote:i,...typeof n.prefix=="string"?{prefix:n.prefix}:{},...typeof n.suffix=="string"?{suffix:n.suffix}:{},...typeof n.offset=="number"?{offset:n.offset}:{}}}r(ie,"anchorFrom");function p(n,t){return x(n,"review_id","must be a safe review id",w,t)}r(p,"requireReviewId");function _(n,t){return x(n,"comment_id","must be a 32-character lowercase hexadecimal id",e=>Z.test(e),t)}r(_,"requireCommentId");async function h(n){const t=await m(n);if(t.state!=="open")throw new f("review_terminal","review already has a terminal outcome",{state:t.state,requested:"comment",review:t});return t}r(h,"requireOpenReview");async function D(n){const t=n===null?void 0:(await g(n))?.review_binding?.review_id,e=n===null?null:await z(n)??(t===void 0?null:await m(t));if(e===null||e.state!=="open")throw new f("review_required","an open review is required when no review id is supplied",{actor_node_id:n});return e}r(D,"requireCompanionReview");async function oe(n){return{comment:l(n),events:(await N(n.comment_id)).map(k)}}r(oe,"toDetail");function re(n,t){return{attempted:!0,target_node_id:n.companion_node_id,status:"failed",woke:!1,error:t instanceof Error?t.message:String(t)}}r(re,"deliveryFailure");async function P(n){if(!n.changed)return{comment:l(n.comment),changed:!1};let t;try{t=await J({review:n.review,comment:n.comment,verb:n.verb,actor_node_id:n.actor.node_id,deliver:n.deliver,operation_id:n.operationId})}catch(e){t=re(n.review,e)}return{comment:l(n.comment),changed:!0,delivery:t}}r(P,"mutationResult");async function de(n,t){const e=[],i=C(n.body,["text","anchor","actor_node_id","deliver"],e),o=t==="review"?(()=>{const y=p(n,e);return y===void 0?void 0:{kind:"review",review_id:y}})():{kind:"self"},a=R(i,"text",e),d=ie(i.anchor,"anchor",e),s=O(i,e),c=T(i,e);return s!==null&&await A(s,e),(e.length>0||o===void 0||a===void 0||d===void 0||s===null)&&u(e),{selector:o,text:a,anchor:d,actor:s,...c===void 0?{}:{deliver:c}}}r(de,"parseCreate");async function ae(n,t){const e=[],i=C(n.body,t?["text","actor_node_id","deliver","if_revision"]:["actor_node_id","deliver","if_revision"],e),o=_(n,e),a=t?R(i,"text",e):void 0,d=O(i,e),s=T(i,e),c=te(i,e);return d!==null&&await A(d,e),(e.length>0||o===void 0||d===null||t&&a===void 0)&&u(e),{comment_id:o,...a===void 0?{}:{text:a},actor:d,...s===void 0?{}:{deliver:s},...c===void 0?{}:{if_revision:c}}}r(ae,"parseAction");async function se(n,t,e){for(const[d,s]of n.query)d!=="status"&&(d!=="actor_node_id"||t!=="self")&&e.push({field:d,problem:"is not allowed",received:s});const i=n.query.getAll("status");(i.length>1||i.length===1&&!ee.has(i[0]))&&e.push({field:"status",problem:"must be open, resolved, deleted, or all",received:i.length>1?i:i[0]});const o=n.query.getAll("actor_node_id");let a=null;if(o.length>1)e.push({field:"actor_node_id",problem:"must appear at most once",received:o});else if(o.length===1){const d=o[0];w(d)?(a=d,await I(d,"actor_node_id",e)):e.push({field:"actor_node_id",problem:"must be a safe node id",received:d})}return{...i.length===0?{}:{status:i[0]},actor_node_id:a}}r(se,"parseListQuery");function ce(n,t){const e={};for(const[i,o]of n.query)i!=="since_seq"&&i!=="limit"&&t.push({field:i,problem:"is not allowed",received:o});for(const i of["since_seq","limit"]){const o=n.query.getAll(i);if(o.length>1){t.push({field:i,problem:"must appear at most once",received:o});continue}if(o.length===0)continue;const a=o[0],d=Number(a);if(!Number.isSafeInteger(d)||d<0||String(d)!==a){t.push({field:i,problem:"must be a non-negative safe integer",received:a});continue}e[i]=d}return e.limit!==void 0&&e.limit<1&&t.push({field:"limit",problem:"must be at least 1",received:e.limit}),e}r(ce,"parseEventQuery");async function $(n,t){const e=await de(n,t),i=b(),o=await S(async a=>{const d=e.selector.kind==="review"?await h(e.selector.review_id):await h((await D(e.actor.node_id)).review_id),s=V(await K(a,d.review_id),e.anchor),c=await F({review_id:d.review_id,text:e.text,anchor:s,actor:e.actor,operation_id:i});return{review:d,mutation:c}});return{status:200,body:await P({review:o.review,...o.mutation,verb:"create",actor:e.actor,deliver:e.deliver,operationId:i})}}r($,"handleCreate");async function M(n,t){const e=[],i=t==="review"?(()=>{const s=p(n,e);return s===void 0?void 0:{kind:"review",review_id:s}})():{kind:"self"},o=await se(n,t,e);(e.length>0||i===void 0)&&u(e);const a=i.kind==="review"?await m(i.review_id):await D(o.actor_node_id);return{status:200,body:{review_id:a.review_id,comments:(await H(a.review_id,o)).map(l)}}}r(M,"handleList");async function ue(n){const t=[],e=p(n,t),i=ce(n,t);(t.length>0||e===void 0)&&u(t);const o=await m(e),a=await U(o.review_id,i);return{status:200,body:{review_id:o.review_id,events:a.events.map(k),next_since_seq:a.events.length===0?null:a.next_since_seq}}}r(ue,"handleEvents");async function me(n){const t=[],e=_(n,t);(t.length>0||e===void 0)&&u(t);const i=await q(e);if(i===null)throw new f("unknown_comment","comment was not found",{received:e});return await m(i.review_id),{status:200,body:await oe(i)}}r(me,"handleDetail");async function v(n,t){const e=await ae(n,t==="edit"),i=b(),o=await S(async()=>{const a=await q(e.comment_id);if(a===null)throw new f("unknown_comment","comment was not found",{received:e.comment_id});const d=await h(a.review_id),s=t==="edit"?await L(e.comment_id,{text:e.text,actor:e.actor,operation_id:i,if_revision:e.if_revision}):t==="resolve"?await Q(e.comment_id,{actor:e.actor,operation_id:i,if_revision:e.if_revision}):t==="reopen"?await B(e.comment_id,{actor:e.actor,operation_id:i,if_revision:e.if_revision}):await G(e.comment_id,{actor:e.actor,operation_id:i,if_revision:e.if_revision});return{review:d,mutation:s}});return{status:200,body:await P({review:o.review,...o.mutation,verb:t,actor:e.actor,deliver:e.deliver,operationId:i})}}r(v,"handleAction");async function fe(n){const t=[],e=_(n,t);(t.length>0||e===void 0)&&u(t);const i=await W(e);return{status:200,body:{comment_id:e,node_id:i.node_id,cwd:i.cwd}}}r(fe,"handleFork");const Te=[{method:"POST",pattern:"/v1/human/reviews/self/comments",handler:r(n=>$(n,"self"),"handler")},{method:"GET",pattern:"/v1/human/reviews/self/comments",handler:r(async n=>await M(n,"self"),"handler")},{method:"POST",pattern:"/v1/human/reviews/:review_id/comments",handler:r(n=>$(n,"review"),"handler")},{method:"GET",pattern:"/v1/human/reviews/:review_id/comments",handler:r(async n=>await M(n,"review"),"handler")},{method:"GET",pattern:"/v1/human/reviews/:review_id/comment-events",handler:ue},{method:"GET",pattern:"/v1/human/comments/:comment_id",handler:me},{method:"POST",pattern:"/v1/human/comments/:comment_id/edit",handler:r(n=>v(n,"edit"),"handler")},{method:"POST",pattern:"/v1/human/comments/:comment_id/resolve",handler:r(n=>v(n,"resolve"),"handler")},{method:"POST",pattern:"/v1/human/comments/:comment_id/reopen",handler:r(n=>v(n,"reopen"),"handler")},{method:"POST",pattern:"/v1/human/comments/:comment_id/delete",handler:r(n=>v(n,"delete"),"handler")},{method:"POST",pattern:"/v1/human/comments/:comment_id/fork",handler:fe}];export{Te as reviewCommentRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var g=Object.defineProperty;var s=(n,e)=>g(n,"name",{value:e,configurable:!0});import{ApiError as p}from"../../../api/index.js";import{isCloudRole as R}from"../../../core/canvas/person.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{isSafeNodeId as h}from"../../../core/canvas/paths.js";import{readDocument as q}from"../../../core/graph/documents.js";import{getById as S}from"../../../core/graph/objects.js";import{checkoutsForCwd as E}from"../../../core/graph/repo-sync/repos.js";import{getNode as _}from"../../../core/canvas/canvas.js";import{assertScope as T}from"../../../core/scopes.js";import{createReview as C}from"../../../core/review/birth.js";import{readAnchorBase as A,listReviews as $,requireVisibleReview as b}from"../../../core/review/store.js";import{canvasOrigin as I}from"../canvas-host.js";import{cancelReview as D,submitReviewApproval as O}from"../../review/finish.js";import{toFeedbackResultDTO as L,toReviewDTO as F}from"../map.js";import{readerFor as N,resolveRef as P,warmReaderRepos as j}from"../reader.js";import{actsAsPerson as B,canReadNode as G}from"../router.js";import{invalidRequest as V,objectBody as v,optionalString as c,requireParam as W,requiredString as y}from"./validate.js";import{filterAsync as K}from"../../../core/async-array.js";const M=new Set(["open","approved","canceled"]),U=["origin_kind","origin_node_id","document","idempotency_key","subtitle","output_path"],z=["reason","actor","disposition"];function l(n){V("review request",n)}s(l,"invalidRequest");function w(n,e){return W(n,"review_id","must be a safe review id",h,e)}s(w,"requireReviewId");function m(n){return{...F(n,n.state==="approved"?{result_path:`${n.review_dir}/result.json`}:{}),review_dir:n.review_dir}}s(m,"toReviewResponseDTO");function H(n){const e=[],i=v(n.body,U,e),o=i.origin_kind,t=o==="ticket"||o==="inline"?o:void 0;t===void 0&&e.push({field:"origin_kind",problem:"must be ticket or inline",...o===void 0?{}:{received:o}});const r=y(i,"origin_node_id",e);r!==void 0&&!h(r)&&e.push({field:"origin_node_id",problem:"must be a safe node id",received:r});const d=c(i,"document",e);d===void 0&&e.push({field:"document",problem:"is required"});const a=y(i,"idempotency_key",e);a!==void 0&&a.length>128&&e.push({field:"idempotency_key",problem:"must be at most 128 characters",received:a});const f=c(i,"subtitle",e),u=c(i,"output_path",e);return t==="ticket"&&f===void 0&&i.subtitle===void 0&&e.push({field:"subtitle",problem:"is required for ticket reviews"}),t==="inline"&&i.subtitle!==void 0&&e.push({field:"subtitle",problem:"is only allowed for ticket reviews",received:i.subtitle}),t==="inline"&&i.output_path!==void 0&&e.push({field:"output_path",problem:"is only allowed for ticket reviews",received:i.output_path}),u!==void 0&&R()&&e.push({field:"output_path",problem:"is not supported on the cloud: a review result is projected only to its own request files",received:u}),(e.length>0||t===void 0||r===void 0||d===void 0||!h(r)||a===void 0||a.length>128)&&l(e),{origin_kind:t,origin_node_id:r,document:d,idempotency_key:a,...f===void 0?{}:{subtitle:f},...u===void 0?{}:{output_path:u}}}s(H,"parseCreate");function J(n){const e=[],i={},o=new Set(["state","origin_node_id","file"]);for(const[t,r]of n.query.entries())o.has(t)||e.push({field:t,problem:"is not allowed",received:r});for(const t of o){const r=n.query.getAll(t);if(r.length>1){e.push({field:t,problem:"must appear at most once",received:r});continue}const d=r[0];d!==void 0&&(t==="state"?M.has(d)?i.state=d:e.push({field:t,problem:"must be open, approved, or canceled",received:d}):t==="origin_node_id"?h(d)?i.origin_node_id=d:e.push({field:t,problem:"must be a safe node id",received:d}):d===""?e.push({field:t,problem:"must be a non-empty string",received:d}):i.file=d)}return e.length>0&&l(e),i}s(J,"parseList");function Q(n,e){const i=n.body===void 0?{}:v(n.body,z,e),o=c(i,"reason",e),t=c(i,"actor",e),r=c(i,"disposition",e);return r!==void 0&&r!=="canceled"&&r!=="dismissed"&&e.push({field:"disposition",problem:'must be "canceled" or "dismissed"',received:r}),{...o===void 0?{}:{reason:o},...t===void 0?{}:{actor:t},...r==="canceled"||r==="dismissed"?{disposition:r}:{}}}s(Q,"parseCancel");function X(n,e){v(n.body,[],e)}s(X,"requireEmptyBody");async function Y(n){const e=H(n);if(I()===void 0)throw new p(409,"no_canvas_host","this runtime has no canvas host to serve the review page",{next:"Reviews open in the browser at the canvas host (`CRTR_CANVAS_URL`); file this review from a cloud runtime."});const i=await _(e.origin_node_id);i!==null&&T(i,"crtr:act");const{document:o,...t}=e,r=await C({...t,document:await Z(n,o)});return{status:200,body:m(r)}}s(Y,"handleCreate");async function Z(n,e){return await j(n.principal),await k(async i=>{const o=await N(i,n),t=await P(i,o,e);if("remote"in t)throw new p(404,"not_found",`no document named ${t.remote} on this runtime`,{next:"Check the name with `crtr canvas search`."});if("deleted"in t)throw new p(404,"not_found",`${t.deleted.name} is deleted`,{id:t.deleted.id,deleted:!0});if(t.type!=="document")throw new p(400,"invalid_request",`${e} is a ${t.type}, not a document`);const r=await q(i,o,t,async(f,u)=>await E(i,f,u));if(r.needsMerge)throw new p(409,"needs_merge",`${t.name} has ${r.heads.length} heads; merge them before a review`,{id:t.id,next:`Read it with \`crtr canvas read ${t.id}\` and write the merged body with \`crtr doc edit\`.`});const d=t.owner===null?null:await S(i,t.owner),a=d===null?"":d.type==="node"?d.id:d.name;return{id:t.id,name:a===""?t.name:`${a}/${t.name}`,base:r.record.heads_key,body:r.heads[0].body}})}s(Z,"reviewedDocument");async function x(n){const e=J(n);return{status:200,body:{reviews:(await K(await $(e),async o=>{if(B(n.principal))return!0;const t=await _(o.origin_node_id);return t!==null&&await G(n.principal,t.grantee??"app:terminal",t.node_id)})).map(m)}}}s(x,"handleList");async function ee(n){const e=[],i=w(n,e);return(e.length>0||i===void 0)&&l(e),{status:200,body:m(await b(i))}}s(ee,"handleRead");async function te(n){const e=[],i=w(n,e);X(n,e),(e.length>0||i===void 0)&&l(e);const o=await O(i);return{status:200,body:o.outcome==="awaiting_companion"?{review:m(o.record),outcome:o.outcome}:{review:m(o.record),result:L(o.result),outcome:o.outcome}}}s(te,"handleSubmit");async function ie(n){const e=[],i=w(n,e),o=Q(n,e);(e.length>0||i===void 0)&&l(e);const t=await D(i,o);return{status:200,body:{review:m(t.record),outcome:t.outcome}}}s(ie,"handleCancel");async function ne(n){const e=[],i=w(n,e);(e.length>0||i===void 0)&&l(e);const o=await b(i),t=await A(o.review_id);if(t===null)throw new Error(`review anchor base is missing: ${o.review_id}`);return{status:200,body:{review_id:o.review_id,anchor_base_sha256:t.sha256,anchor_base_text:new TextDecoder("utf-8",{fatal:!0}).decode(t.bytes),file:o.file}}}s(ne,"handleDocument");const ke=[{method:"POST",pattern:"/v1/human/reviews",scope:"crtr:act",handler:Y},{method:"GET",pattern:"/v1/human/reviews",handler:x},{method:"GET",pattern:"/v1/human/reviews/:review_id",handler:ee},{method:"POST",pattern:"/v1/human/reviews/:review_id/submit",handler:te},{method:"POST",pattern:"/v1/human/reviews/:review_id/cancel",handler:ie},{method:"GET",pattern:"/v1/human/reviews/:review_id/document",handler:ne}];export{H as parseCreate,ke as reviewRoutes};
|