@deepraxis/cli 0.2.2-dev.d73d5e4 → 0.2.2-dev.d8d3f52

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/praxis.js CHANGED
@@ -6946,6 +6946,7 @@ var require_public_api = __commonJS((exports) => {
6946
6946
 
6947
6947
  // src/main.ts
6948
6948
  import { readFile as readFile3 } from "node:fs/promises";
6949
+ import { createHash as createHash3 } from "node:crypto";
6949
6950
  import { spawn as spawn2 } from "node:child_process";
6950
6951
  import { createInterface } from "node:readline";
6951
6952
 
@@ -17012,7 +17013,7 @@ Execution errors include error.details.prints containing output printed before f
17012
17013
  name: "to",
17013
17014
  type: "number",
17014
17015
  required: false,
17015
- description: "Range end for kind mix, in seconds on the project clock, exclusive. A range longer than 120 seconds is refused; request several ranges instead."
17016
+ description: "Range end for kind mix, in seconds on the project clock, exclusive. An end up to 0.05 s past the timeline's end (a rounded duration) is read as the end; further past is refused. A range longer than 120 seconds is refused; request several ranges instead."
17016
17017
  },
17017
17018
  {
17018
17019
  name: "revision",
@@ -17166,7 +17167,7 @@ Execution errors include error.details.prints containing output printed before f
17166
17167
  name: "folder",
17167
17168
  type: "string",
17168
17169
  required: false,
17169
- description: "Optional destination path within the bound media library; omitted uses its default folder."
17170
+ description: "Optional destination path within the bound media library; omitted uses its default folder. Naming a binding or a folder also imports the finished video into that media library as an asset. Omit both and the export is a file only: read file.url to download it."
17170
17171
  },
17171
17172
  {
17172
17173
  name: "name",
@@ -17184,7 +17185,7 @@ Execution errors include error.details.prints containing output printed before f
17184
17185
  name: "binding",
17185
17186
  type: "string",
17186
17187
  required: false,
17187
- description: "Writable binding name used as the export destination; omission uses default_upload."
17188
+ description: "Writable binding name used as the export destination; omission uses default_upload. Naming a binding or a folder also imports the finished video into that media library as an asset. Omit both and the export is a file only; read file.url to download it."
17188
17189
  },
17189
17190
  {
17190
17191
  name: "revision",
@@ -17289,7 +17290,7 @@ Execution errors include error.details.prints containing output printed before f
17289
17290
  resource: "cut.projects.renders",
17290
17291
  method: "create",
17291
17292
  summary: "Create draft range render",
17292
- description: "Render one interval of the timeline so you can hear or look at how that passage comes out, without publishing anything to a media library. Choose kind audio for the mixed soundtrack as an .m4a file, or kind video for a draft-quality .mp4 with picture and sound. from and to are seconds on the project clock and must satisfy 0 <= from < to, to <= the timeline duration, and to - from <= 120; a longer passage is requested in several 分段请求 ranges and joined by the caller. The result is a temporary file (purpose user_data) that expires 24 hours after it is stored and is never imported into a library, so it is not a deliverable and carries no cut-export tag. HTTP 202 only accepts the job; poll praxis.cut.renders.retrieve using the returned id until status is done or failed, then read url while it lasts. A draft also bills like a draft export, by rendered seconds. Each project runs at most 2 draft renders at a time, a budget separate from its exports; a third answers HTTP 429 CUT_BUSY and the same call succeeds once one finishes.",
17293
+ description: "Render one interval of the timeline so you can hear or look at how that passage comes out, without publishing anything to a media library. Choose kind audio for the mixed soundtrack as an .m4a file, or kind video for a draft-quality .mp4 with picture and sound. from and to are seconds on the project clock and must satisfy 0 <= from < to, to <= the timeline duration (an end up to 0.05 s past it, a rounded duration, is read as the end), and to - from <= 120; a longer passage is requested in several 分段请求 ranges and joined by the caller. The result is a temporary file (purpose user_data) that expires 24 hours after it is stored and is never imported into a library, so it is not a deliverable and carries no cut-export tag. HTTP 202 only accepts the job; poll praxis.cut.renders.retrieve using the returned id until status is done or failed, then read url while it lasts. A draft also bills like a draft export, by rendered seconds. Each project runs at most 2 draft renders at a time, a budget separate from its exports; a third answers HTTP 429 CUT_BUSY and the same call succeeds once one finishes.",
17293
17294
  http: "POST",
17294
17295
  path: "/cut/v1/projects/{project_id}/renders",
17295
17296
  streaming: "no",
@@ -20678,6 +20679,41 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
20678
20679
  ]
20679
20680
  }
20680
20681
  },
20682
+ {
20683
+ resource: "media.libraries",
20684
+ method: "retrieveDefault",
20685
+ summary: "Get default library",
20686
+ description: "Return this organization’s default library. Calling ensures the organization’s default library exists (ADR-093): the first call creates it and later calls return the same library, so this is the method to call before writing when no library id is known. Generated and edited media land here when no library is named. The path segment {lib} accepts the literal default, which resolves to this library before the credential check — so an agent that has never listed libraries can still write to the right place. Returns the same Library object as libraries.retrieve; a credential bound to one library reaches this only when that binding covers the default library.",
20687
+ http: "GET",
20688
+ path: "/media/v1/libraries/default",
20689
+ streaming: "no",
20690
+ pagination: false,
20691
+ pathParams: [],
20692
+ query: []
20693
+ },
20694
+ {
20695
+ resource: "media.libraries",
20696
+ method: "setDefault",
20697
+ summary: "Set default library",
20698
+ description: "Point this organization’s default library at an existing library. Calling ensures the organization’s default library exists (ADR-093): the path is resolved before the credential check, so a first call creates the default library when there is none and then repoints it. The path segment {lib} accepts the literal default, which resolves to this library before the credential check. Supply library_id from library creation or listing; the library must be active and belong to the organization. This changes where library-less generation and uploads land across the whole organization, so it affects other callers as well as this one. It does not move or copy any asset — assets already in the previous default library stay there. Returns the library now set as the default. Deleting the default library is refused with LIBRARY_IS_DEFAULT until another library is made the default.",
20699
+ http: "PUT",
20700
+ path: "/media/v1/libraries/default",
20701
+ streaming: "no",
20702
+ pagination: false,
20703
+ pathParams: [],
20704
+ query: [],
20705
+ body: {
20706
+ required: true,
20707
+ fields: [
20708
+ {
20709
+ name: "library_id",
20710
+ type: "string",
20711
+ required: true,
20712
+ description: "Identifier of a library belonging to the caller."
20713
+ }
20714
+ ]
20715
+ }
20716
+ },
20681
20717
  {
20682
20718
  resource: "media.libraries",
20683
20719
  method: "delete",
@@ -20802,6 +20838,25 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
20802
20838
  required: false,
20803
20839
  description: "image, video (including audio), raw; auto is accepted by Upload actions only, and listing with auto returns 400."
20804
20840
  },
20841
+ {
20842
+ name: "material_type",
20843
+ type: "string",
20844
+ enum: [
20845
+ "image",
20846
+ "video",
20847
+ "audio",
20848
+ "voice",
20849
+ "sticker",
20850
+ "font",
20851
+ "text_style",
20852
+ "text_template",
20853
+ "animation_preset",
20854
+ "lut",
20855
+ "transition_map"
20856
+ ],
20857
+ required: false,
20858
+ description: "Filter assets to one kind of material, independent of the stored resource_type. Omit to list every material type. Assets stored before this field existed match no material_type filter."
20859
+ },
20805
20860
  {
20806
20861
  name: "cursor",
20807
20862
  type: "string",
@@ -21162,6 +21217,68 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
21162
21217
  ]
21163
21218
  }
21164
21219
  },
21220
+ {
21221
+ resource: "media.assets",
21222
+ method: "edit",
21223
+ summary: "Edit asset",
21224
+ description: "Edit an existing asset and store the result as a new asset. Use library_id from creation or listing and asset_id from asset creation or listing; library_id also accepts the literal default, which resolves to the organization’s default library before the credential check. The source asset is never overwritten: the new asset hangs under it in the edit chain, records it in derived_from, and reads back with assets.lineage, so earlier steps stay reachable. The body is operation plus the optional model, asset_folder, understanding and idempotency_key; operation.type selects the edit and carries that operation’s own fields. This release performs variations, inpaint, erase, replace_object, recolor, remove_background and replace_background on images; every other type in the operation vocabulary — the video and audio edits — is refused with OPERATION_NOT_SUPPORTED. inpaint takes mask, a PNG File identifier beginning with file- whose transparent area marks the region to replace, plus the prompt describing what belongs there. Aspects beyond the source asset’s material type return REFERENCE_TYPE_MISMATCH. Editing is charged through Router and the job records the charge in usage. The response is 202 with a queued Job whose type is image, whose operation is the edit applied, and whose source_asset_id is the asset edited; poll GET /media/v1/libraries/{library_id}/jobs/{job_id} until it is completed or failed, then read the produced asset. Example: POST /media/v1/libraries/lib_example/assets/9dfa312ef9bc4b00816339b598b1152c/edits with {\"operation\":{\"type\":\"variations\",\"strength\":\"subtle\"}}.",
21225
+ http: "POST",
21226
+ path: "/media/v1/libraries/{library_id}/assets/{asset_id}/edits",
21227
+ streaming: "no",
21228
+ pagination: false,
21229
+ pathParams: [
21230
+ {
21231
+ name: "library_id",
21232
+ sdkName: "library_id",
21233
+ description: "Library ID returned by creation."
21234
+ },
21235
+ {
21236
+ name: "asset_id",
21237
+ sdkName: "asset_id",
21238
+ description: "32-character asset ID."
21239
+ }
21240
+ ],
21241
+ query: [],
21242
+ body: {
21243
+ required: true,
21244
+ fields: [
21245
+ {
21246
+ name: "operation",
21247
+ type: "object",
21248
+ required: true,
21249
+ description: "One edit to apply to the source asset. type selects the operation and the discriminating branch carries that operation’s fields. This release performs variations, inpaint, erase, replace_object, recolor, remove_background and replace_background on images; every other type here describes the operation vocabulary and is refused with OPERATION_NOT_SUPPORTED."
21250
+ },
21251
+ {
21252
+ name: "model",
21253
+ type: "string",
21254
+ required: false,
21255
+ description: "Router model that performs the edit; omit it to use the library default image model."
21256
+ },
21257
+ {
21258
+ name: "asset_folder",
21259
+ type: "string",
21260
+ required: false,
21261
+ description: "Folder the produced asset is filed under; defaults to the source asset’s folder. New path segments containing U+FFFD or consisting only of question marks are rejected with INVALID_PARAMS; send UTF-8 names. Existing affected folders remain readable and assets can be moved out."
21262
+ },
21263
+ {
21264
+ name: "understanding",
21265
+ type: "string",
21266
+ enum: [
21267
+ "auto",
21268
+ "skip"
21269
+ ],
21270
+ required: false,
21271
+ description: "Understanding behavior for the produced asset; defaults to auto."
21272
+ },
21273
+ {
21274
+ name: "idempotency_key",
21275
+ type: "string",
21276
+ required: false,
21277
+ description: "Stable key so a retried request reuses the same job instead of editing and charging again; reusing it with different content is rejected."
21278
+ }
21279
+ ]
21280
+ }
21281
+ },
21165
21282
  {
21166
21283
  resource: "media.libraries.assets.frames",
21167
21284
  method: "create",
@@ -21208,6 +21325,29 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
21208
21325
  ]
21209
21326
  }
21210
21327
  },
21328
+ {
21329
+ resource: "media.assets",
21330
+ method: "lineage",
21331
+ summary: "Get asset lineage",
21332
+ description: "Read the whole edit tree containing one asset, so a caller sees what it was edited from and what was edited from it. Use library_id from creation or listing and asset_id from asset creation or listing; library_id also accepts the literal default, which resolves to the organization’s default library before the credential check. The response names the root the tree descends from, the asset asked about, and every step between them, each with the operation, prompt and creation time that produced it. Deleted assets stay in the tree, marked deleted, so the chain stays connected after cleanup. This is a read: it starts no processing and changes no asset. Example: GET /media/v1/libraries/lib_example/assets/9dfa312ef9bc4b00816339b598b1152c/lineage.",
21333
+ http: "GET",
21334
+ path: "/media/v1/libraries/{library_id}/assets/{asset_id}/lineage",
21335
+ streaming: "no",
21336
+ pagination: false,
21337
+ pathParams: [
21338
+ {
21339
+ name: "library_id",
21340
+ sdkName: "library_id",
21341
+ description: "Library ID returned by creation."
21342
+ },
21343
+ {
21344
+ name: "asset_id",
21345
+ sdkName: "asset_id",
21346
+ description: "32-character asset ID."
21347
+ }
21348
+ ],
21349
+ query: []
21350
+ },
21211
21351
  {
21212
21352
  resource: "media.libraries.assets.reprocess",
21213
21353
  method: "create",
@@ -21609,6 +21749,126 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
21609
21749
  ]
21610
21750
  }
21611
21751
  },
21752
+ {
21753
+ resource: "media.images",
21754
+ method: "generate",
21755
+ summary: "Generate image",
21756
+ description: "Generate one or more images from a text prompt and store them straight into the library. Use library_id from creation or listing; the path segment {library_id} also accepts the literal default, which resolves to the organization’s default library before the credential check, so an agent that has never listed a library can still generate. The request body is the image request itself: prompt is required, and n, size, background, output_format, output, references, seed, model, asset_folder and understanding are optional. Set output to sticker for a cut-out with a transparent background. references attach existing assets with a role — edit_target, style, structure or subject — and a model that cannot honour a role returns REFERENCE_TYPE_MISMATCH. Aspect ratio is not accepted for images; name size instead. Generation is charged through Router and the job records the charge in usage; nothing is charged for a request refused before it starts. The response is 202 with a queued Job whose type is image and whose operation is generate; poll GET /media/v1/libraries/{library_id}/jobs/{job_id} until its status is completed or failed, then read the produced assets from the library. Send Idempotency-Key, or idempotency_key in the body, to retry without generating and charging twice. Example: POST /media/v1/libraries/default/images/generations with {\"prompt\":\"A red kite above a calm sea at sunrise\",\"n\":1,\"output\":\"sticker\"}.",
21757
+ http: "POST",
21758
+ path: "/media/v1/libraries/{library_id}/images/generations",
21759
+ streaming: "no",
21760
+ pagination: false,
21761
+ pathParams: [
21762
+ {
21763
+ name: "library_id",
21764
+ sdkName: "library_id",
21765
+ description: "Library ID returned by creation."
21766
+ }
21767
+ ],
21768
+ query: [],
21769
+ body: {
21770
+ required: true,
21771
+ fields: [
21772
+ {
21773
+ name: "prompt",
21774
+ type: "string",
21775
+ required: true,
21776
+ description: "Text prompt describing the image to generate; Router forwards it to the image model unchanged."
21777
+ },
21778
+ {
21779
+ name: "negative_prompt",
21780
+ type: "string",
21781
+ required: false,
21782
+ description: "What the image must not contain. Models without a negative-prompt control ignore it."
21783
+ },
21784
+ {
21785
+ name: "n",
21786
+ type: "integer",
21787
+ required: false,
21788
+ description: "Images to generate in one job, from 1 to 10; defaults to 1. Each produced image is charged separately."
21789
+ },
21790
+ {
21791
+ name: "size",
21792
+ type: "string",
21793
+ required: false,
21794
+ description: "Requested pixel size written as width x height. Router validates it against the chosen model and rejects an unsupported size with INVALID_PARAMS."
21795
+ },
21796
+ {
21797
+ name: "background",
21798
+ type: "string",
21799
+ enum: [
21800
+ "transparent",
21801
+ "opaque",
21802
+ "auto"
21803
+ ],
21804
+ required: false,
21805
+ description: "Background handling; defaults to auto. Whether transparency is honoured depends on the model."
21806
+ },
21807
+ {
21808
+ name: "output_format",
21809
+ type: "string",
21810
+ enum: [
21811
+ "png",
21812
+ "jpeg",
21813
+ "webp"
21814
+ ],
21815
+ required: false,
21816
+ description: "Encoding of the stored image; defaults to png. Transparency requires png or webp."
21817
+ },
21818
+ {
21819
+ name: "output",
21820
+ type: "string",
21821
+ enum: [
21822
+ "image",
21823
+ "sticker"
21824
+ ],
21825
+ required: false,
21826
+ description: "How the result is stored: image for a normal picture, or sticker for a cut-out committed with material_type sticker; defaults to image."
21827
+ },
21828
+ {
21829
+ name: "references",
21830
+ type: "array",
21831
+ itemType: "object",
21832
+ required: false,
21833
+ description: "Existing assets the model may use, each with the role it plays. Router answers REFERENCE_TYPE_MISMATCH when the chosen model cannot honour a role."
21834
+ },
21835
+ {
21836
+ name: "seed",
21837
+ type: "integer",
21838
+ required: false,
21839
+ description: "Seed for reproducible sampling; omit it to let the model choose one."
21840
+ },
21841
+ {
21842
+ name: "model",
21843
+ type: "string",
21844
+ required: false,
21845
+ description: "Router model with image-generation capability; omit it to use the library default image model."
21846
+ },
21847
+ {
21848
+ name: "asset_folder",
21849
+ type: "string",
21850
+ required: false,
21851
+ description: "Folder the produced asset is filed under; defaults to the library root. New path segments containing U+FFFD or consisting only of question marks are rejected with INVALID_PARAMS; send UTF-8 names. Existing affected folders remain readable and assets can be moved out."
21852
+ },
21853
+ {
21854
+ name: "understanding",
21855
+ type: "string",
21856
+ enum: [
21857
+ "auto",
21858
+ "skip"
21859
+ ],
21860
+ required: false,
21861
+ description: "Understanding behavior for the produced asset; defaults to auto."
21862
+ },
21863
+ {
21864
+ name: "idempotency_key",
21865
+ type: "string",
21866
+ required: false,
21867
+ description: "Stable key so a retried request reuses the same job instead of generating and charging again; reusing it with different content is rejected."
21868
+ }
21869
+ ]
21870
+ }
21871
+ },
21612
21872
  {
21613
21873
  resource: "media.libraries.jobs",
21614
21874
  method: "list",
@@ -21631,11 +21891,13 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
21631
21891
  type: "string",
21632
21892
  enum: [
21633
21893
  "queued",
21894
+ "in_progress",
21634
21895
  "running",
21635
21896
  "completed",
21636
21897
  "completed_with_errors",
21637
21898
  "failed",
21638
- "cancelled"
21899
+ "cancelled",
21900
+ "canceled"
21639
21901
  ],
21640
21902
  required: false,
21641
21903
  description: "Filter jobs by their current status."
@@ -21834,7 +22096,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
21834
22096
  name: "top_k",
21835
22097
  type: "integer",
21836
22098
  required: false,
21837
- description: "Maximum search hits, from 1 to 50; defaults to 20."
22099
+ description: "Maximum search hits, from 1 to 50; defaults to 20. top_k takes effect and bounds how many distinct hits come back, counting collapsed duplicates as one hit."
21838
22100
  },
21839
22101
  {
21840
22102
  name: "mode",
@@ -21845,6 +22107,25 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
21845
22107
  ],
21846
22108
  required: false,
21847
22109
  description: "Ranking mode: hybrid combines semantic and keyword matches; semantic uses vector similarity only. Defaults to hybrid."
22110
+ },
22111
+ {
22112
+ name: "material_type",
22113
+ type: "string",
22114
+ enum: [
22115
+ "image",
22116
+ "video",
22117
+ "audio",
22118
+ "voice",
22119
+ "sticker",
22120
+ "font",
22121
+ "text_style",
22122
+ "text_template",
22123
+ "animation_preset",
22124
+ "lut",
22125
+ "transition_map"
22126
+ ],
22127
+ required: false,
22128
+ description: "What this asset is as a reusable material, as opposed to resource_type (its stored file category). Omitted on assets stored before this field existed and on raw assets that are not materials."
21848
22129
  }
21849
22130
  ]
21850
22131
  }
@@ -21957,7 +22238,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
21957
22238
  name: "top_k",
21958
22239
  type: "integer",
21959
22240
  required: false,
21960
- description: "Maximum search hits, from 1 to 50; defaults to 20."
22241
+ description: "Maximum search hits, from 1 to 50; defaults to 20. top_k takes effect and bounds how many distinct hits come back, counting collapsed duplicates as one hit."
21961
22242
  },
21962
22243
  {
21963
22244
  name: "mode",
@@ -21968,6 +22249,25 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
21968
22249
  ],
21969
22250
  required: false,
21970
22251
  description: "Ranking mode: hybrid combines semantic and keyword matches; semantic uses vector similarity only. Defaults to hybrid."
22252
+ },
22253
+ {
22254
+ name: "material_type",
22255
+ type: "string",
22256
+ enum: [
22257
+ "image",
22258
+ "video",
22259
+ "audio",
22260
+ "voice",
22261
+ "sticker",
22262
+ "font",
22263
+ "text_style",
22264
+ "text_template",
22265
+ "animation_preset",
22266
+ "lut",
22267
+ "transition_map"
22268
+ ],
22269
+ required: false,
22270
+ description: "What this asset is as a reusable material, as opposed to resource_type (its stored file category). Omitted on assets stored before this field existed and on raw assets that are not materials."
21971
22271
  }
21972
22272
  ]
21973
22273
  }
@@ -24652,7 +24952,7 @@ for more details.`
24652
24952
  resource: "ontology.nodes",
24653
24953
  method: "create",
24654
24954
  summary: "Create node",
24655
- description: "Record one entity in the graph, for a system mirroring a record it owns. type must already be registered and ref, when given, must match that type's ref_prefix. Send an Idempotency-Key header; repeating the same key with the same content returns the first result instead of creating a second node. This writes structure only — to give an agent something to remember, use POST /agent/v1/agents/{agent_id}/consolidations.",
24955
+ description: "Record one entity in the graph, for a system mirroring a record it owns. type must already be registered and ref, when given, must match that type's ref_prefix. Send an Idempotency-Key header; repeating the same key with the same content returns the first result instead of creating a second node. This writes structure only; it does not give any agent a memory.",
24656
24956
  http: "POST",
24657
24957
  path: "/ontology/v1/nodes",
24658
24958
  streaming: "no",
@@ -24807,6 +25107,60 @@ for more details.`
24807
25107
  ]
24808
25108
  }
24809
25109
  },
25110
+ {
25111
+ resource: "ontology.nodes",
25112
+ method: "retrieveNeighborhood",
25113
+ summary: "Retrieve neighborhood",
25114
+ description: "Load the subgraph around one node instead of the whole graph — the read to use when a screen or an agent needs the context of one entity. Returns the start node, every node within depth hops of it, the relations whose both ends are in that set, and truncated true when the node limit cut the walk short. direction chooses which way relations are followed; as_of and include_invalid read the graph as those parameters do elsewhere. Visibility is exactly nodes.retrieve's — a node you may reach but not read comes back restricted with its name only, and relations touching it are withheld, so this read never reaches further than a node read does. The node id comes from nodes.list, nodes.create or a changeset; an unknown one answers ONTOLOGY_NODE_NOT_FOUND, the same answer nodes.retrieve gives.",
25115
+ http: "GET",
25116
+ path: "/ontology/v1/nodes/{node_id}/neighborhood",
25117
+ streaming: "no",
25118
+ pagination: false,
25119
+ pathParams: [
25120
+ {
25121
+ name: "node_id",
25122
+ sdkName: "node_id",
25123
+ description: "Node id returned by nodes.list, nodes.create or a changeset, in the form ond_ followed by 32 lowercase letters or digits; a name or an external record id is not accepted."
25124
+ }
25125
+ ],
25126
+ query: [
25127
+ {
25128
+ name: "depth",
25129
+ type: "integer",
25130
+ required: false,
25131
+ description: "How many hops from the given node to walk, 1 to 3; defaults to 1. A value outside that range is refused 400 rather than clamped, so the answer is never a smaller graph than the one asked for."
25132
+ },
25133
+ {
25134
+ name: "limit",
25135
+ type: "integer",
25136
+ required: false,
25137
+ description: "Maximum nodes to return, 1 to 500; defaults to 200. When the walk reaches this many nodes it stops and reports truncated true, so treat a truncated answer as a sample of the neighborhood rather than all of it. This bound is not the list routes' page size, and there is no cursor to resume from."
25138
+ },
25139
+ {
25140
+ name: "direction",
25141
+ type: "string",
25142
+ enum: [
25143
+ "out",
25144
+ "in",
25145
+ "both"
25146
+ ],
25147
+ required: false,
25148
+ description: "Which way to follow relations from each node walked; out follows relations the node is the source of, in follows those it is the target of, both follows either. Defaults to both. Relations between two returned nodes are included whichever direction brought the second node in."
25149
+ },
25150
+ {
25151
+ name: "as_of",
25152
+ type: "string",
25153
+ required: false,
25154
+ description: "ISO 8601 timestamp; walk the graph as it was then — a node recorded later is absent and a relation invalidated since still counts. Omit to read current state."
25155
+ },
25156
+ {
25157
+ name: "include_invalid",
25158
+ type: "boolean",
25159
+ required: false,
25160
+ description: "Set true to walk relations whose invalid_at has passed, which is how a fact that stopped being true stays reachable. Omit or false to walk currently valid relations only."
25161
+ }
25162
+ ]
25163
+ },
24810
25164
  {
24811
25165
  resource: "ontology.relations",
24812
25166
  method: "list",
@@ -24872,7 +25226,7 @@ for more details.`
24872
25226
  resource: "ontology.relations",
24873
25227
  method: "create",
24874
25228
  summary: "Create relation",
24875
- description: "Record one fact between two existing nodes, for a system mirroring a relationship it owns. type must be registered and must admit these endpoints; fact states the relationship in one sentence. Send an Idempotency-Key header; repeating the same key returns the first result instead of writing a second relation. This writes structure only — to give an agent something to remember, use POST /agent/v1/agents/{agent_id}/consolidations.",
25229
+ description: "Record one fact between two existing nodes, for a system mirroring a relationship it owns. type must be registered and must admit these endpoints; fact states the relationship in one sentence. Send an Idempotency-Key header; repeating the same key returns the first result instead of writing a second relation. This writes structure only; it does not give any agent a memory.",
24876
25230
  http: "POST",
24877
25231
  path: "/ontology/v1/relations",
24878
25232
  streaming: "no",
@@ -24984,7 +25338,7 @@ for more details.`
24984
25338
  resource: "ontology.search",
24985
25339
  method: "create",
24986
25340
  summary: "Search nodes",
24987
- description: "Resolve text to the nodes it most likely names, when a mirror holds a name and needs the node id it corresponds to. Results are ranked candidates, not an answer, each reporting whether the match came from the node's name, an alias, its description or a relation's fact. Narrow with types, and cap the result count with limit (1–50, default 20). This reads structure; it is not an agent recall — agents recall through POST /agent/v1/agents/{agent_id}/consolidations.",
25341
+ description: "Resolve text to the nodes it most likely names, when a mirror holds a name and needs the node id it corresponds to. Results are ranked candidates, not an answer, each reporting whether the match came from the node's name, an alias, its description or a relation's fact. Narrow with types, and cap the result count with limit (1–50, default 20). This reads structure; it is not an agent's recall, which reads the graph from that agent's own viewpoint inside its sessions.",
24988
25342
  http: "POST",
24989
25343
  path: "/ontology/v1/search",
24990
25344
  streaming: "no",
@@ -27658,7 +28012,7 @@ for more details.`
27658
28012
  required: true,
27659
28013
  fields: [
27660
28014
  {
27661
- name: "updateMask",
28015
+ name: "update_mask",
27662
28016
  type: "array",
27663
28017
  itemType: "string",
27664
28018
  required: true,
@@ -27901,7 +28255,7 @@ for more details.`
27901
28255
  required: true,
27902
28256
  fields: [
27903
28257
  {
27904
- name: "updateMask",
28258
+ name: "update_mask",
27905
28259
  type: "array",
27906
28260
  itemType: "string",
27907
28261
  required: true,
@@ -28212,7 +28566,7 @@ for more details.`
28212
28566
  required: true,
28213
28567
  fields: [
28214
28568
  {
28215
- name: "updateMask",
28569
+ name: "update_mask",
28216
28570
  type: "array",
28217
28571
  itemType: "string",
28218
28572
  required: true,
@@ -28373,7 +28727,7 @@ for more details.`
28373
28727
  resource: "studio.themes",
28374
28728
  method: "list",
28375
28729
  summary: "List the rendition themes of a platform",
28376
- description: "List themes: the layouts a rendition is produced with, for one platform or for all of them. Pass a platform to see only the themes that platform can use. A theme decides the page or card a rendition is built into, so read the chosen theme before creating a rendition rather than after the output looks wrong.",
28730
+ description: "List themes: the layouts a rendition is produced with, for one platform or for all of them. Pass a platform to see only the themes that platform can use. The first page starts with the built-in themes (builtin true, such as warm-card@1 for Xiaohongshu cards and plain-mono@1 for WeChat articles), which every organization can use and nobody can change or delete; your organization's own themes follow. A theme decides the page or card a rendition is built into, so read the chosen theme before creating a rendition rather than after the output looks wrong.",
28377
28731
  http: "GET",
28378
28732
  path: "/studio/v1/themes",
28379
28733
  streaming: "no",
@@ -28522,7 +28876,7 @@ for more details.`
28522
28876
  required: true,
28523
28877
  fields: [
28524
28878
  {
28525
- name: "updateMask",
28879
+ name: "update_mask",
28526
28880
  type: "array",
28527
28881
  itemType: "string",
28528
28882
  required: true,
@@ -28662,7 +29016,7 @@ for more details.`
28662
29016
  description: "Caller-chosen key and value pairs kept on a resource; the keys are the caller's own names and no platform meaning is attached to them."
28663
29017
  },
28664
29018
  {
28665
- name: "requestId",
29019
+ name: "request_id",
28666
29020
  type: "string",
28667
29021
  required: false,
28668
29022
  description: "Caller-chosen key that makes this create safe to repeat: the same value answers the first result instead of creating a second work."
@@ -28735,14 +29089,14 @@ for more details.`
28735
29089
  required: true,
28736
29090
  fields: [
28737
29091
  {
28738
- name: "updateMask",
29092
+ name: "update_mask",
28739
29093
  type: "array",
28740
29094
  itemType: "string",
28741
29095
  required: true,
28742
29096
  description: "Field paths this call changes, spelled as they appear in the work, such as title or goal.message; a field left out keeps its value."
28743
29097
  },
28744
29098
  {
28745
- name: "expectedRevision",
29099
+ name: "expected_revision",
28746
29100
  type: "integer",
28747
29101
  required: false,
28748
29102
  description: "Work revision the caller read; when the work moved past it the write is refused with REVISION_CONFLICT and nothing changes."
@@ -28814,7 +29168,7 @@ for more details.`
28814
29168
  required: true,
28815
29169
  fields: [
28816
29170
  {
28817
- name: "expectedRevision",
29171
+ name: "expected_revision",
28818
29172
  type: "integer",
28819
29173
  required: false,
28820
29174
  description: "Brief revision the caller read; a mismatch is refused with REVISION_CONFLICT rather than merged."
@@ -28833,21 +29187,21 @@ for more details.`
28833
29187
  description: "Source files to keep with the brief, added to the ones already attached."
28834
29188
  },
28835
29189
  {
28836
- name: "addPoints",
29190
+ name: "add_points",
28837
29191
  type: "array",
28838
- itemType: "string",
29192
+ itemType: "object",
28839
29193
  required: false,
28840
- description: "New requirement points to split out of the brief; each receives the next free key in order."
29194
+ description: "New requirement points to split out of the brief; each receives the next free key in order. A plain string is a unit point; pass { text, scope: work } for a constraint on the whole piece (period, voice, point of view, cast, words to avoid)."
28841
29195
  },
28842
29196
  {
28843
- name: "editPoints",
29197
+ name: "edit_points",
28844
29198
  type: "array",
28845
29199
  itemType: "object",
28846
29200
  required: false,
28847
29201
  description: "Existing points to reword, each naming the key it keeps and the text that replaces it."
28848
29202
  },
28849
29203
  {
28850
- name: "removePoints",
29204
+ name: "remove_points",
28851
29205
  type: "array",
28852
29206
  itemType: "string",
28853
29207
  required: false,
@@ -28930,7 +29284,7 @@ for more details.`
28930
29284
  description: "Unit tree to create the draft with, given by the caller instead of a template; children nest, and a unit without a kind takes the genre default for its position."
28931
29285
  },
28932
29286
  {
28933
- name: "derivedFrom",
29287
+ name: "derived_from",
28934
29288
  type: "object",
28935
29289
  required: false,
28936
29290
  description: "What the new draft should be derived from, so the service can record the source revision for later staleness checks."
@@ -28942,7 +29296,7 @@ for more details.`
28942
29296
  description: "Initial values for the genre properties, keyed by property key; a value the genre does not define is refused rather than stored."
28943
29297
  },
28944
29298
  {
28945
- name: "requestId",
29299
+ name: "request_id",
28946
29300
  type: "string",
28947
29301
  required: false,
28948
29302
  description: "Caller-chosen key that makes this create safe to repeat: the same value answers the first draft instead of creating a second one."
@@ -29011,14 +29365,14 @@ for more details.`
29011
29365
  required: true,
29012
29366
  fields: [
29013
29367
  {
29014
- name: "updateMask",
29368
+ name: "update_mask",
29015
29369
  type: "array",
29016
29370
  itemType: "string",
29017
29371
  required: true,
29018
29372
  description: "Field paths this call changes, such as title, key or props.topics; a field left out keeps its value."
29019
29373
  },
29020
29374
  {
29021
- name: "expectedRevision",
29375
+ name: "expected_revision",
29022
29376
  type: "integer",
29023
29377
  required: false,
29024
29378
  description: "Draft revision the caller read; a mismatch is refused with REVISION_CONFLICT and nothing changes. Omit it only for structure calls that genuinely do not depend on the current state."
@@ -29117,6 +29471,64 @@ for more details.`
29117
29471
  ],
29118
29472
  query: []
29119
29473
  },
29474
+ {
29475
+ resource: "studio.works.drafts.renditions",
29476
+ method: "create",
29477
+ summary: "Create a rendition of a draft for a platform",
29478
+ description: "Create a rendition: the form of one draft that a platform receives, such as a Xiaohongshu card set, a DOCX file or a Markdown file. Read the platform first with the platform call and pass its versioned key; pass a theme only to override the platform's default layout. Pass render true to render in the same call and read render_state and issues in the answer; without it the rendition starts as pending and the render call produces it. Rendering a Xiaohongshu card set is billed by Browser Rendering time (meter browser_ms, product studio-render); DOCX and Markdown renditions are not billed. A draft with no body renders as invalid with a draft_empty issue, and an unavailable render service leaves render_state failed with a render_unavailable issue, so repeat the render call later. Send a request_id to make a repeated call return the first rendition instead of creating another. Next, publish the rendition to export it.",
29479
+ http: "POST",
29480
+ path: "/studio/v1/works/{work}/drafts/{draft}/renditions",
29481
+ streaming: "no",
29482
+ pagination: false,
29483
+ pathParams: [
29484
+ {
29485
+ name: "work",
29486
+ sdkName: "work",
29487
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29488
+ },
29489
+ {
29490
+ name: "draft",
29491
+ sdkName: "draft",
29492
+ description: "Draft being addressed, either its in-work key such as novel or its drf_ identifier; a key renamed earlier still resolves through its previous value."
29493
+ }
29494
+ ],
29495
+ query: [],
29496
+ body: {
29497
+ required: true,
29498
+ fields: [
29499
+ {
29500
+ name: "platform",
29501
+ type: "string",
29502
+ required: true,
29503
+ description: "Versioned platform key from the platform list. Export platforms today are markdown@1, docx@1 and xiaohongshu@1; a platform that only publishes to an account answers PLATFORM_NOT_AVAILABLE."
29504
+ },
29505
+ {
29506
+ name: "theme",
29507
+ type: "string",
29508
+ required: false,
29509
+ description: "Theme to render with, a thm_ identifier or a built-in key from the theme list; omit it to use the platform default."
29510
+ },
29511
+ {
29512
+ name: "settings",
29513
+ type: "object",
29514
+ required: false,
29515
+ description: "Per-rendition settings; each platform reads only the settings that apply to it and ignores the rest."
29516
+ },
29517
+ {
29518
+ name: "render",
29519
+ type: "boolean",
29520
+ required: false,
29521
+ description: "Whether to render in the same call. True returns a rendition that is already rendered, invalid or failed; false or omitted returns it pending, to be rendered by the render operation."
29522
+ },
29523
+ {
29524
+ name: "request_id",
29525
+ type: "string",
29526
+ required: false,
29527
+ description: "Caller-chosen key that makes a repeated create return the first rendition instead of making another; use a new value for each distinct rendition."
29528
+ }
29529
+ ]
29530
+ }
29531
+ },
29120
29532
  {
29121
29533
  resource: "studio.works.drafts",
29122
29534
  method: "retrieveReview",
@@ -29362,7 +29774,7 @@ for more details.`
29362
29774
  required: false,
29363
29775
  fields: [
29364
29776
  {
29365
- name: "expectedRevision",
29777
+ name: "expected_revision",
29366
29778
  type: "integer",
29367
29779
  required: false,
29368
29780
  description: "Draft revision the caller read; a mismatch is refused rather than confirming a draft that changed under the caller."
@@ -29370,6 +29782,212 @@ for more details.`
29370
29782
  ]
29371
29783
  }
29372
29784
  },
29785
+ {
29786
+ resource: "studio.works.renditions",
29787
+ method: "list",
29788
+ summary: "List the renditions of a work",
29789
+ description: "List the renditions of one work, each with its platform, render state, stale flag and publish state. Pass draft to see only the renditions of one draft. Use it to find the rendition to publish or to render again, and read stale before exporting: a stale rendition was built from an older draft and cannot be exported until the render call has rebuilt it. The answer is one page; keep following next_page_token while it is present.",
29790
+ http: "GET",
29791
+ path: "/studio/v1/works/{work}/renditions",
29792
+ streaming: "no",
29793
+ pagination: false,
29794
+ pathParams: [
29795
+ {
29796
+ name: "work",
29797
+ sdkName: "work",
29798
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29799
+ }
29800
+ ],
29801
+ query: [
29802
+ {
29803
+ name: "draft",
29804
+ type: "string",
29805
+ required: false,
29806
+ description: "Draft key such as novel or its drf_ identifier; when given, only the renditions of that draft are returned. Omit it to list the renditions of every draft in the work."
29807
+ },
29808
+ {
29809
+ name: "page_size",
29810
+ type: "integer",
29811
+ required: false,
29812
+ description: "How many items this page returns, 1 to 100; omitted uses the service default. Treat the answer as one page, not the whole set, and keep following next_page_token while it is present."
29813
+ },
29814
+ {
29815
+ name: "page_token",
29816
+ type: "string",
29817
+ required: false,
29818
+ description: "Cursor from the previous answer's next_page_token; it is opaque, so pass it back unchanged and never build one from an id or an offset."
29819
+ }
29820
+ ]
29821
+ },
29822
+ {
29823
+ resource: "studio.works.renditions",
29824
+ method: "delete",
29825
+ summary: "Delete a rendition",
29826
+ description: "Delete a rendition and stop listing it. The draft it was built from is untouched, and a new rendition can be created from it at any time. Files already downloaded from an earlier export are not affected. Use it to clear a failed or abandoned rendition; to refresh one, call the render operation instead.",
29827
+ http: "DELETE",
29828
+ path: "/studio/v1/works/{work}/renditions/{rendition}",
29829
+ streaming: "no",
29830
+ pagination: false,
29831
+ pathParams: [
29832
+ {
29833
+ name: "work",
29834
+ sdkName: "work",
29835
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29836
+ },
29837
+ {
29838
+ name: "rendition",
29839
+ sdkName: "rendition",
29840
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29841
+ }
29842
+ ],
29843
+ query: []
29844
+ },
29845
+ {
29846
+ resource: "studio.works.renditions",
29847
+ method: "retrieve",
29848
+ summary: "Read one rendition",
29849
+ description: "Read one rendition in full: its render state, the validation issues the render found, the parts (one per card page or thread post), the files it produced and its publish state. Call it after create, render or publish to see the outcome, because a render that finished invalid or failed is reported here and not as an HTTP error. stale is true when the draft has changed since source_revision; call the render operation before exporting a stale rendition.",
29850
+ http: "GET",
29851
+ path: "/studio/v1/works/{work}/renditions/{rendition}",
29852
+ streaming: "no",
29853
+ pagination: false,
29854
+ pathParams: [
29855
+ {
29856
+ name: "work",
29857
+ sdkName: "work",
29858
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29859
+ },
29860
+ {
29861
+ name: "rendition",
29862
+ sdkName: "rendition",
29863
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29864
+ }
29865
+ ],
29866
+ query: []
29867
+ },
29868
+ {
29869
+ resource: "studio.works.renditions",
29870
+ method: "update",
29871
+ summary: "Change the theme or settings of a rendition",
29872
+ description: "Change a rendition's theme or settings. Send update_mask naming exactly the fields you change, such as theme or settings; a field left out keeps its value. The produced files are not rebuilt by this call, so call the render operation afterwards to apply the change. A rendition whose export or publish has started is locked and answers RENDITION_PUBLISH_LOCKED; create a new rendition for new content.",
29873
+ http: "PATCH",
29874
+ path: "/studio/v1/works/{work}/renditions/{rendition}",
29875
+ streaming: "no",
29876
+ pagination: false,
29877
+ pathParams: [
29878
+ {
29879
+ name: "work",
29880
+ sdkName: "work",
29881
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29882
+ },
29883
+ {
29884
+ name: "rendition",
29885
+ sdkName: "rendition",
29886
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29887
+ }
29888
+ ],
29889
+ query: [],
29890
+ body: {
29891
+ required: true,
29892
+ fields: [
29893
+ {
29894
+ name: "update_mask",
29895
+ type: "array",
29896
+ itemType: "string",
29897
+ required: true,
29898
+ description: "Field paths this call changes: theme, settings or both; a field left out keeps its value."
29899
+ },
29900
+ {
29901
+ name: "theme",
29902
+ type: "string",
29903
+ required: false,
29904
+ description: "New theme, a thm_ identifier or a built-in key, used when theme is named in the update mask; render again to apply it."
29905
+ },
29906
+ {
29907
+ name: "settings",
29908
+ type: "object",
29909
+ required: false,
29910
+ description: "Per-rendition settings; each platform reads only the settings that apply to it and ignores the rest."
29911
+ }
29912
+ ]
29913
+ }
29914
+ },
29915
+ {
29916
+ resource: "studio.works.renditions",
29917
+ method: "retrieveContent",
29918
+ summary: "Get a download URL for a rendition file",
29919
+ description: "Get a signed, short-lived URL to download what a rendition produced. Without part it points to the rendition's own first file: the ZIP of pages for a card rendition, the DOCX for docx@1. With part it points to that part's first file, such as one card PNG; a part that has no file, or a rendition not rendered yet, answers RENDITION_NOT_RENDERED, and an index no part has answers INVALID_PARAMS. Call it after a successful render or export, download the url before expire_time, and call again for a fresh one when it has expired. The URL is a credential: do not store or share it.",
29920
+ http: "GET",
29921
+ path: "/studio/v1/works/{work}/renditions/{rendition}/content",
29922
+ streaming: "no",
29923
+ pagination: false,
29924
+ pathParams: [
29925
+ {
29926
+ name: "work",
29927
+ sdkName: "work",
29928
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29929
+ },
29930
+ {
29931
+ name: "rendition",
29932
+ sdkName: "rendition",
29933
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29934
+ }
29935
+ ],
29936
+ query: [
29937
+ {
29938
+ name: "part",
29939
+ type: "integer",
29940
+ required: false,
29941
+ description: "Index of the part to download, the index value of an entry in the rendition's parts list; omit it to get the rendition's own first file."
29942
+ }
29943
+ ]
29944
+ },
29945
+ {
29946
+ resource: "studio.works.renditions",
29947
+ method: "publish",
29948
+ summary: "Export a rendition",
29949
+ description: "Export a rendition for the platforms that deliver a file: markdown@1, docx@1 and xiaohongshu@1 end with publish.state exported, and a card rendition gains one ZIP of its pages in files. Publishing to a platform account such as X or WeChat is not available yet and answers PLATFORM_NOT_AVAILABLE; export instead. The rendition must be rendered, not stale and without error-level issues: RENDITION_NOT_RENDERED means call the render operation first, RENDITION_STALE means the draft changed so render again, RENDITION_INVALID means fix the draft problems listed in issues and render again. Exporting the same rendition twice at once answers REVISION_CONFLICT; retry shortly. Next, call the content operation to download the file.",
29950
+ http: "POST",
29951
+ path: "/studio/v1/works/{work}/renditions/{rendition}:publish",
29952
+ streaming: "no",
29953
+ pagination: false,
29954
+ pathParams: [
29955
+ {
29956
+ name: "work",
29957
+ sdkName: "work",
29958
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29959
+ },
29960
+ {
29961
+ name: "rendition",
29962
+ sdkName: "rendition",
29963
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29964
+ }
29965
+ ],
29966
+ query: []
29967
+ },
29968
+ {
29969
+ resource: "studio.works.renditions",
29970
+ method: "render",
29971
+ summary: "Render a rendition again from the current draft",
29972
+ description: "Render the rendition from the draft as it is now, replacing its parts and files and clearing stale. Call it after the draft changed, after a theme or settings change, or after a failed render. The answer carries render_state: rendered, invalid when the draft has an error-level issue (for example draft_empty on a draft with no body), or failed when the render service was unavailable (issue render_unavailable; repeat later). A render does not fail the HTTP call for those outcomes, so read render_state and issues. Rendering a Xiaohongshu card set is billed by Browser Rendering time (meter browser_ms, product studio-render); DOCX and Markdown are not billed. Rendering the same rendition twice at once answers REVISION_CONFLICT; retry shortly. Next, publish the rendition to export it.",
29973
+ http: "POST",
29974
+ path: "/studio/v1/works/{work}/renditions/{rendition}:render",
29975
+ streaming: "no",
29976
+ pagination: false,
29977
+ pathParams: [
29978
+ {
29979
+ name: "work",
29980
+ sdkName: "work",
29981
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29982
+ },
29983
+ {
29984
+ name: "rendition",
29985
+ sdkName: "rendition",
29986
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29987
+ }
29988
+ ],
29989
+ query: []
29990
+ },
29373
29991
  {
29374
29992
  resource: "studio.works.units",
29375
29993
  method: "retrieve",
@@ -38819,6 +39437,63 @@ var mediaCreateDeliveryToken = (options) => (options.client ?? client).post({
38819
39437
  ...options.headers
38820
39438
  }
38821
39439
  });
39440
+ var mediaGetDefaultLibrary = (options) => (options?.client ?? client).get({
39441
+ security: [{
39442
+ key: "media-BearerAuth",
39443
+ scheme: "bearer",
39444
+ type: "http"
39445
+ }],
39446
+ url: "/media/v1/libraries/default",
39447
+ ...options
39448
+ });
39449
+ var mediaSetDefaultLibrary = (options) => (options.client ?? client).put({
39450
+ security: [{
39451
+ key: "media-BearerAuth",
39452
+ scheme: "bearer",
39453
+ type: "http"
39454
+ }],
39455
+ url: "/media/v1/libraries/default",
39456
+ ...options,
39457
+ headers: {
39458
+ "Content-Type": "application/json",
39459
+ ...options.headers
39460
+ }
39461
+ });
39462
+ var mediaGetAssetLineage = (options) => (options.client ?? client).get({
39463
+ security: [{
39464
+ key: "media-BearerAuth",
39465
+ scheme: "bearer",
39466
+ type: "http"
39467
+ }],
39468
+ url: "/media/v1/libraries/{library_id}/assets/{asset_id}/lineage",
39469
+ ...options
39470
+ });
39471
+ var mediaGenerateImage = (options) => (options.client ?? client).post({
39472
+ security: [{
39473
+ key: "media-BearerAuth",
39474
+ scheme: "bearer",
39475
+ type: "http"
39476
+ }],
39477
+ url: "/media/v1/libraries/{library_id}/images/generations",
39478
+ ...options,
39479
+ headers: {
39480
+ "Content-Type": "application/json",
39481
+ ...options.headers
39482
+ }
39483
+ });
39484
+ var mediaEditAsset = (options) => (options.client ?? client).post({
39485
+ security: [{
39486
+ key: "media-BearerAuth",
39487
+ scheme: "bearer",
39488
+ type: "http"
39489
+ }],
39490
+ url: "/media/v1/libraries/{library_id}/assets/{asset_id}/edits",
39491
+ ...options,
39492
+ headers: {
39493
+ "Content-Type": "application/json",
39494
+ ...options.headers
39495
+ }
39496
+ });
38822
39497
  var mediaUnderstandingFailureSummary = (options) => (options.client ?? client).get({
38823
39498
  security: [{
38824
39499
  key: "media-BearerAuth",
@@ -38965,6 +39640,15 @@ var ontologyUpdateNode = (options) => (options.client ?? client).patch({
38965
39640
  ...options.headers
38966
39641
  }
38967
39642
  });
39643
+ var ontologyNeighborhood = (options) => (options.client ?? client).get({
39644
+ security: [{
39645
+ key: "ontology-bearerAuth",
39646
+ scheme: "bearer",
39647
+ type: "http"
39648
+ }],
39649
+ url: "/ontology/v1/nodes/{node_id}/neighborhood",
39650
+ ...options
39651
+ });
38968
39652
  var ontologyMergeNode = (options) => (options.client ?? client).post({
38969
39653
  security: [{
38970
39654
  key: "ontology-bearerAuth",
@@ -40728,6 +41412,118 @@ var studioThemesUpdate = (options) => (options.client ?? client).patch({
40728
41412
  ...options.headers
40729
41413
  }
40730
41414
  });
41415
+ var studioRenditionsCreate = (options) => (options.client ?? client).post({
41416
+ security: [{
41417
+ key: "BearerAuth",
41418
+ scheme: "bearer",
41419
+ type: "http"
41420
+ }, {
41421
+ key: "ApiKeyAuth",
41422
+ name: "X-API-Key",
41423
+ type: "apiKey"
41424
+ }],
41425
+ url: "/studio/v1/works/{work}/drafts/{draft}/renditions",
41426
+ ...options,
41427
+ headers: {
41428
+ "Content-Type": "application/json",
41429
+ ...options.headers
41430
+ }
41431
+ });
41432
+ var studioRenditionsList = (options) => (options.client ?? client).get({
41433
+ security: [{
41434
+ key: "BearerAuth",
41435
+ scheme: "bearer",
41436
+ type: "http"
41437
+ }, {
41438
+ key: "ApiKeyAuth",
41439
+ name: "X-API-Key",
41440
+ type: "apiKey"
41441
+ }],
41442
+ url: "/studio/v1/works/{work}/renditions",
41443
+ ...options
41444
+ });
41445
+ var studioRenditionsDelete = (options) => (options.client ?? client).delete({
41446
+ security: [{
41447
+ key: "BearerAuth",
41448
+ scheme: "bearer",
41449
+ type: "http"
41450
+ }, {
41451
+ key: "ApiKeyAuth",
41452
+ name: "X-API-Key",
41453
+ type: "apiKey"
41454
+ }],
41455
+ url: "/studio/v1/works/{work}/renditions/{rendition}",
41456
+ ...options
41457
+ });
41458
+ var studioRenditionsGet = (options) => (options.client ?? client).get({
41459
+ security: [{
41460
+ key: "BearerAuth",
41461
+ scheme: "bearer",
41462
+ type: "http"
41463
+ }, {
41464
+ key: "ApiKeyAuth",
41465
+ name: "X-API-Key",
41466
+ type: "apiKey"
41467
+ }],
41468
+ url: "/studio/v1/works/{work}/renditions/{rendition}",
41469
+ ...options
41470
+ });
41471
+ var studioRenditionsUpdate = (options) => (options.client ?? client).patch({
41472
+ security: [{
41473
+ key: "BearerAuth",
41474
+ scheme: "bearer",
41475
+ type: "http"
41476
+ }, {
41477
+ key: "ApiKeyAuth",
41478
+ name: "X-API-Key",
41479
+ type: "apiKey"
41480
+ }],
41481
+ url: "/studio/v1/works/{work}/renditions/{rendition}",
41482
+ ...options,
41483
+ headers: {
41484
+ "Content-Type": "application/json",
41485
+ ...options.headers
41486
+ }
41487
+ });
41488
+ var studioRenditionsRender = (options) => (options.client ?? client).post({
41489
+ security: [{
41490
+ key: "BearerAuth",
41491
+ scheme: "bearer",
41492
+ type: "http"
41493
+ }, {
41494
+ key: "ApiKeyAuth",
41495
+ name: "X-API-Key",
41496
+ type: "apiKey"
41497
+ }],
41498
+ url: "/studio/v1/works/{work}/renditions/{rendition}:render",
41499
+ ...options
41500
+ });
41501
+ var studioRenditionsPublish = (options) => (options.client ?? client).post({
41502
+ security: [{
41503
+ key: "BearerAuth",
41504
+ scheme: "bearer",
41505
+ type: "http"
41506
+ }, {
41507
+ key: "ApiKeyAuth",
41508
+ name: "X-API-Key",
41509
+ type: "apiKey"
41510
+ }],
41511
+ url: "/studio/v1/works/{work}/renditions/{rendition}:publish",
41512
+ ...options
41513
+ });
41514
+ var studioRenditionsContentUrl = (options) => (options.client ?? client).get({
41515
+ security: [{
41516
+ key: "BearerAuth",
41517
+ scheme: "bearer",
41518
+ type: "http"
41519
+ }, {
41520
+ key: "ApiKeyAuth",
41521
+ name: "X-API-Key",
41522
+ type: "apiKey"
41523
+ }],
41524
+ url: "/studio/v1/works/{work}/renditions/{rendition}/content",
41525
+ ...options
41526
+ });
40731
41527
  var vaultListVaults = (options) => (options?.client ?? client).get({
40732
41528
  security: [{
40733
41529
  key: "vault-bearerAuth",
@@ -42303,11 +43099,18 @@ function createKnowledge(transport) {
42303
43099
  }
42304
43100
  function createMedia(transport) {
42305
43101
  return {
43102
+ assets: {
43103
+ edit: bind(transport, mediaEditAsset),
43104
+ lineage: bind(transport, mediaGetAssetLineage)
43105
+ },
42306
43106
  generation: {
42307
43107
  capabilities: {
42308
43108
  list: bind(transport, mediaGetGenerationCapabilities)
42309
43109
  }
42310
43110
  },
43111
+ images: {
43112
+ generate: bind(transport, mediaGenerateImage)
43113
+ },
42311
43114
  libraries: {
42312
43115
  assets: {
42313
43116
  batch: bind(transport, mediaBatchAssets),
@@ -42363,6 +43166,7 @@ function createMedia(transport) {
42363
43166
  },
42364
43167
  restore: bind(transport, mediaRestoreLibrary),
42365
43168
  retrieve: bind(transport, mediaGetLibrary),
43169
+ retrieveDefault: bind(transport, mediaGetDefaultLibrary),
42366
43170
  search: {
42367
43171
  create: bind(transport, mediaSearch),
42368
43172
  expression: {
@@ -42375,6 +43179,7 @@ function createMedia(transport) {
42375
43179
  create: bind(transport, mediaVisualSearch)
42376
43180
  }
42377
43181
  },
43182
+ setDefault: bind(transport, mediaSetDefaultLibrary),
42378
43183
  understandings: {
42379
43184
  list: bindPage(transport, mediaListUnderstandingsByLibrary),
42380
43185
  retrieveFailureSummary: bind(transport, mediaUnderstandingFailureSummary)
@@ -42491,6 +43296,7 @@ function createOntology(transport) {
42491
43296
  create: bind(transport, ontologyMergeNode)
42492
43297
  },
42493
43298
  retrieve: bind(transport, ontologyRetrieveNode),
43299
+ retrieveNeighborhood: bind(transport, ontologyNeighborhood),
42494
43300
  update: bind(transport, ontologyUpdateNode)
42495
43301
  },
42496
43302
  relations: {
@@ -42682,6 +43488,9 @@ function createStudio(transport) {
42682
43488
  create: bind(transport, studioDraftsCreate),
42683
43489
  list: bind(transport, studioDraftsList),
42684
43490
  rebase: bind(transport, studioDraftsRebase),
43491
+ renditions: {
43492
+ create: bind(transport, studioRenditionsCreate)
43493
+ },
42685
43494
  retrieve: bind(transport, studioDraftsGet),
42686
43495
  retrieveExport: bind(transport, studioDraftsExport),
42687
43496
  retrieveOutline: bind(transport, studioDraftsOutline),
@@ -42697,6 +43506,15 @@ function createStudio(transport) {
42697
43506
  update: bind(transport, studioDraftsUpdate)
42698
43507
  },
42699
43508
  list: bind(transport, studioWorksList),
43509
+ renditions: {
43510
+ delete: bind(transport, studioRenditionsDelete),
43511
+ list: bind(transport, studioRenditionsList),
43512
+ publish: bind(transport, studioRenditionsPublish),
43513
+ render: bind(transport, studioRenditionsRender),
43514
+ retrieve: bind(transport, studioRenditionsGet),
43515
+ retrieveContent: bind(transport, studioRenditionsContentUrl),
43516
+ update: bind(transport, studioRenditionsUpdate)
43517
+ },
42700
43518
  resolve: bind(transport, studioWorksResolve),
42701
43519
  retrieve: bind(transport, studioWorksGet),
42702
43520
  units: {
@@ -43731,7 +44549,7 @@ async function connectActions(deps, settings) {
43731
44549
  home: settings.home,
43732
44550
  fs,
43733
44551
  now: settings.now,
43734
- fetch: deps.fetch ?? globalThis.fetch
44552
+ fetch: deps.fetch ?? globalThis.fetch.bind(globalThis)
43735
44553
  });
43736
44554
  const noPlaywright = () => new PraxisError({
43737
44555
  status: 501,
@@ -44671,6 +45489,7 @@ var workflows = [
44671
45489
  { words: ["app", "rollback"], usage: "app rollback [--dir <path>] [--to <version_id>]", summary: "Deploy the previous version again (or --to a given version) and wait until it is active.", example: "praxis app rollback --to <version_id>" },
44672
45490
  { words: ["devops", "deploy", "plan"], usage: "devops deploy plan [--env <name>] [--since <commit>]", summary: "Plan this repository's deploy: the targets by dependency layer, and with --since the ones a change touches. Local facts only — no login, no request.", example: "praxis devops deploy plan --env develop --since HEAD~1" },
44673
45491
  { words: ["devops", "test", "run"], usage: "devops test run --remote [--project <dvp_…>] [--no-wait] [--repeat <n>] [--select <kind:value>]", summary: "Run the DevOps test selection for the pushed HEAD on the Praxis cloud, wait for the verdict and list the failed cases.", example: "praxis devops test run --remote --select smoke" },
45492
+ { words: ["canvas", "import"], usage: "canvas import <file.pen> [--name <name>] [--canvas <cvs_…> --yes] [--frames <id,id>] [--image-root <dir>] [--dry-run]", summary: "Import a Pencil .pen file as a canvas, uploading the images it references first.", example: 'praxis canvas import design.pen --name "Landing page"' },
44674
45493
  { words: ["skill"], usage: "skill [--install <dir>]", summary: "Print the AI skill, or write <dir>/praxis-cli/SKILL.md." }
44675
45494
  ];
44676
45495
  var workflowNouns = [...new Set(workflows.filter((w) => w.words.length > 1).map((w) => w.words[0]))];
@@ -45056,8 +45875,11 @@ async function withLock(lockPath, run, ports = {}) {
45056
45875
  }
45057
45876
 
45058
45877
  // src/auth/credentials.ts
45059
- function credentialSource(vars) {
45060
- return vars.PRAXIS_API_KEY ? "api-key" : vars.PRAXIS_API_TOKEN ? "machine-token" : "login";
45878
+ function apiKeyVariable(env) {
45879
+ return env === "develop" ? "PRAXIS_API_KEY_DEVELOP" : "PRAXIS_API_KEY";
45880
+ }
45881
+ function credentialSource(vars, env) {
45882
+ return vars[apiKeyVariable(env)] ? "api-key" : vars.PRAXIS_API_TOKEN ? "machine-token" : "login";
45061
45883
  }
45062
45884
  async function identityRpc(config, fetchImpl, method, params, token) {
45063
45885
  const response = await fetchImpl(`${config.gatewayUrl}/rpc/practice-identity`, {
@@ -45087,8 +45909,9 @@ function jwtFetch(fetchImpl, token) {
45087
45909
  function credentials(config, vars, ports) {
45088
45910
  const path = ports.path ?? tokenPath(config.env);
45089
45911
  const store = ports.store ?? createTokenStore(config.env, path, ports.secretStore);
45090
- const source = credentialSource(vars);
45091
- const apiKey = vars.PRAXIS_API_KEY;
45912
+ const source = credentialSource(vars, config.env);
45913
+ const keyVariable = apiKeyVariable(config.env);
45914
+ const apiKey = vars[keyVariable];
45092
45915
  const machineToken = source === "machine-token" ? vars.PRAXIS_API_TOKEN : undefined;
45093
45916
  const remember = ports.remember ?? (() => {});
45094
45917
  if (apiKey)
@@ -45100,7 +45923,7 @@ function credentials(config, vars, ports) {
45100
45923
  let pending;
45101
45924
  const requireLogin = () => {
45102
45925
  if (apiKey)
45103
- throw new UsageError("The API Key determines the organization; listing or switching login organizations is unavailable.", "Unset PRAXIS_API_KEY and run `praxis login`, then retry the org command.");
45926
+ throw new UsageError("The API Key determines the organization; listing or switching login organizations is unavailable.", `Unset ${keyVariable} and run \`praxis login\`, then retry the org command.`);
45104
45927
  if (machineToken)
45105
45928
  throw new UsageError("The machine token determines the organization; listing or switching login organizations is unavailable.", "Unset PRAXIS_API_TOKEN and run `praxis login`, then retry the org command.");
45106
45929
  };
@@ -45124,7 +45947,7 @@ function credentials(config, vars, ports) {
45124
45947
  async function get(org) {
45125
45948
  if (apiKey) {
45126
45949
  if (org)
45127
- throw new UsageError("--org cannot override an API Key organization", "Remove --org or unset PRAXIS_API_KEY and run `praxis login`.");
45950
+ throw new UsageError("--org cannot override an API Key organization", `Remove --org or unset ${keyVariable} and run \`praxis login\`.`);
45128
45951
  return { source: "api-key", token: apiKey };
45129
45952
  }
45130
45953
  if (machineToken) {
@@ -45207,7 +46030,7 @@ function skillDocument(commands) {
45207
46030
  "## General rules",
45208
46031
  "",
45209
46032
  "- Select the environment only with `PRAXIS_ENV`; there is no `--env` option. The dev package defaults to develop.",
45210
- "- Authenticate with `PRAXIS_API_KEY`, `PRAXIS_API_TOKEN` (a machine token, sent in the Authorization header; computers have it set) or `praxis login`, in that order. Login saves the session even when an environment credential takes precedence; unset the named variable in its warning to use the saved login. API keys and machine tokens determine the organization; login sessions can use `--org <organization_id>`. `PRAXIS_API_URL` overrides the API base and must be an https deepraxis.com URL.",
46033
+ "- Authenticate with the API key of the environment (`PRAXIS_API_KEY` for production, `PRAXIS_API_KEY_DEVELOP` for develop; a key only works in the environment that issued it), `PRAXIS_API_TOKEN` (a machine token, sent in the Authorization header; computers have it set) or `praxis login`, in that order. Login saves the session even when an environment credential takes precedence; unset the named variable in its warning to use the saved login. API keys and machine tokens determine the organization; login sessions can use `--org <organization_id>`. `PRAXIS_API_URL` overrides the API base and must be an https deepraxis.com URL.",
45211
46034
  "- AI mode is enabled automatically in supported agent environments. Use `--format agent` to select it explicitly.",
45212
46035
  "- Use `--json` for the complete JSON response without presentation truncation. Successful JSON output goes to stdout; errors go to stderr.",
45213
46036
  "- Supply bodies with `--data JSON`, `--data @file.json`, or `--data -` for stdin. Scalar field options override matching JSON fields. Structured fields require `--data`. Multipart binary fields accept local file paths (or @paths), with repeatable flags for arrays. A binary field named data uses `--data <path>` instead of JSON.",
@@ -45241,7 +46064,22 @@ function skillDocument(commands) {
45241
46064
  "- `--select` narrows the run: `tag:<tag>` (a bare word reads as a tag), `package:<path>`, `suite:<path>`, `file:<path>`. `--repeat N` runs each selected case N times (a flake then shows up as flaky, not as a failure).",
45242
46065
  "- The run waits by default and polls every 5s; `--no-wait` returns as soon as the run exists, with `result` still `pending`.",
45243
46066
  "- Exit code 0 means the verdict passed (or is still pending); 1 means failed, errored, cancelled or timed out — the failed cases are listed, up to 20, with the run URL for the rest; 2 is a usage error.",
45244
- "- The run URL is on the Console of the environment the CLI talks to; the run id is also on stdout with `--json`."
46067
+ "- The run URL is on the Console of the environment the CLI talks to; the run id is also on stdout with `--json`.",
46068
+ "",
46069
+ "## canvas import (workflow)",
46070
+ "",
46071
+ "Import a Pencil `.pen` file as a canvas, uploading the images it references first:",
46072
+ "",
46073
+ "- Use it for a `.pen` file on this machine. The canvas API itself only takes nodes that already point at platform file ids, and a codemode program runs in the cloud where it cannot read your files — this command is the local half.",
46074
+ "- Node ids, component references, variables and themes are preserved as written: the file imports as it is, not as a redraw.",
46075
+ "- `--name <name>` names a new canvas (default: the file name without `.pen`). `--canvas <cvs_…>` imports into an existing canvas instead, which **clears every node already on it** — that is why it also requires `--yes`.",
46076
+ "- `--frames <id,id>` imports only these top-level nodes, in document order. The top-level nodes their `ref`s need come along automatically and are listed as `added`.",
46077
+ "- Images: an image fill must name a platform file id (`file-…`). Each non-`file-` url is looked up beside the `.pen` file, then under each `--image-root <dir>` (repeatable), then by file name under each root, and uploaded with a signed URL. Identical content uploads once.",
46078
+ "- An image that is not found locally is **not** a failure: it is listed under `images.missing` and `warnings` and the import continues. The canvas then shows a placeholder there — fix the path and re-import rather than leaving it.",
46079
+ "- `--dry-run` reads the local file and prints the plan (top-level nodes, added dependencies, node count, images found/missing, chunk count) without logging in or sending any request. Use it to check a document before it reaches a canvas.",
46080
+ "- Large documents go up in chunks of at most 1.5 M JSON characters; the first chunk resets the canvas and carries the variables and themes. The command is not atomic across chunks: a failure part-way leaves what already arrived, so re-run it (`--canvas … --yes` replaces the whole canvas).",
46081
+ "- Exit code 0 means the import completed, warnings included; 2 is a usage error (missing `--yes` with `--canvas`, an unreadable or non-`.pen` file).",
46082
+ "- `--format json` prints `{ canvas_id, viewer_url, revision, frames, added, nodes, images: { uploaded, reused, missing }, chunks, warnings, dry_run }`. Warnings are `FRAME_NOT_FOUND`, `REF_DANGLING`, `IMAGE_UNMAPPED` (planned) and `UNSUPPORTED_IMAGE_URL` (the service could not resolve one)."
45245
46083
  ];
45246
46084
  let domain;
45247
46085
  for (const command of commands) {
@@ -45365,7 +46203,7 @@ Enter code: ${code.user_code}` });
45365
46203
  const location = await (ports.store ?? createTokenStore(config.env, path)).save(toStored(flow.tokens, ports.now()));
45366
46204
  if (location !== "keychain")
45367
46205
  ports.emit({ kind: "message", channel: "stderr", text: "stored in a file (no system keychain available)" });
45368
- const shadowedBy = ports.source === "api-key" ? "PRAXIS_API_KEY" : ports.source === "machine-token" ? "PRAXIS_API_TOKEN" : undefined;
46206
+ const shadowedBy = ports.source === "api-key" ? apiKeyVariable(config.env) : ports.source === "machine-token" ? "PRAXIS_API_TOKEN" : undefined;
45369
46207
  ports.emit({ kind: "message", text: `Logged in (${config.env}).` });
45370
46208
  if (shadowedBy)
45371
46209
  ports.emit({ kind: "message", channel: "stderr", text: `Note: ${shadowedBy} is set and takes precedence over this login. Unset it (unset ${shadowedBy}) to use the login.` });
@@ -46057,6 +46895,13 @@ function workerNameOf(config) {
46057
46895
  const name = config?.name;
46058
46896
  return typeof name === "string" && name !== "" ? name : undefined;
46059
46897
  }
46898
+ function productionBlockOf(config) {
46899
+ const env = config?.env;
46900
+ if (env === null || typeof env !== "object")
46901
+ return;
46902
+ const block = env.production;
46903
+ return block !== null && typeof block === "object" ? block : undefined;
46904
+ }
46060
46905
  function bindingReferences(config) {
46061
46906
  const references = [];
46062
46907
  const own = workerNameOf(config);
@@ -46136,18 +46981,23 @@ function packageManifestOf(text) {
46136
46981
  return null;
46137
46982
  const name = parsed.name;
46138
46983
  const dependencies = new Set;
46139
- for (const field of ["dependencies", "devDependencies"]) {
46984
+ const devOnly = new Set;
46985
+ for (const field of ["dependencies", "peerDependencies", "optionalDependencies", "devDependencies"]) {
46140
46986
  const block = parsed[field];
46141
46987
  if (block === null || typeof block !== "object" || Array.isArray(block))
46142
46988
  continue;
46143
46989
  for (const [dependency, version] of Object.entries(block)) {
46144
- if (typeof version === "string" && version.startsWith("workspace:"))
46145
- dependencies.add(dependency);
46990
+ if (typeof version !== "string" || !version.startsWith("workspace:") || dependencies.has(dependency))
46991
+ continue;
46992
+ dependencies.add(dependency);
46993
+ if (field === "devDependencies")
46994
+ devOnly.add(dependency);
46146
46995
  }
46147
46996
  }
46148
46997
  return {
46149
46998
  ...typeof name === "string" && name !== "" ? { name } : {},
46150
- workspaceDependencies: [...dependencies].sort()
46999
+ workspaceDependencies: [...dependencies].sort(),
47000
+ devOnlyWorkspaceDependencies: [...devOnly].sort()
46151
47001
  };
46152
47002
  }
46153
47003
  function lifecycleOf(text) {
@@ -46326,7 +47176,8 @@ var WORKSPACE_PASSES = Symbol("deploy-core.workspace-passes");
46326
47176
  async function readWorkspacesOnce(facts, options) {
46327
47177
  const tree = new Set(facts.tree);
46328
47178
  const index = await workspaceIndexOf(facts, options);
46329
- return await mapBounded(index.packages, READ_CONCURRENCY, async (entry) => {
47179
+ const limit = options.readConcurrency !== undefined && options.readConcurrency >= 1 ? Math.floor(options.readConcurrency) : READ_CONCURRENCY;
47180
+ return await mapBounded(index.packages, limit, async (entry) => {
46330
47181
  const manifest = manifestPathIn(entry.dir, tree);
46331
47182
  const [manifestText, configText] = await Promise.all([
46332
47183
  facts.read(entry.packageJson),
@@ -46341,7 +47192,8 @@ async function readWorkspacesOnce(facts, options) {
46341
47192
  config,
46342
47193
  ...workerNameOf(config) === undefined ? {} : { workerName: workerNameOf(config) },
46343
47194
  lifecycle: lifecycleOf(manifestText),
46344
- workspaceDependencies: pkg?.workspaceDependencies ?? []
47195
+ workspaceDependencies: pkg?.workspaceDependencies ?? [],
47196
+ devOnlyWorkspaceDependencies: pkg?.devOnlyWorkspaceDependencies ?? []
46345
47197
  };
46346
47198
  });
46347
47199
  }
@@ -46383,7 +47235,9 @@ function workspaceCloudflareProvider(options = {}) {
46383
47235
  name: workspace.packageName ?? (workspace.dir === "." ? "app" : workspace.dir.split("/").at(-1)),
46384
47236
  destination: "cloudflare",
46385
47237
  ...workspace.workerName === undefined ? {} : { workerName: workspace.workerName },
46386
- ...environments === undefined ? {} : { environments }
47238
+ ...environments === undefined ? {} : { environments },
47239
+ production: productionBlockOf(workspace.config) !== undefined,
47240
+ onTrain: lifecycle?.train !== false
46387
47241
  });
46388
47242
  }
46389
47243
  return { targets: [...partial.targets, ...targets] };
@@ -46432,19 +47286,50 @@ function closePlan(drafts, workspaces) {
46432
47286
  const configOf = new Map(workspaces.map((workspace) => [workspace.dir, workspace.config]));
46433
47287
  const edges = wranglerEdges(drafts.map((draft) => ({ id: draft.path, config: configOf.get(draft.path) ?? null })));
46434
47288
  const byName = directoriesOfPackageNames(workspaces);
46435
- const dependenciesOf = (dir) => workspaces.find((workspace) => workspace.dir === dir)?.workspaceDependencies ?? [];
47289
+ const dependenciesOf = (dir) => {
47290
+ const workspace = workspaces.find((entry) => entry.dir === dir);
47291
+ if (workspace === undefined)
47292
+ return [];
47293
+ const devOnly = new Set(workspace.devOnlyWorkspaceDependencies ?? []);
47294
+ return workspace.workspaceDependencies.filter((name) => {
47295
+ if (!devOnly.has(name))
47296
+ return true;
47297
+ const path = byName.get(name);
47298
+ return path === undefined || !isDeployToolDependency(name, path);
47299
+ });
47300
+ };
46436
47301
  return drafts.map((draft) => ({
46437
47302
  path: draft.path,
46438
47303
  name: draft.name,
46439
47304
  destination: draft.destination,
46440
47305
  dependsOn: edges.get(draft.path) ?? [],
46441
47306
  ...draft.environments === undefined ? {} : { environments: draft.environments },
47307
+ production: draft.production === true,
47308
+ onTrain: draft.onTrain !== false,
46442
47309
  workspaceDeps: workspaceClosureOf(draft.path, byName, dependenciesOf)
46443
47310
  })).sort((a, b) => a.path.localeCompare(b.path));
46444
47311
  }
47312
+ function isDeployToolDependency(name, path) {
47313
+ const directory = path.replace(/^(\.\/)+/, "").replace(/^\/+/, "").replace(/\/+$/, "");
47314
+ if (directory === "packages/mise" || directory.startsWith("packages/mise/"))
47315
+ return true;
47316
+ if (directory === "packages/testing" || directory.startsWith("packages/testing/"))
47317
+ return true;
47318
+ return name.startsWith("@mise/");
47319
+ }
46445
47320
  function targetsFor(plan, environment2) {
46446
47321
  return plan.targets.filter((target) => target.environments === undefined || target.environments.includes(environment2));
46447
47322
  }
47323
+ var TARGET_EXTERNAL_INPUTS = {
47324
+ "apps/docs": [
47325
+ "apps/api/openapi/openapi.yaml",
47326
+ "packages/praxis/rpc-kit/src/errors.ts",
47327
+ "services/agent/src/domain/error-codes.ts",
47328
+ ...["application", "database", "knowledge"].map((s) => `services/${s}/src/api/error-exit.ts`),
47329
+ ...["router", "vault", "browser", "search"].map((s) => `services/${s}/src/api/rpc-contract.ts`),
47330
+ ...["media", "automation", "sandbox", "file", "billing", "config", "eventbus", "lakehouse", "identity", "notification", "ops", "registry"].map((s) => `services/${s}/src/api/contract.ts`)
47331
+ ]
47332
+ };
46448
47333
  function diffTargets(plan, changedPaths) {
46449
47334
  const changed = new Set(changedPaths);
46450
47335
  const touches = (dir) => {
@@ -46456,7 +47341,8 @@ function diffTargets(plan, changedPaths) {
46456
47341
  return true;
46457
47342
  return false;
46458
47343
  };
46459
- return plan.targets.filter((target) => touches(target.path) || target.workspaceDeps.some(touches)).map((target) => target.path);
47344
+ const readsChangedInput = (dir) => (TARGET_EXTERNAL_INPUTS[dir] ?? []).some((file) => changed.has(file));
47345
+ return plan.targets.filter((target) => touches(target.path) || target.workspaceDeps.some(touches) || readsChangedInput(target.path) || target.workspaceDeps.some(readsChangedInput)).map((target) => target.path);
46460
47346
  }
46461
47347
  function layersOf(plan) {
46462
47348
  const paths = plan.targets.map((target) => target.path);
@@ -46626,6 +47512,1231 @@ async function devopsDeployPlan(args, ports) {
46626
47512
  ports.human(renderDeployPlan(view));
46627
47513
  }
46628
47514
 
47515
+ // src/commands/canvas-import.ts
47516
+ import { basename as basename2, dirname as dirname2, join as join5, resolve as resolve3 } from "node:path";
47517
+
47518
+ // ../../packages/canvas/document/src/types.ts
47519
+ class OpRejectedError extends Error {
47520
+ rejection;
47521
+ constructor(rejection) {
47522
+ super(`${rejection.code}: ${JSON.stringify(rejection)}`);
47523
+ this.rejection = rejection;
47524
+ }
47525
+ }
47526
+ var CONTAINER_TYPES = new Set(["frame", "group"]);
47527
+ // ../../packages/canvas/document/src/legacy-props.ts
47528
+ function ownIconProps(node2) {
47529
+ const out = { ...node2 };
47530
+ if ((node2.type === "icon" || node2.type === undefined) && "iconName" in node2) {
47531
+ if (!("icon" in node2))
47532
+ out.icon = node2.iconName;
47533
+ delete out.iconName;
47534
+ }
47535
+ return out;
47536
+ }
47537
+ function migrateLegacyIconProps(node2) {
47538
+ const out = ownIconProps(node2);
47539
+ if (node2.descendants && typeof node2.descendants === "object" && !Array.isArray(node2.descendants))
47540
+ out.descendants = Object.fromEntries(Object.entries(node2.descendants).map(([key, value]) => [
47541
+ key,
47542
+ value && typeof value === "object" && !Array.isArray(value) ? migrateLegacyIconProps(value) : value
47543
+ ]));
47544
+ if (Array.isArray(node2.children))
47545
+ out.children = node2.children.map((child) => migrateLegacyIconProps(child));
47546
+ return out;
47547
+ }
47548
+ function migrateLegacyProps(node2) {
47549
+ const out = ownIconProps(node2);
47550
+ const stroke = node2.stroke;
47551
+ if (stroke && typeof stroke === "object" && !Array.isArray(stroke) && "fill" in stroke) {
47552
+ const old = stroke;
47553
+ out.stroke = old.fill;
47554
+ if (!("strokeWidth" in node2) && "thickness" in old)
47555
+ out.strokeWidth = old.thickness;
47556
+ if (!("strokeAlignment" in node2) && "align" in old) {
47557
+ out.strokeAlignment = old.align === "inside" ? "inner" : old.align === "outside" ? "outer" : old.align;
47558
+ }
47559
+ }
47560
+ if (Array.isArray(node2.children))
47561
+ out.children = node2.children.map((child) => migrateLegacyProps(child));
47562
+ if (node2.descendants && typeof node2.descendants === "object" && !Array.isArray(node2.descendants))
47563
+ out.descendants = Object.fromEntries(Object.entries(node2.descendants).map(([key, value]) => [
47564
+ key,
47565
+ value && typeof value === "object" && !Array.isArray(value) ? migrateLegacyProps(value) : value
47566
+ ]));
47567
+ return out;
47568
+ }
47569
+
47570
+ // ../../packages/canvas/document/src/store.ts
47571
+ var DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
47572
+ var BASE = DIGITS.length;
47573
+ function midpoint(a, b) {
47574
+ if (b !== null) {
47575
+ let n = 0;
47576
+ while ((a[n] ?? "0") === b[n])
47577
+ n++;
47578
+ if (n > 0)
47579
+ return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
47580
+ }
47581
+ const da = a ? DIGITS.indexOf(a[0]) : 0;
47582
+ const db = b !== null ? DIGITS.indexOf(b[0]) : BASE;
47583
+ if (db - da > 1)
47584
+ return DIGITS[Math.floor((da + db) / 2)];
47585
+ if (b !== null && b.length > 1)
47586
+ return b.slice(0, 1);
47587
+ return DIGITS[da] + midpoint(a.slice(1), null);
47588
+ }
47589
+ function between(a, b) {
47590
+ return midpoint(a ?? "", b);
47591
+ }
47592
+ function spacedKeys(n) {
47593
+ let width = 1;
47594
+ while (BASE ** width < n + 2)
47595
+ width++;
47596
+ const keys = [];
47597
+ for (let i = 1;i <= n; i++) {
47598
+ let v = i;
47599
+ let s = "";
47600
+ for (let d = 0;d < width; d++) {
47601
+ s = DIGITS[v % BASE] + s;
47602
+ v = Math.floor(v / BASE);
47603
+ }
47604
+ keys.push(s + "V");
47605
+ }
47606
+ return keys;
47607
+ }
47608
+
47609
+ class MapNodeStore {
47610
+ nodes = new Map;
47611
+ kids = new Map;
47612
+ vars = {};
47613
+ themeAxes = {};
47614
+ rev = 0;
47615
+ get(id) {
47616
+ return this.nodes.get(id);
47617
+ }
47618
+ children(id) {
47619
+ return this.kids.get(id) ?? [];
47620
+ }
47621
+ variables() {
47622
+ return this.vars;
47623
+ }
47624
+ themes() {
47625
+ return this.themeAxes;
47626
+ }
47627
+ revision() {
47628
+ return this.rev;
47629
+ }
47630
+ unlink(n) {
47631
+ const list = this.kids.get(n.parent);
47632
+ if (!list)
47633
+ return;
47634
+ const i = list.indexOf(n.id);
47635
+ if (i >= 0)
47636
+ list.splice(i, 1);
47637
+ }
47638
+ link(n) {
47639
+ let list = this.kids.get(n.parent);
47640
+ if (!list)
47641
+ this.kids.set(n.parent, list = []);
47642
+ let lo = 0;
47643
+ let hi = list.length;
47644
+ if (hi && this.nodes.get(list[hi - 1]).ord < n.ord)
47645
+ lo = hi;
47646
+ while (lo < hi) {
47647
+ const mid = lo + hi >> 1;
47648
+ const o = this.nodes.get(list[mid]).ord;
47649
+ if (o < n.ord || o === n.ord && list[mid] < n.id)
47650
+ lo = mid + 1;
47651
+ else
47652
+ hi = mid;
47653
+ }
47654
+ list.splice(lo, 0, n.id);
47655
+ }
47656
+ put(node2) {
47657
+ const prev = this.nodes.get(node2.id);
47658
+ if (prev && (prev.parent !== node2.parent || prev.ord !== node2.ord))
47659
+ this.unlink(prev);
47660
+ this.nodes.set(node2.id, node2);
47661
+ if (!prev || prev.parent !== node2.parent || prev.ord !== node2.ord)
47662
+ this.link(node2);
47663
+ }
47664
+ remove(id) {
47665
+ const prev = this.nodes.get(id);
47666
+ if (!prev)
47667
+ return;
47668
+ this.unlink(prev);
47669
+ this.kids.delete(id);
47670
+ this.nodes.delete(id);
47671
+ }
47672
+ setVariables(vars, themes) {
47673
+ this.vars = vars;
47674
+ this.themeAxes = themes;
47675
+ }
47676
+ setRevision(rev) {
47677
+ this.rev = rev;
47678
+ }
47679
+ size() {
47680
+ return this.nodes.size;
47681
+ }
47682
+ reindex() {}
47683
+ }
47684
+ function ownProps(node2) {
47685
+ const { children: _c, ...rest } = node2;
47686
+ return rest;
47687
+ }
47688
+ function flatten(nodes, parent, top, rev, out = []) {
47689
+ const keys = spacedKeys(nodes.length);
47690
+ nodes.forEach((n, i) => {
47691
+ const t = top ?? n.id;
47692
+ const props = ownProps(n);
47693
+ const ord = typeof props.__ord === "string" ? props.__ord : keys[i];
47694
+ delete props.__ord;
47695
+ out.push({ id: n.id, parent, ord, top: t, props, rev });
47696
+ if (Array.isArray(n.children) && n.children.length)
47697
+ flatten(n.children, n.id, t, rev, out);
47698
+ });
47699
+ return out;
47700
+ }
47701
+ function subtree(store, id, depth = Infinity, withOrd = false) {
47702
+ const row = store.get(id);
47703
+ if (!row)
47704
+ throw new Error(`node ${id} not found`);
47705
+ const node2 = migrateLegacyIconProps(row.props);
47706
+ if (withOrd)
47707
+ node2.__ord = row.ord;
47708
+ const kids = store.children(id);
47709
+ if (kids.length) {
47710
+ if (depth <= 0)
47711
+ node2.children = "...";
47712
+ else
47713
+ node2.children = kids.map((k) => subtree(store, k, depth - 1, withOrd));
47714
+ }
47715
+ return node2;
47716
+ }
47717
+ // ../../packages/canvas/document/src/apply.ts
47718
+ function applyOp(store, op, rev) {
47719
+ switch (op.op) {
47720
+ case "insert": {
47721
+ const top = op.parent === null ? null : store.get(op.parent).top;
47722
+ const rows = flatten([op.node], op.parent, top, rev);
47723
+ rows[0] = { ...rows[0], ord: op.ord };
47724
+ for (const r of rows)
47725
+ store.put(r);
47726
+ return [rows[0].top];
47727
+ }
47728
+ case "update": {
47729
+ const row = store.get(op.id);
47730
+ const props = { ...row.props };
47731
+ for (const [k, v] of Object.entries(op.patch)) {
47732
+ if (v === undefined || v === null)
47733
+ delete props[k];
47734
+ else
47735
+ props[k] = v;
47736
+ }
47737
+ store.put({ ...row, props, rev });
47738
+ return [row.top];
47739
+ }
47740
+ case "delete": {
47741
+ const row = store.get(op.id);
47742
+ removeSubtree(store, op.id);
47743
+ return [row.top];
47744
+ }
47745
+ case "move": {
47746
+ const row = store.get(op.id);
47747
+ const oldTop = row.top;
47748
+ const newTop = op.parent === null ? op.id : store.get(op.parent).top;
47749
+ store.put({ ...row, parent: op.parent, ord: op.ord, top: newTop, rev });
47750
+ if (newTop !== oldTop)
47751
+ retop(store, op.id, newTop, rev);
47752
+ return oldTop === newTop ? [newTop] : [oldTop, newTop];
47753
+ }
47754
+ case "setVariables": {
47755
+ const vars = op.replace ? op.variables : { ...store.variables(), ...op.variables };
47756
+ const themes = { ...store.themes() };
47757
+ for (const [axis, values] of Object.entries(op.themes)) {
47758
+ const cur = themes[axis] ?? [];
47759
+ themes[axis] = [...cur, ...values.filter((v) => !cur.includes(v))];
47760
+ }
47761
+ store.setVariables(vars, themes);
47762
+ return [];
47763
+ }
47764
+ }
47765
+ }
47766
+ function removeSubtree(store, id) {
47767
+ for (const c of store.children(id))
47768
+ removeSubtree(store, c);
47769
+ store.remove(id);
47770
+ }
47771
+ function retop(store, id, top, rev) {
47772
+ for (const c of store.children(id)) {
47773
+ const row = store.get(c);
47774
+ store.put({ ...row, top, rev });
47775
+ retop(store, c, top, rev);
47776
+ }
47777
+ }
47778
+ // ../../packages/canvas/document/src/expand.ts
47779
+ function defaultTheme(themes) {
47780
+ const t = {};
47781
+ for (const [axis, values] of Object.entries(themes))
47782
+ if (values.length)
47783
+ t[axis] = values[0];
47784
+ return t;
47785
+ }
47786
+ function resolveVariable(name, vars, theme, depth = 0) {
47787
+ const def = vars[name];
47788
+ if (!def || depth > 8)
47789
+ return;
47790
+ let v;
47791
+ if (Array.isArray(def.value)) {
47792
+ let best;
47793
+ for (const e of def.value) {
47794
+ const keys = Object.keys(e.theme ?? {});
47795
+ if (keys.every((k) => theme[k] === e.theme[k]) && (!best || keys.length > best.score))
47796
+ best = { value: e.value, score: keys.length };
47797
+ }
47798
+ v = best?.value ?? def.value[0]?.value;
47799
+ } else
47800
+ v = def.value;
47801
+ if (typeof v === "string" && v.startsWith("$") && vars[v.slice(1)])
47802
+ return resolveVariable(v.slice(1), vars, theme, depth + 1);
47803
+ return v;
47804
+ }
47805
+ function resolveDeep(value, vars, theme) {
47806
+ if (typeof value === "string") {
47807
+ if (value.startsWith("$") && vars[value.slice(1)] !== undefined)
47808
+ return resolveVariable(value.slice(1), vars, theme);
47809
+ return value;
47810
+ }
47811
+ if (Array.isArray(value))
47812
+ return value.map((v) => resolveDeep(v, vars, theme));
47813
+ if (value && typeof value === "object") {
47814
+ const out = {};
47815
+ for (const [k, v] of Object.entries(value))
47816
+ out[k] = resolveDeep(v, vars, theme);
47817
+ return out;
47818
+ }
47819
+ return value;
47820
+ }
47821
+ var SKIP_RESOLVE = new Set(["id", "type", "ref", "descendants", "name", "content", "children"]);
47822
+ function resolveProps(props, vars, theme) {
47823
+ const out = {};
47824
+ for (const [k, v] of Object.entries(props))
47825
+ out[k] = SKIP_RESOLVE.has(k) ? v : resolveDeep(v, vars, theme);
47826
+ if (typeof props.content === "string" && props.content.startsWith("$") && vars[props.content.slice(1)] !== undefined)
47827
+ out.content = String(resolveVariable(props.content.slice(1), vars, theme));
47828
+ return out;
47829
+ }
47830
+ function propsOf(store, src) {
47831
+ if (src.kind === "store")
47832
+ return store.get(src.id)?.props;
47833
+ const { children: _c, ...rest } = src.node;
47834
+ return rest;
47835
+ }
47836
+ function childrenOf(store, src) {
47837
+ if (src.kind === "store")
47838
+ return store.children(src.id).map((id) => ({ kind: "store", id }));
47839
+ return (src.node.children ?? []).map((node2) => ({ kind: "inline", node: node2 }));
47840
+ }
47841
+ function expandNode(store, id, parentTheme) {
47842
+ return expandSrc({ store, vars: store.variables(), stack: [] }, { kind: "store", id }, parentTheme, null, {});
47843
+ }
47844
+ function expandSrc(ctx, src, parentTheme, pathPrefix, overrides) {
47845
+ let props = propsOf(ctx.store, src);
47846
+ if (!props)
47847
+ return null;
47848
+ const ownId = props.id;
47849
+ const path = pathPrefix ? `${pathPrefix}/${ownId}` : ownId;
47850
+ const ov = pathPrefix ? overrides[ownId] : undefined;
47851
+ if (ov && typeof ov.type === "string") {
47852
+ const repl = ov;
47853
+ const replId = typeof repl.id === "string" ? repl.id : ownId;
47854
+ const e = expandSrc(ctx, { kind: "inline", node: { ...repl, id: replId } }, parentTheme, null, {});
47855
+ return e ? { ...e, role: "instance-child" } : null;
47856
+ }
47857
+ if (ov)
47858
+ props = { ...props, ...ov };
47859
+ const theme = props.theme && typeof props.theme === "object" ? { ...parentTheme, ...props.theme } : parentTheme;
47860
+ if (props.type === "ref")
47861
+ return expandRef(ctx, props, path, theme, pathPrefix ? childOverrides(overrides, ownId) : {});
47862
+ const resolved = resolveProps(props, ctx.vars, theme);
47863
+ const children = [];
47864
+ for (const c of childrenOf(ctx.store, src)) {
47865
+ const e = expandSrc(ctx, c, theme, pathPrefix, overrides);
47866
+ if (e)
47867
+ children.push(e);
47868
+ }
47869
+ return {
47870
+ path,
47871
+ type: props.type,
47872
+ props: resolved,
47873
+ children,
47874
+ theme,
47875
+ role: pathPrefix ? "instance-child" : props.reusable ? "component" : "plain"
47876
+ };
47877
+ }
47878
+ function childOverrides(overrides, id) {
47879
+ const out = {};
47880
+ const prefix = id + "/";
47881
+ for (const [k, v] of Object.entries(overrides))
47882
+ if (k.startsWith(prefix))
47883
+ out[k.slice(prefix.length)] = v;
47884
+ return out;
47885
+ }
47886
+ function expandRef(ctx, ref, path, theme, inherited) {
47887
+ const target = ref.ref;
47888
+ const comp = ctx.store.get(target);
47889
+ if (!comp || ctx.stack.includes(target))
47890
+ return null;
47891
+ const descendants = { ...ref.descendants ?? {} };
47892
+ for (const [id, override] of Object.entries(inherited)) {
47893
+ descendants[id] = typeof override.type === "string" ? override : { ...descendants[id], ...override };
47894
+ }
47895
+ const { id: _i, type: _t, ref: _r, descendants: _d, reusable: _re, ...refOwn } = ref;
47896
+ const root = { ...comp.props, ...refOwn, id: ref.id };
47897
+ delete root.reusable;
47898
+ ctx.stack.push(target);
47899
+ const rootTheme = root.theme && typeof root.theme === "object" ? { ...theme, ...root.theme } : theme;
47900
+ const children = [];
47901
+ for (const c of ctx.store.children(target)) {
47902
+ const e = expandSrc(ctx, { kind: "store", id: c }, rootTheme, path, descendants);
47903
+ if (e)
47904
+ children.push(e);
47905
+ }
47906
+ ctx.stack.pop();
47907
+ return { path, type: root.type, props: resolveProps(root, ctx.vars, rootTheme), children, theme: rootTheme, role: "instance" };
47908
+ }
47909
+ // ../../packages/canvas/document/src/known-props.ts
47910
+ var ENTITY = "id type name context reusable theme enabled opacity flipX flipY layoutPosition metadata rotation x y children";
47911
+ var SIZE = "width height";
47912
+ var STROKE = "stroke strokeWidth strokeLinecap strokeLinejoin strokeAlignment";
47913
+ var EFFECTS = "effect";
47914
+ var GRAPHICS = `${EFFECTS} ${STROKE} fill`;
47915
+ var TEXT = "fontFamily fontSize fontWeight letterSpacing fontStyle underline lineHeight textAlign textAlignVertical strikethrough href";
47916
+ var LAYOUT = "layout gap layoutIncludeStroke padding justifyContent alignItems";
47917
+ var RECTANGLE = `${SIZE} ${GRAPHICS} cornerRadius`;
47918
+ var keys = (extra) => new Set(`${ENTITY} ${extra}`.split(/\s+/));
47919
+ var KNOWN_PROPS = {
47920
+ rectangle: keys(RECTANGLE),
47921
+ ellipse: keys(`${SIZE} ${GRAPHICS} innerRadius startAngle sweepAngle`),
47922
+ polygon: keys(`${SIZE} ${GRAPHICS} polygonCount cornerRadius`),
47923
+ path: keys(`${SIZE} ${GRAPHICS} fillRule geometry viewBox`),
47924
+ text: keys(`${SIZE} ${GRAPHICS} ${TEXT} content textGrowth`),
47925
+ frame: keys(`${RECTANGLE} ${LAYOUT} clip placeholder slot`),
47926
+ group: keys(EFFECTS),
47927
+ note: keys(`${SIZE} ${TEXT} content`),
47928
+ prompt: keys(`${SIZE} ${TEXT} content model`),
47929
+ context: keys(`${SIZE} ${TEXT} content`),
47930
+ icon: keys(`${SIZE} ${EFFECTS} library icon weight fill`),
47931
+ script: keys(`${SIZE} clip scriptUri inputs`),
47932
+ browser: keys(`${SIZE} ${EFFECTS} ${STROKE} url deviceId zoom scrollX scrollY cornerRadius`),
47933
+ ref: keys("ref descendants")
47934
+ };
47935
+ function unknownProperties(node2, type) {
47936
+ if (type === "ref")
47937
+ return [];
47938
+ const allowed = Object.hasOwn(KNOWN_PROPS, type) ? KNOWN_PROPS[type] : keys("");
47939
+ return Object.keys(node2).filter((key) => !key.startsWith("__") && !allowed.has(key));
47940
+ }
47941
+ function iconNameOf(node2) {
47942
+ for (const key of ["icon", "iconName"]) {
47943
+ const value = node2[key];
47944
+ if (typeof value === "string" && value.trim() !== "")
47945
+ return value;
47946
+ }
47947
+ return "";
47948
+ }
47949
+ function hasUnsupportedImageUrl(node2) {
47950
+ const invalid = (paint) => {
47951
+ if (Array.isArray(paint))
47952
+ return paint.some(invalid);
47953
+ if (!paint || typeof paint !== "object")
47954
+ return false;
47955
+ const fill = paint;
47956
+ return fill.type === "image" && (typeof fill.url !== "string" || !/^file-[0-9A-Za-z]{24}$/.test(fill.url));
47957
+ };
47958
+ return invalid(node2.fill) || invalid(node2.stroke);
47959
+ }
47960
+
47961
+ // ../../packages/canvas/document/src/execute-api.ts
47962
+ var LIMITS = { ops: 5000, printBytes: 64 * 1024, screenshots: 4 };
47963
+ var ID_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
47964
+ class ExecuteApi {
47965
+ store;
47966
+ rec;
47967
+ bounds;
47968
+ rev;
47969
+ random;
47970
+ document = "document";
47971
+ layoutCache = new Map;
47972
+ constructor(store, rec, bounds, rev, random = Math.random) {
47973
+ this.store = store;
47974
+ this.rec = rec;
47975
+ this.bounds = bounds;
47976
+ this.rev = rev;
47977
+ this.random = random;
47978
+ }
47979
+ mint() {
47980
+ for (;; ) {
47981
+ let id = "";
47982
+ for (let i = 0;i < 5; i++)
47983
+ id += ID_CHARS[Math.floor(this.random() * ID_CHARS.length)];
47984
+ if (!this.store.get(id))
47985
+ return id;
47986
+ }
47987
+ }
47988
+ commit(op) {
47989
+ if (this.rec.ops.length >= LIMITS.ops)
47990
+ throw new Error(`SCRIPT_LIMIT: more than ${LIMITS.ops} operations in one execute`);
47991
+ const touched = applyOp(this.store, op, this.rev);
47992
+ this.mutations++;
47993
+ this.rec.ops.push(op);
47994
+ if (op.op === "setVariables")
47995
+ this.rec.allTouched = true;
47996
+ for (const t of touched) {
47997
+ this.rec.touchedTop.add(t);
47998
+ this.layoutCache.delete(t);
47999
+ }
48000
+ if (op.op === "setVariables")
48001
+ this.layoutCache.clear();
48002
+ }
48003
+ parentId(parent) {
48004
+ if (parent === "document" || parent === "" || parent == null)
48005
+ return null;
48006
+ if (parent.includes("/"))
48007
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "parent", reason: "cannot insert inside a component instance; use Replace on the instance child" });
48008
+ const row = this.store.get(parent);
48009
+ if (!row)
48010
+ throw new OpRejectedError({ code: "PARENT_NOT_FOUND", path: parent });
48011
+ if (!CONTAINER_TYPES.has(row.props.type))
48012
+ throw new OpRejectedError({ code: "CANNOT_HAVE_CHILDREN", parent, type: row.props.type });
48013
+ return parent;
48014
+ }
48015
+ lastOrd(parent) {
48016
+ const kids = this.store.children(parent);
48017
+ return kids.length ? this.store.get(kids[kids.length - 1]).ord : null;
48018
+ }
48019
+ withIds(node2) {
48020
+ if (typeof node2 !== "object" || node2 === null || typeof node2.type !== "string")
48021
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "type", reason: "node needs a type" });
48022
+ if (node2.type === "ref") {
48023
+ const target = node2.ref;
48024
+ if (!this.store.get(target))
48025
+ throw new OpRejectedError({ code: "UNKNOWN_REF", ref: target });
48026
+ }
48027
+ for (const k of ["width", "height"]) {
48028
+ const v = node2[k];
48029
+ if (typeof v === "number" && v < 0)
48030
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: k, reason: "negative size" });
48031
+ if (typeof v === "string" && /%|vh|vw|calc/.test(v))
48032
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: k, reason: "percentage and viewport sizes are not supported" });
48033
+ }
48034
+ const id = this.mint();
48035
+ const out = { ...node2, id };
48036
+ if (typeof node2.name === "string")
48037
+ this.rec.created[node2.name] = id;
48038
+ if (Array.isArray(node2.children)) {
48039
+ if (!CONTAINER_TYPES.has(node2.type))
48040
+ throw new OpRejectedError({ code: "CANNOT_HAVE_CHILDREN", parent: id, type: node2.type });
48041
+ out.children = node2.children.map((c) => this.withIds(c));
48042
+ }
48043
+ return out;
48044
+ }
48045
+ warnProps(data, type, nodeId) {
48046
+ if (hasUnsupportedImageUrl(data) && this.rec.warnings.length < 20 && !this.rec.warnings.some((w) => w.code === "UNSUPPORTED_IMAGE_URL" && w.nodeId === nodeId))
48047
+ this.rec.warnings.push({ code: "UNSUPPORTED_IMAGE_URL", nodeId, message: "image fill url must be a file id (file-…)" });
48048
+ if (data.type === "icon" && !iconNameOf(data) && this.rec.warnings.length < 20 && !this.rec.warnings.some((w) => w.code === "ICON_NAME_MISSING" && w.nodeId === nodeId))
48049
+ this.rec.warnings.push({ code: "ICON_NAME_MISSING", nodeId, message: "icon node has no icon: set icon to a lucide name (name is the node's name, not the icon)" });
48050
+ for (const prop of unknownProperties(data, type)) {
48051
+ const message = `${prop} is not a .pen property`;
48052
+ if (this.rec.warnings.length >= 20)
48053
+ break;
48054
+ if (!this.rec.warnings.some((w) => w.code === "UNKNOWN_PROPERTY" && w.nodeId === nodeId && w.message === message))
48055
+ this.rec.warnings.push({ code: "UNKNOWN_PROPERTY", nodeId, message });
48056
+ }
48057
+ for (const child of Array.isArray(data.children) ? data.children : [])
48058
+ this.warnProps(child, child.type, child.id ?? nodeId);
48059
+ if (data.descendants && typeof data.descendants === "object") {
48060
+ const descendants = typeof data.ref === "string" ? this.resolveDescendantKeys(data.ref, data.descendants) : data.descendants;
48061
+ for (const [key, value] of Object.entries(descendants)) {
48062
+ if (!value || typeof value !== "object")
48063
+ continue;
48064
+ const patch = value;
48065
+ const target = this.store.get(key)?.props.type ?? (typeof data.ref === "string" ? this.expandedAt(`${data.ref}/${key}`, {})?.node.type : undefined);
48066
+ this.warnProps(patch, typeof patch.type === "string" ? patch.type : target ?? "ref", `${nodeId}/${key}`);
48067
+ }
48068
+ }
48069
+ }
48070
+ splitInstancePath(path) {
48071
+ const i = path.indexOf("/");
48072
+ if (i < 0)
48073
+ return null;
48074
+ return { owner: path.slice(0, i), rest: path.slice(i + 1) };
48075
+ }
48076
+ resolveDescendantKeys(rootId, desc) {
48077
+ const byName = new Map;
48078
+ const walk = (id) => {
48079
+ for (const c of this.store.children(id)) {
48080
+ const n = this.store.get(c).props;
48081
+ if (n.name)
48082
+ byName.set(n.name, [...byName.get(n.name) ?? [], c]);
48083
+ walk(c);
48084
+ }
48085
+ };
48086
+ walk(rootId);
48087
+ const out = {};
48088
+ for (const [k, v] of Object.entries(desc)) {
48089
+ let key = k;
48090
+ if (!k.includes("/") && !this.store.get(k)) {
48091
+ const hits = byName.get(k);
48092
+ if (hits?.length === 1)
48093
+ key = hits[0];
48094
+ }
48095
+ out[key] = v;
48096
+ }
48097
+ return out;
48098
+ }
48099
+ Insert(parent, nodeData) {
48100
+ const p = this.parentId(parent);
48101
+ let node2 = this.withIds(migrateLegacyProps(nodeData));
48102
+ if (node2.type === "ref" && node2.descendants && typeof node2.descendants === "object")
48103
+ node2 = { ...node2, descendants: this.resolveDescendantKeys(node2.ref, node2.descendants) };
48104
+ this.warnProps(node2, node2.type, node2.id);
48105
+ this.commit({ op: "insert", parent: p, ord: between(this.lastOrd(p), null), node: node2 });
48106
+ return node2.id;
48107
+ }
48108
+ Copy(path, parent, copyNodeData = {}) {
48109
+ if (path.includes("/"))
48110
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "path", reason: "copying an instance child is not supported in this spike" });
48111
+ const src = this.store.get(path);
48112
+ if (!src)
48113
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48114
+ const p = this.parentId(parent);
48115
+ const { descendants, ...over } = migrateLegacyProps(copyNodeData);
48116
+ let node2;
48117
+ if (src.props.reusable) {
48118
+ node2 = { type: "ref", ref: src.id, ...over };
48119
+ if (descendants)
48120
+ node2.descendants = this.resolveDescendantKeys(src.id, descendants);
48121
+ node2 = this.withIds(node2);
48122
+ } else {
48123
+ const tree = subtree(this.store, src.id);
48124
+ const descMap = descendants ? this.resolveDescendantKeys(src.id, descendants) : {};
48125
+ const apply = (n) => {
48126
+ const d = descMap[n.id];
48127
+ let out = d && typeof d.type === "string" ? { ...d } : { ...n, ...d ?? {} };
48128
+ if (Array.isArray(n.children) && !(d && typeof d.type === "string"))
48129
+ out = { ...out, children: n.children.map(apply) };
48130
+ return out;
48131
+ };
48132
+ node2 = this.withIds({ ...apply(tree), ...over });
48133
+ }
48134
+ this.warnProps(node2, node2.type, node2.id);
48135
+ this.commit({ op: "insert", parent: p, ord: between(this.lastOrd(p), null), node: node2 });
48136
+ return node2.id;
48137
+ }
48138
+ Update(path, updateData) {
48139
+ updateData = migrateLegacyProps(updateData);
48140
+ const inst = this.splitInstancePath(path);
48141
+ if (inst) {
48142
+ const owner = this.store.get(inst.owner);
48143
+ if (!owner || owner.props.type !== "ref")
48144
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48145
+ const desc = { ...owner.props.descendants ?? {} };
48146
+ this.warnProps(updateData, this.expandedAt(path, {})?.node.type ?? "ref", path);
48147
+ desc[inst.rest] = { ...desc[inst.rest] ?? {}, ...updateData };
48148
+ this.commit({ op: "update", id: owner.id, patch: { descendants: desc } });
48149
+ return;
48150
+ }
48151
+ const row = this.store.get(path);
48152
+ if (!row)
48153
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48154
+ for (const f of ["id", "type", "ref"])
48155
+ if (f in updateData && updateData[f] !== row.props[f])
48156
+ throw new OpRejectedError({ code: "IMMUTABLE_FIELD", field: f });
48157
+ if ("children" in updateData)
48158
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "children", reason: "use Replace to change children" });
48159
+ const { id: _i, type: _t, ref: _r, ...patch } = updateData;
48160
+ if (patch.descendants && row.props.type === "ref")
48161
+ patch.descendants = { ...row.props.descendants ?? {}, ...this.resolveDescendantKeys(row.props.ref, patch.descendants) };
48162
+ this.warnProps({ ...patch, ...row.props.type === "ref" ? { ref: row.props.ref } : {} }, row.props.type, row.id);
48163
+ this.commit({ op: "update", id: row.id, patch });
48164
+ }
48165
+ Replace(path, nodeData) {
48166
+ const inst = this.splitInstancePath(path);
48167
+ if (inst) {
48168
+ const owner = this.store.get(inst.owner);
48169
+ if (!owner || owner.props.type !== "ref")
48170
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48171
+ const node3 = this.withIds(migrateLegacyProps(nodeData));
48172
+ this.warnProps(node3, node3.type, node3.id);
48173
+ const desc = { ...owner.props.descendants ?? {}, [inst.rest]: node3 };
48174
+ this.commit({ op: "update", id: owner.id, patch: { descendants: desc } });
48175
+ return node3.id;
48176
+ }
48177
+ const row = this.store.get(path);
48178
+ if (!row)
48179
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48180
+ const node2 = this.withIds(migrateLegacyProps(nodeData));
48181
+ this.warnProps(node2, node2.type, node2.id);
48182
+ this.commit({ op: "delete", id: row.id });
48183
+ this.commit({ op: "insert", parent: row.parent, ord: row.ord, node: node2 });
48184
+ return node2.id;
48185
+ }
48186
+ Move(path, parent, index) {
48187
+ if (path.includes("/"))
48188
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "path", reason: "instance children cannot be moved; edit the component" });
48189
+ const row = this.store.get(path);
48190
+ if (!row)
48191
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48192
+ const p = parent === undefined ? row.parent : this.parentId(parent);
48193
+ for (let cur = p;cur !== null; cur = this.store.get(cur)?.parent ?? null)
48194
+ if (cur === row.id)
48195
+ throw new OpRejectedError({ code: "CYCLE", id: row.id, parent: p });
48196
+ const siblings = this.store.children(p).filter((s) => s !== row.id);
48197
+ const i = index === undefined ? siblings.length : Math.max(0, Math.min(index, siblings.length));
48198
+ const before = i > 0 ? this.store.get(siblings[i - 1]).ord : null;
48199
+ const after = i < siblings.length ? this.store.get(siblings[i]).ord : null;
48200
+ this.commit({ op: "move", id: row.id, parent: p, ord: between(before, after) });
48201
+ }
48202
+ Delete(path) {
48203
+ if (path === "document")
48204
+ throw new OpRejectedError({ code: "ROOT_PROTECTED" });
48205
+ if (path.includes("/"))
48206
+ throw new OpRejectedError({ code: "INSTANCE_CHILD_DELETE", path });
48207
+ if (!this.store.get(path))
48208
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48209
+ this.commit({ op: "delete", id: path });
48210
+ }
48211
+ SetVariables(variables, replace = false) {
48212
+ const themes = {};
48213
+ for (const [name, def] of Object.entries(variables ?? {})) {
48214
+ if (name.startsWith("$"))
48215
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: name, reason: "variable names must not start with $" });
48216
+ if (!def || typeof def !== "object" || !("type" in def) || !("value" in def))
48217
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: name, reason: "expected { type, value }" });
48218
+ if (Array.isArray(def.value))
48219
+ for (const e of def.value)
48220
+ for (const [axis, v] of Object.entries(e.theme ?? {}))
48221
+ themes[axis] = [...new Set([...themes[axis] ?? [], v])];
48222
+ }
48223
+ this.commit({ op: "setVariables", variables, themes, replace });
48224
+ }
48225
+ GetVariables() {
48226
+ return { variables: this.store.variables(), themes: this.store.themes() };
48227
+ }
48228
+ Get(a, b, c) {
48229
+ let path = null;
48230
+ let visit2 = null;
48231
+ let opts = {};
48232
+ for (const arg of [a, b, c]) {
48233
+ if (typeof arg === "string")
48234
+ path = arg;
48235
+ else if (typeof arg === "function")
48236
+ visit2 = arg;
48237
+ else if (arg && typeof arg === "object")
48238
+ opts = arg;
48239
+ }
48240
+ if (!path && !visit2)
48241
+ throw new Error("Reading the whole document without a visitor would return everything! Pass a visitor or target a specific node.");
48242
+ if (!visit2)
48243
+ return this.readNode(path, opts);
48244
+ const out = [];
48245
+ const roots = path && path !== "document" ? [path] : this.store.children(null);
48246
+ for (const r of roots)
48247
+ this.visitFrom(r, visit2, opts, out);
48248
+ return out;
48249
+ }
48250
+ readNode(path, opts) {
48251
+ if (opts.resolveInstances || opts.resolveVariables || path.includes("/")) {
48252
+ const e = this.expandedAt(path, opts);
48253
+ if (!e)
48254
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48255
+ return toPen(e.node, opts.depth ?? Infinity, !!opts.resolveVariables, opts.resolveInstances !== false || path.includes("/"));
48256
+ }
48257
+ if (!this.store.get(path))
48258
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
48259
+ return subtree(this.store, path, opts.depth ?? Infinity);
48260
+ }
48261
+ expandedCache = new Map;
48262
+ mutations = 0;
48263
+ expandedAt(path, _opts) {
48264
+ const first = path.split("/")[0];
48265
+ const row = this.store.get(first);
48266
+ if (!row)
48267
+ return null;
48268
+ let hit = this.expandedCache.get(row.top);
48269
+ if (!hit || hit.rev !== this.mutations) {
48270
+ const tree = expandNode(this.store, row.top, defaultTheme(this.store.themes()));
48271
+ if (!tree)
48272
+ return null;
48273
+ const index = new Map;
48274
+ const walk = (n) => {
48275
+ index.set(n.path, n);
48276
+ n.children.forEach(walk);
48277
+ };
48278
+ walk(tree);
48279
+ hit = { rev: this.mutations, index };
48280
+ this.expandedCache.set(row.top, hit);
48281
+ if (this.expandedCache.size > 8)
48282
+ this.expandedCache.delete(this.expandedCache.keys().next().value);
48283
+ }
48284
+ const node2 = hit.index.get(path);
48285
+ return node2 ? { node: node2, top: row.top } : null;
48286
+ }
48287
+ layoutOf(top) {
48288
+ let l = this.layoutCache.get(top);
48289
+ if (!l) {
48290
+ l = this.bounds.layout(top);
48291
+ this.layoutCache.set(top, l);
48292
+ if (this.layoutCache.size > 8)
48293
+ this.layoutCache.delete(this.layoutCache.keys().next().value);
48294
+ }
48295
+ return l;
48296
+ }
48297
+ visitFrom(startPath, visit2, opts, out) {
48298
+ const at = this.expandedAt(startPath, opts);
48299
+ if (!at)
48300
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: startPath });
48301
+ const self = this;
48302
+ const withInstances = !!opts.resolveInstances;
48303
+ const walk = (e, parentCtx, depth, index) => {
48304
+ if (opts.depth !== undefined && depth > opts.depth)
48305
+ return;
48306
+ let skip = false;
48307
+ const node2 = toPen(e, 0, !!opts.resolveVariables, withInstances, true);
48308
+ const ctx = {
48309
+ node: node2,
48310
+ parentCtx,
48311
+ depth,
48312
+ index,
48313
+ get bounds() {
48314
+ const b = self.layoutOf(at.top).boxes.get(e.path);
48315
+ return b ? { x: b.x, y: b.y, width: b.width, height: b.height } : { x: 0, y: 0, width: 0, height: 0 };
48316
+ },
48317
+ get problems() {
48318
+ const p = self.layoutOf(at.top).problems.find((q) => q.path === e.path && (q.code === "PARTIALLY_CLIPPED" || q.code === "FULLY_CLIPPED"));
48319
+ return p ? p.code === "FULLY_CLIPPED" ? "fully clipped" : "partially clipped" : undefined;
48320
+ },
48321
+ skipChildren() {
48322
+ skip = true;
48323
+ }
48324
+ };
48325
+ const r = visit2(node2, ctx);
48326
+ if (r !== undefined)
48327
+ out.push(r);
48328
+ if (skip)
48329
+ return;
48330
+ if (e.role === "instance" && !withInstances)
48331
+ return;
48332
+ e.children.forEach((c, i) => walk(c, ctx, depth + 1, i));
48333
+ };
48334
+ walk(at.node, undefined, 0, 0);
48335
+ }
48336
+ level(root, parent, opts) {
48337
+ const withInstances = !!opts.resolveInstances;
48338
+ const conv = (e) => ({
48339
+ node: toPen(e, 0, !!opts.resolveVariables, withInstances, true),
48340
+ path: e.path,
48341
+ more: e.children.length > 0 && !(e.role === "instance" && !withInstances)
48342
+ });
48343
+ if (parent === null) {
48344
+ const roots = root && root !== "document" ? [root] : this.store.children(null);
48345
+ return roots.map((r) => {
48346
+ const at2 = this.expandedAt(r, opts);
48347
+ if (!at2)
48348
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: r });
48349
+ return conv(at2.node);
48350
+ });
48351
+ }
48352
+ const at = this.expandedAt(parent, opts);
48353
+ return at ? at.node.children.map(conv) : [];
48354
+ }
48355
+ tree(path, opts) {
48356
+ const withInstances = !!opts.resolveInstances;
48357
+ const roots = path && path !== "document" ? [path] : this.store.children(null);
48358
+ const out = [];
48359
+ for (const r of roots) {
48360
+ const at = this.expandedAt(r, opts);
48361
+ if (!at)
48362
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: r });
48363
+ const conv = (e, depth) => ({
48364
+ node: toPen(e, 0, !!opts.resolveVariables, withInstances, true),
48365
+ path: e.path,
48366
+ children: e.role === "instance" && !withInstances || opts.depth !== undefined && depth >= opts.depth ? [] : e.children.map((c) => conv(c, depth + 1))
48367
+ });
48368
+ out.push(conv(at.node, 0));
48369
+ }
48370
+ return out;
48371
+ }
48372
+ boundsOf(path) {
48373
+ const first = path.split("/")[0];
48374
+ const row = this.store.get(first);
48375
+ if (!row)
48376
+ return { bounds: { x: 0, y: 0, width: 0, height: 0 } };
48377
+ const l = this.layoutOf(row.top);
48378
+ const b = l.boxes.get(path);
48379
+ const p = l.problems.find((q) => q.path === path && (q.code === "PARTIALLY_CLIPPED" || q.code === "FULLY_CLIPPED"));
48380
+ return {
48381
+ bounds: b ? { x: b.x, y: b.y, width: b.width, height: b.height } : { x: 0, y: 0, width: 0, height: 0 },
48382
+ problems: p ? p.code === "FULLY_CLIPPED" ? "fully clipped" : "partially clipped" : undefined
48383
+ };
48384
+ }
48385
+ FindEmptySpace(input) {
48386
+ const dir = input.direction ?? "right";
48387
+ const pad = input.padding ?? 0;
48388
+ const rects = [];
48389
+ const tops = input.nodeId ? [input.nodeId] : this.store.children(null);
48390
+ for (const t of tops) {
48391
+ const row = this.store.get(t);
48392
+ if (!row)
48393
+ continue;
48394
+ const b = this.layoutOf(row.top).boxes.get(t);
48395
+ if (b)
48396
+ rects.push({ x: b.wx, y: b.wy, width: b.width, height: b.height });
48397
+ }
48398
+ if (!rects.length)
48399
+ return { x: 0, y: 0 };
48400
+ const minX = Math.min(...rects.map((r) => r.x));
48401
+ const minY = Math.min(...rects.map((r) => r.y));
48402
+ const maxX = Math.max(...rects.map((r) => r.x + r.width));
48403
+ const maxY = Math.max(...rects.map((r) => r.y + r.height));
48404
+ if (dir === "right")
48405
+ return { x: maxX + pad, y: minY };
48406
+ if (dir === "left")
48407
+ return { x: minX - pad - input.width, y: minY };
48408
+ if (dir === "bottom")
48409
+ return { x: minX, y: maxY + pad };
48410
+ return { x: minX, y: minY - pad - input.height };
48411
+ }
48412
+ Print(...values) {
48413
+ const line = values.map((v) => typeof v === "string" ? v : JSON.stringify(v)).join(" ");
48414
+ this.rec.printBytes += line.length;
48415
+ if (this.rec.printBytes > LIMITS.printBytes)
48416
+ throw new Error(`SCRIPT_LIMIT: Print output over ${LIMITS.printBytes} bytes`);
48417
+ this.rec.prints.push(line);
48418
+ }
48419
+ TakeScreenshot(nodeIds) {
48420
+ for (const id of nodeIds)
48421
+ if (this.rec.screenshots.length < LIMITS.screenshots)
48422
+ this.rec.screenshots.push(id);
48423
+ }
48424
+ }
48425
+ function toPen(e, depth, _resolved, _instances, shallow = false) {
48426
+ const node2 = { ...e.props, id: e.path, type: e.type };
48427
+ if (!shallow && e.children.length) {
48428
+ if (depth <= 0)
48429
+ node2.children = "...";
48430
+ else
48431
+ node2.children = e.children.map((c) => toPen(c, depth - 1, _resolved, _instances));
48432
+ }
48433
+ return node2;
48434
+ }
48435
+ // ../../packages/canvas/document/src/pen-import.ts
48436
+ var FILE_ID = /^file-/;
48437
+ var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
48438
+ var isImage = (node2) => node2.type === "image" && typeof node2.url === "string";
48439
+ var isRef = (node2) => node2.type === "ref" && typeof node2.ref === "string";
48440
+ function visit2(value, nodeId, fn) {
48441
+ if (Array.isArray(value)) {
48442
+ for (const item of value)
48443
+ visit2(item, nodeId, fn);
48444
+ return;
48445
+ }
48446
+ const node2 = asRecord(value);
48447
+ if (!node2)
48448
+ return;
48449
+ const id = typeof node2.id === "string" ? node2.id : nodeId;
48450
+ fn(node2, id);
48451
+ for (const key of Object.keys(node2))
48452
+ visit2(node2[key], id, fn);
48453
+ }
48454
+ function indexTops(tops) {
48455
+ const owner = new Map;
48456
+ for (const top of tops) {
48457
+ visit2(top, top.id, (node2) => {
48458
+ if (typeof node2.id === "string")
48459
+ owner.set(node2.id, top.id);
48460
+ });
48461
+ }
48462
+ return owner;
48463
+ }
48464
+ var clone = (value) => JSON.parse(JSON.stringify(value));
48465
+ function penImageUrls(nodes) {
48466
+ const urls = [];
48467
+ const seen = new Set;
48468
+ for (const node2 of nodes) {
48469
+ visit2(node2, node2.id, (value) => {
48470
+ if (!isImage(value))
48471
+ return;
48472
+ const url = value.url;
48473
+ if (FILE_ID.test(url) || seen.has(url))
48474
+ return;
48475
+ seen.add(url);
48476
+ urls.push(url);
48477
+ });
48478
+ }
48479
+ return urls;
48480
+ }
48481
+ function planPenImport(doc, opts = {}) {
48482
+ const tops = Array.isArray(doc.children) ? doc.children : [];
48483
+ const warnings = [];
48484
+ const selected = new Set;
48485
+ const added = [];
48486
+ if (opts.frames === undefined) {
48487
+ for (const top of tops)
48488
+ selected.add(top.id);
48489
+ } else {
48490
+ const frames = new Set(opts.frames);
48491
+ for (const id of frames) {
48492
+ if (!tops.some((top) => top.id === id))
48493
+ warnings.push({ code: "FRAME_NOT_FOUND", id });
48494
+ else
48495
+ selected.add(id);
48496
+ }
48497
+ const owner = indexTops(tops);
48498
+ const byId = new Map(tops.map((top) => [top.id, top]));
48499
+ const dangling = new Set;
48500
+ for (let queue = [...selected];queue.length > 0; ) {
48501
+ const top = byId.get(queue.shift());
48502
+ if (!top)
48503
+ continue;
48504
+ visit2(top, top.id, (node2, nodeId) => {
48505
+ if (!isRef(node2))
48506
+ return;
48507
+ const ref = node2.ref;
48508
+ const target = owner.get(ref);
48509
+ if (target === undefined) {
48510
+ const key = `${ref}\x00${nodeId}`;
48511
+ if (dangling.has(key))
48512
+ return;
48513
+ dangling.add(key);
48514
+ warnings.push({ code: "REF_DANGLING", ref, nodeId });
48515
+ return;
48516
+ }
48517
+ if (selected.has(target))
48518
+ return;
48519
+ selected.add(target);
48520
+ queue.push(target);
48521
+ });
48522
+ }
48523
+ for (const top of tops)
48524
+ if (selected.has(top.id) && !frames.has(top.id))
48525
+ added.push(top.id);
48526
+ }
48527
+ const images = opts.images ?? {};
48528
+ const unmapped = new Map;
48529
+ const children = tops.filter((top) => selected.has(top.id)).map((top) => clone(top));
48530
+ for (const node2 of children) {
48531
+ visit2(node2, node2.id, (value, nodeId) => {
48532
+ if (!isImage(value))
48533
+ return;
48534
+ const url = value.url;
48535
+ if (FILE_ID.test(url))
48536
+ return;
48537
+ const fileId = Object.hasOwn(images, url) ? images[url] : undefined;
48538
+ if (typeof fileId === "string") {
48539
+ value.url = fileId;
48540
+ return;
48541
+ }
48542
+ const nodeIds = unmapped.get(url);
48543
+ if (nodeIds) {
48544
+ if (!nodeIds.includes(nodeId))
48545
+ nodeIds.push(nodeId);
48546
+ } else
48547
+ unmapped.set(url, [nodeId]);
48548
+ });
48549
+ }
48550
+ for (const [url, nodeIds] of unmapped)
48551
+ warnings.push({ code: "IMAGE_UNMAPPED", url, nodeIds });
48552
+ return {
48553
+ children,
48554
+ ...doc.variables ? { variables: clone(doc.variables) } : {},
48555
+ ...doc.themes ? { themes: clone(doc.themes) } : {},
48556
+ added,
48557
+ warnings
48558
+ };
48559
+ }
48560
+ // src/commands/canvas-import.ts
48561
+ var CHUNK_CHARS = 1500000;
48562
+ function countNodes(nodes) {
48563
+ let total = 0;
48564
+ const walk = (list) => {
48565
+ for (const node2 of list) {
48566
+ total++;
48567
+ if (Array.isArray(node2.children))
48568
+ walk(node2.children);
48569
+ }
48570
+ };
48571
+ walk(nodes);
48572
+ return total;
48573
+ }
48574
+ function chunkTopNodes(nodes, limit = CHUNK_CHARS) {
48575
+ const chunks = [];
48576
+ let current = [];
48577
+ let size = 0;
48578
+ for (const node2 of nodes) {
48579
+ const length = JSON.stringify(node2).length;
48580
+ if (current.length && size + length > limit) {
48581
+ chunks.push(current);
48582
+ current = [];
48583
+ size = 0;
48584
+ }
48585
+ current.push(node2);
48586
+ size += length;
48587
+ }
48588
+ if (current.length)
48589
+ chunks.push(current);
48590
+ return chunks;
48591
+ }
48592
+ var CONTENT_TYPES = {
48593
+ png: "image/png",
48594
+ jpg: "image/jpeg",
48595
+ jpeg: "image/jpeg",
48596
+ webp: "image/webp",
48597
+ gif: "image/gif",
48598
+ svg: "image/svg+xml",
48599
+ avif: "image/avif"
48600
+ };
48601
+ var contentTypeOf = (url) => CONTENT_TYPES[url.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
48602
+ var viewerUrlFor = (canvasId, env) => `https://console${env === "develop" ? "-develop" : ""}.deepraxis.com/canvases/${canvasId}`;
48603
+ function imageCandidates(url, penFile, roots) {
48604
+ const name = basename2(url);
48605
+ return [...new Set([
48606
+ join5(dirname2(penFile), url),
48607
+ ...roots.map((root) => join5(root, url)),
48608
+ ...roots.map((root) => join5(root, name))
48609
+ ])];
48610
+ }
48611
+ var isMissing = (error) => error?.code === "ENOENT";
48612
+ var reason = (error) => error instanceof Error ? error.message : String(error);
48613
+ async function findImage(url, candidates, ports) {
48614
+ for (const path of candidates) {
48615
+ try {
48616
+ return await ports.readBytes(path);
48617
+ } catch (error) {
48618
+ if (!isMissing(error))
48619
+ throw new UsageError(`cannot read ${path}, needed for image ${url}`, reason(error));
48620
+ }
48621
+ }
48622
+ return;
48623
+ }
48624
+ var warningKey = (warning) => `${warning.code}\x00${"url" in warning ? warning.url : ("id" in warning) ? warning.id : warning.ref}\x00${"nodeId" in warning ? warning.nodeId : ""}`;
48625
+ var warningLine = (warning) => {
48626
+ switch (warning.code) {
48627
+ case "IMAGE_UNMAPPED":
48628
+ return `${warning.code}: ${warning.url} (${warning.nodeIds.length} node(s))`;
48629
+ case "REF_DANGLING":
48630
+ return `${warning.code}: ${warning.ref} at ${warning.nodeId}`;
48631
+ case "FRAME_NOT_FOUND":
48632
+ return `${warning.code}: ${warning.id}`;
48633
+ default:
48634
+ return `${warning.code}: ${warning.url}`;
48635
+ }
48636
+ };
48637
+ async function canvasImport(args, ports) {
48638
+ if (args.canvas !== undefined && !args.yes) {
48639
+ throw new UsageError(`--canvas ${args.canvas} clears every node already on that canvas`, "It is a whole-canvas replacement, not a merge. Re-run with --yes, or omit --canvas to import into a new canvas.");
48640
+ }
48641
+ const file = resolve3(ports.cwd, args.file);
48642
+ let text;
48643
+ try {
48644
+ text = await ports.readFile(file);
48645
+ } catch (error) {
48646
+ throw new UsageError(`cannot read ${args.file}`, isMissing(error) ? "Check the path: `praxis canvas import <file.pen>`." : reason(error));
48647
+ }
48648
+ let doc;
48649
+ try {
48650
+ doc = JSON.parse(text);
48651
+ } catch (error) {
48652
+ throw new UsageError(`${args.file} is not valid JSON`, reason(error));
48653
+ }
48654
+ if (!Array.isArray(doc.children))
48655
+ throw new UsageError(`${args.file} has no children array`, "A .pen document is an object with a children array of top-level nodes.");
48656
+ const frames = args.frames?.filter((frame) => frame !== "");
48657
+ const roots = (args.imageRoots ?? []).map((root) => resolve3(ports.cwd, root));
48658
+ const selection = planPenImport(doc, frames ? { frames } : {});
48659
+ const urls = penImageUrls(selection.children);
48660
+ const found = new Map;
48661
+ const missing = [];
48662
+ for (const url of urls) {
48663
+ const bytes = await findImage(url, imageCandidates(url, file, roots), ports);
48664
+ if (bytes === undefined)
48665
+ missing.push(url);
48666
+ else
48667
+ found.set(url, { bytes, digest: await ports.hash(bytes) });
48668
+ }
48669
+ const images = {};
48670
+ let uploaded = 0;
48671
+ let reused = 0;
48672
+ if (!args.dryRun) {
48673
+ const byDigest = new Map;
48674
+ for (const [url, { bytes, digest }] of found) {
48675
+ const existing = byDigest.get(digest);
48676
+ if (existing !== undefined) {
48677
+ images[url] = existing;
48678
+ reused++;
48679
+ continue;
48680
+ }
48681
+ const id = await ports.upload({ filename: basename2(url), bytes, contentType: contentTypeOf(url) });
48682
+ byDigest.set(digest, id);
48683
+ images[url] = id;
48684
+ uploaded++;
48685
+ }
48686
+ }
48687
+ const plan = planPenImport(doc, { ...frames ? { frames } : {}, images });
48688
+ const chunks = chunkTopNodes(plan.children);
48689
+ const nodes = countNodes(plan.children);
48690
+ const warnings = plan.warnings.filter((warning) => !(args.dryRun && warning.code === "IMAGE_UNMAPPED" && !missing.includes(warning.url)));
48691
+ let canvasId = null;
48692
+ let revision = null;
48693
+ if (!args.dryRun) {
48694
+ canvasId = args.canvas ?? (await ports.rpc("canvas.canvases.create", { name: args.name ?? basename2(file).replace(/\.pen$/, "") })).id;
48695
+ for (let index = 0;index < chunks.length; index++) {
48696
+ const result2 = await ports.rpc("canvas.canvases.import", {
48697
+ canvasId,
48698
+ reset: index === 0,
48699
+ ...index === 0 && plan.variables ? { variables: plan.variables } : {},
48700
+ ...index === 0 && plan.themes ? { themes: plan.themes } : {},
48701
+ children: chunks[index]
48702
+ });
48703
+ revision = result2.revision;
48704
+ const seen = new Set(warnings.map(warningKey));
48705
+ for (const warning of result2.warnings ?? []) {
48706
+ if (seen.has(warningKey(warning)))
48707
+ continue;
48708
+ seen.add(warningKey(warning));
48709
+ warnings.push(warning);
48710
+ }
48711
+ }
48712
+ }
48713
+ const result = {
48714
+ canvas_id: canvasId,
48715
+ viewer_url: canvasId === null ? null : viewerUrlFor(canvasId, ports.env),
48716
+ revision,
48717
+ frames: plan.children.map((node2) => node2.id),
48718
+ added: plan.added,
48719
+ nodes,
48720
+ images: { uploaded, reused, missing },
48721
+ chunks: chunks.length,
48722
+ warnings,
48723
+ dry_run: args.dryRun
48724
+ };
48725
+ ports.emit({ kind: "object", data: result });
48726
+ const name = args.name ?? basename2(file).replace(/\.pen$/, "");
48727
+ const headline = `${plan.children.length} top-level nodes (${plan.added.length} added as component dependencies), ${nodes} nodes, ${chunks.length} chunk(s)`;
48728
+ ports.human([
48729
+ args.dryRun ? `${file}: ${headline}` : `${canvasId} ${name} — ${headline}, ${uploaded} image(s) uploaded${reused ? `, ${reused} reused` : ""}`,
48730
+ ...result.viewer_url ? [result.viewer_url] : [],
48731
+ ...plan.added.length ? [`added as dependencies: ${plan.added.join(", ")}`] : [],
48732
+ `${urls.length - missing.length}/${urls.length} image(s) found locally`,
48733
+ ...missing.length ? [`not found (they will not render): ${missing.join(", ")}`] : [],
48734
+ ...warnings.map(warningLine)
48735
+ ].join(`
48736
+ `));
48737
+ return 0;
48738
+ }
48739
+
46629
48740
  // src/main.ts
46630
48741
  import { spawnSync } from "node:child_process";
46631
48742
 
@@ -46685,13 +48796,13 @@ var groups = [["id"], ["name", "title", "display_name"], ["status", "state"], ["
46685
48796
  var isExtraColumn = (key) => !groups.some((group) => group.includes(key));
46686
48797
  function columnsFor(items) {
46687
48798
  const rows = items.map(record);
46688
- const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
48799
+ const keys2 = [...new Set(rows.flatMap((row) => Object.keys(row)))];
46689
48800
  const chosen = groups.flatMap((group) => {
46690
- const key = group.find((k) => keys.includes(k));
48801
+ const key = group.find((k) => keys2.includes(k));
46691
48802
  return key ? [key] : [];
46692
48803
  });
46693
48804
  const standard = new Set([...groups.flat(), "object"]);
46694
- const extra = keys.filter((key) => !standard.has(key) && rows.some((row) => row[key] !== null && row[key] !== undefined) && rows.every((row) => {
48805
+ const extra = keys2.filter((key) => !standard.has(key) && rows.some((row) => row[key] !== null && row[key] !== undefined) && rows.every((row) => {
46695
48806
  const v = row[key];
46696
48807
  return v === null || v === undefined || typeof v === "boolean" || typeof v === "number" || typeof v === "string" && [...v].length <= 24;
46697
48808
  })).slice(0, 2);
@@ -46746,9 +48857,9 @@ class ModelStream {
46746
48857
  const data = streamData(event), message = record(data.message), response = record(data.response);
46747
48858
  this.chunks.push(streamText(event));
46748
48859
  const choices = Array.isArray(data.choices) ? data.choices : [];
46749
- const reason = choices.map((c) => record(c).finish_reason).find((r) => typeof r === "string" && r) ?? record(data.delta).stop_reason ?? message.stop_reason ?? data.stop_reason ?? record(response.incomplete_details).reason ?? response.status;
46750
- if (typeof reason === "string" && reason)
46751
- this.finishReason = reason;
48860
+ const reason2 = choices.map((c) => record(c).finish_reason).find((r) => typeof r === "string" && r) ?? record(data.delta).stop_reason ?? message.stop_reason ?? data.stop_reason ?? record(response.incomplete_details).reason ?? response.status;
48861
+ if (typeof reason2 === "string" && reason2)
48862
+ this.finishReason = reason2;
46752
48863
  else if (["response.completed", "response.incomplete", "response.failed"].includes(String(data.type)))
46753
48864
  this.finishReason = String(data.type).slice("response.".length);
46754
48865
  for (const usage of [message.usage, data.usage, response.usage]) {
@@ -47183,14 +49294,15 @@ var humanize = (code) => {
47183
49294
  const words = code.toLowerCase().split("_").filter(Boolean).join(" ");
47184
49295
  return words.charAt(0).toUpperCase() + words.slice(1);
47185
49296
  };
47186
- function authHint(source) {
49297
+ function authHint(source, env) {
49298
+ const keyVariable = apiKeyVariable(env);
47187
49299
  switch (source) {
47188
49300
  case "api-key":
47189
- return "The API key from PRAXIS_API_KEY was rejected; check or replace it, or unset it to use `praxis login`.";
49301
+ return `The ${env} API key from ${keyVariable} was rejected; check or replace it, or unset it to use \`praxis login\`.`;
47190
49302
  case "machine-token":
47191
49303
  return "The machine token from PRAXIS_API_TOKEN was rejected (it may have expired); unset it to use `praxis login`, or refresh it.";
47192
49304
  case "login":
47193
- return "Run `praxis login` or set PRAXIS_API_KEY.";
49305
+ return `Run \`praxis login\` or set ${keyVariable}.`;
47194
49306
  }
47195
49307
  }
47196
49308
  function errorInput(error, ctx) {
@@ -47220,7 +49332,7 @@ function errorInput(error, ctx) {
47220
49332
  else if (serverText(problem?.hint))
47221
49333
  hint2 = serverText(problem?.hint);
47222
49334
  else if (authFailure)
47223
- hint2 = authHint(source);
49335
+ hint2 = authHint(source, ctx.env === "develop" ? "develop" : "production");
47224
49336
  else if (status === 404)
47225
49337
  hint2 = ctx.listCommand ? `Check the id; list existing ones with \`${ctx.listCommand}\`` : "Check the id.";
47226
49338
  else if (status === 403)
@@ -47259,7 +49371,7 @@ function startProgress(ctx, write = (text) => writeOutput({ stderr: text })) {
47259
49371
  }
47260
49372
 
47261
49373
  // src/main.ts
47262
- var version = "0.2.2-dev.d73d5e4";
49374
+ var version = "0.2.2-dev.d8d3f52";
47263
49375
  var commands = commandTree(operations);
47264
49376
  var manual = [...workflows.map((w) => w.words), [API_WORD]];
47265
49377
  function route(argv) {
@@ -47296,19 +49408,21 @@ var defaults = {
47296
49408
  stderrIsTTY: Boolean(process.stderr.isTTY),
47297
49409
  columns: process.stdout.columns ?? 100,
47298
49410
  readFile: (path) => readFile3(path, "utf8"),
49411
+ readBytes: (path) => readFile3(path),
49412
+ sha256: async (bytes) => createHash3("sha256").update(bytes).digest("hex"),
47299
49413
  async readStdin() {
47300
49414
  const chunks = [];
47301
49415
  for await (const chunk of process.stdin)
47302
49416
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
47303
49417
  return Buffer.concat(chunks).toString("utf8");
47304
49418
  },
47305
- ask: () => new Promise((resolve3) => {
49419
+ ask: () => new Promise((resolve4) => {
47306
49420
  const input = createInterface({ input: process.stdin, terminal: false });
47307
49421
  input.once("line", (line) => {
47308
- resolve3(/^(y|yes)$/i.test(line.trim()));
49422
+ resolve4(/^(y|yes)$/i.test(line.trim()));
47309
49423
  input.close();
47310
49424
  });
47311
- input.once("close", () => resolve3(false));
49425
+ input.once("close", () => resolve4(false));
47312
49426
  }),
47313
49427
  async openBrowser(url) {
47314
49428
  try {
@@ -47316,27 +49430,27 @@ var defaults = {
47316
49430
  if (!["https:", "http:"].includes(parsed.protocol))
47317
49431
  return;
47318
49432
  const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
47319
- await new Promise((resolve3, reject) => {
49433
+ await new Promise((resolve4, reject) => {
47320
49434
  const child = spawn2(cmd[0], cmd.slice(1), { stdio: "ignore" });
47321
49435
  child.once("error", reject);
47322
- child.once("close", () => resolve3());
49436
+ child.once("close", () => resolve4());
47323
49437
  });
47324
49438
  } catch {}
47325
49439
  },
47326
- wait: (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)),
49440
+ wait: (ms) => new Promise((resolve4) => setTimeout(resolve4, ms)),
47327
49441
  render,
47328
- spawn: (cmd, args, options) => new Promise((resolve3, reject) => {
49442
+ spawn: (cmd, args, options) => new Promise((resolve4, reject) => {
47329
49443
  const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
47330
49444
  child.once("error", reject);
47331
- child.once("close", (code) => resolve3(code ?? 1));
49445
+ child.once("close", (code) => resolve4(code ?? 1));
47332
49446
  }),
47333
- spawnCapture: (cmd, args, options) => new Promise((resolve3, reject) => {
49447
+ spawnCapture: (cmd, args, options) => new Promise((resolve4, reject) => {
47334
49448
  const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
47335
49449
  const chunks = [];
47336
49450
  child.stdout.on("data", (c) => chunks.push(c));
47337
49451
  child.stderr.on("data", (c) => chunks.push(c));
47338
49452
  child.once("error", reject);
47339
- child.once("close", (code) => resolve3({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
49453
+ child.once("close", (code) => resolve4({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
47340
49454
  }),
47341
49455
  has: (bin) => spawnSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" }).status === 0,
47342
49456
  cwd: process.cwd()
@@ -47355,6 +49469,13 @@ var appOptions = {
47355
49469
  { name: "no-wait", type: "boolean", description: "Return as soon as the run exists instead of waiting for a verdict." },
47356
49470
  { name: "repeat", type: "string", description: "How many times each selected case runs (default: 1)." },
47357
49471
  { name: "select", type: "string", repeated: true, description: "Narrow the selection; repeatable. tag:<tag> (a bare word reads as a tag), package:<path>, suite:<path> or file:<path>." }
49472
+ ],
49473
+ "canvas import": [
49474
+ { name: "name", type: "string", description: "Name for the new canvas (default: the file name without .pen)." },
49475
+ { name: "canvas", type: "string", description: "Import into this existing canvas instead of a new one. Whole-canvas replacement: it clears what is already there and requires --yes." },
49476
+ { name: "frames", type: "string", description: "Comma-separated top-level node ids to import. The components they reference come along automatically." },
49477
+ { name: "image-root", type: "string", repeated: true, description: "Directory to resolve image paths against; repeatable. Tried after the .pen file's own directory, then by file name." },
49478
+ { name: "dry-run", type: "boolean", description: "Read the local file and print the plan. No login and no request." }
47358
49479
  ]
47359
49480
  };
47360
49481
  async function main(argv, injected = {}) {
@@ -47363,6 +49484,8 @@ async function main(argv, injected = {}) {
47363
49484
  const write = outputSession((result, context) => ports.render(redact(result, secrets), context));
47364
49485
  if (ports.env.PRAXIS_API_KEY)
47365
49486
  secrets.push(ports.env.PRAXIS_API_KEY);
49487
+ if (ports.env.PRAXIS_API_KEY_DEVELOP)
49488
+ secrets.push(ports.env.PRAXIS_API_KEY_DEVELOP);
47366
49489
  if (ports.env.PRAXIS_API_TOKEN)
47367
49490
  secrets.push(ports.env.PRAXIS_API_TOKEN);
47368
49491
  let ctx = {
@@ -47452,7 +49575,7 @@ Examples:
47452
49575
  return 0;
47453
49576
  }
47454
49577
  const path = ports.tokenPath ?? tokenPath(config.env);
47455
- const store = createTokenStore(config.env, path, selectSecretStore(ports.env, ports.secretStore));
49578
+ const store2 = createTokenStore(config.env, path, selectSecretStore(ports.env, ports.secretStore));
47456
49579
  const wireFetch = async (input, init) => {
47457
49580
  const request = new Request(input, init);
47458
49581
  request.headers.set("User-Agent", `praxis-cli/${version}${ctx.mode === "agent" ? ` agent/${ctx.agentName ?? "unknown"}` : ""}`);
@@ -47462,7 +49585,7 @@ Examples:
47462
49585
  }
47463
49586
  return ports.fetch(request);
47464
49587
  };
47465
- const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store, remember: (s) => {
49588
+ const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store: store2, remember: (s) => {
47466
49589
  secrets.push(s);
47467
49590
  } });
47468
49591
  ctx.credentialSource = auth.source;
@@ -47538,7 +49661,7 @@ Examples:
47538
49661
  return 0;
47539
49662
  }
47540
49663
  const name = selected.words.join(" ");
47541
- const arity = name === "api" ? 2 : name === "org switch" || name === "app create" ? 1 : 0;
49664
+ const arity = name === "api" ? 2 : name === "org switch" || name === "app create" || name === "canvas import" ? 1 : 0;
47542
49665
  if (parsed.positional.length !== arity)
47543
49666
  throw new UsageError(`${name} expects ${arity} positional argument(s)`);
47544
49667
  if (name === "devops deploy plan") {
@@ -47571,12 +49694,12 @@ Examples:
47571
49694
  switch (name) {
47572
49695
  case "login":
47573
49696
  if (flags["no-input"] || quiet)
47574
- throw new UsageError("login requires displaying a device code", "Remove --no-input / --quiet or set PRAXIS_API_KEY for scripts.");
49697
+ throw new UsageError("login requires displaying a device code", "Remove --no-input / --quiet, or set PRAXIS_API_KEY (production) / PRAXIS_API_KEY_DEVELOP (develop) for scripts.");
47575
49698
  ctx.credentialSource = "login";
47576
- await login(config, path, { ...ports, source: auth.source, json: ctx.mode === "json", store, fetch: wireFetch, emit, remember: (s) => secrets.push(s) });
49699
+ await login(config, path, { ...ports, source: auth.source, json: ctx.mode === "json", store: store2, fetch: wireFetch, emit, remember: (s) => secrets.push(s) });
47577
49700
  break;
47578
49701
  case "logout":
47579
- emit({ kind: "message", text: await store.delete() ? "Logged out." : "Not logged in." });
49702
+ emit({ kind: "message", text: await store2.delete() ? "Logged out." : "Not logged in." });
47580
49703
  break;
47581
49704
  case "whoami":
47582
49705
  emit({ kind: "object", data: await whoami(auth, config.env, org) });
@@ -47635,6 +49758,67 @@ Examples:
47635
49758
  cwd: ports.cwd
47636
49759
  });
47637
49760
  }
49761
+ case "canvas import": {
49762
+ const authorize = async () => {
49763
+ const credential = await auth.get(org);
49764
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
49765
+ };
49766
+ const rpc = async (method, params) => {
49767
+ const response = await wireFetch(`${config.apiUrl}/canvas/v1/rpc`, {
49768
+ method: "POST",
49769
+ headers: { ...await authorize(), "content-type": "application/json" },
49770
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
49771
+ signal: AbortSignal.timeout(120000),
49772
+ redirect: "error"
49773
+ });
49774
+ const reply = await response.json();
49775
+ if (!response.ok || reply.error)
49776
+ throw new PraxisError({ code: "CANVAS_RPC_ERROR", message: `${method}: ${reply.error?.message ?? `HTTP ${response.status}`}` });
49777
+ if (!Object.hasOwn(reply, "result"))
49778
+ throw new PraxisError({ code: "INVALID_RESPONSE", message: `${method} answered no result` });
49779
+ return reply.result;
49780
+ };
49781
+ const upload = async ({ filename, bytes, contentType }) => {
49782
+ const signed = await wireFetch(`${config.apiUrl}/file/v1/uploads/signed`, {
49783
+ method: "POST",
49784
+ headers: { ...await authorize(), "content-type": "application/json" },
49785
+ body: JSON.stringify({ filename, bytes: bytes.length, content_type: contentType, purpose: "user_data" }),
49786
+ signal: AbortSignal.timeout(60000),
49787
+ redirect: "error"
49788
+ });
49789
+ const session = await signed.json();
49790
+ if (!signed.ok || typeof session.url !== "string")
49791
+ throw new PraxisError({ code: "UPLOAD_REJECTED", message: `signed upload for ${filename} failed (HTTP ${signed.status})` });
49792
+ const sent = await wireFetch(session.url, { method: "PUT", headers: { "content-type": contentType, "content-length": String(bytes.length) }, body: bytes, signal: AbortSignal.timeout(120000), redirect: "error" });
49793
+ const file = await sent.json();
49794
+ if (!sent.ok || typeof file.id !== "string")
49795
+ throw new PraxisError({ code: "UPLOAD_FAILED", message: `uploading ${filename} failed (HTTP ${sent.status})` });
49796
+ return file.id;
49797
+ };
49798
+ return await canvasImport({
49799
+ file: parsed.positional[0],
49800
+ name: parsed.flags.name?.[0],
49801
+ canvas: parsed.flags.canvas?.[0],
49802
+ frames: typeof parsed.flags.frames?.[0] === "string" ? parsed.flags.frames[0].split(",").map((frame) => frame.trim()).filter(Boolean) : undefined,
49803
+ imageRoots: parsed.flags["image-root"],
49804
+ dryRun: Boolean(parsed.flags["dry-run"]?.[0]),
49805
+ yes: Boolean(flags.yes)
49806
+ }, {
49807
+ readFile: ports.readFile,
49808
+ readBytes: ports.readBytes,
49809
+ hash: ports.sha256,
49810
+ env: config.env,
49811
+ mode: ctx.mode,
49812
+ emit,
49813
+ cwd: ports.cwd,
49814
+ rpc,
49815
+ upload,
49816
+ human: (text) => {
49817
+ if (ctx.mode === "human")
49818
+ emit({ kind: "message", channel: "stdout", text });
49819
+ }
49820
+ });
49821
+ }
47638
49822
  case "api": {
47639
49823
  const method = parsed.positional[0];
47640
49824
  if (!HTTP_METHOD.test(method))