@gravity-rail/cli 0.53.0 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gr.js CHANGED
@@ -15,12 +15,22 @@ import { stdout, stdin } from 'process';
15
15
  import { writeFile, readFile } from 'fs/promises';
16
16
  import { EventEmitter } from 'events';
17
17
 
18
- createRequire(import.meta.url);
18
+ const require$1 = createRequire(import.meta.url);
19
19
  const __filename$1 = fileURLToPath(import.meta.url);
20
20
  dirname(__filename$1);
21
21
 
22
+ var __create = Object.create;
22
23
  var __defProp = Object.defineProperty;
24
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
23
25
  var __getOwnPropNames = Object.getOwnPropertyNames;
26
+ var __getProtoOf = Object.getPrototypeOf;
27
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
28
+ var __require = /* @__PURE__ */ ((x) => typeof require$1 !== "undefined" ? require$1 : typeof Proxy !== "undefined" ? new Proxy(x, {
29
+ get: (a, b) => (typeof require$1 !== "undefined" ? require$1 : a)[b]
30
+ }) : x)(function(x) {
31
+ if (typeof require$1 !== "undefined") return require$1.apply(this, arguments);
32
+ throw Error('Dynamic require of "' + x + '" is not supported');
33
+ });
24
34
  var __esm = (fn, res, err) => function __init() {
25
35
  if (err) throw err[0];
26
36
  try {
@@ -29,10 +39,33 @@ var __esm = (fn, res, err) => function __init() {
29
39
  throw err = [e], e;
30
40
  }
31
41
  };
42
+ var __commonJS = (cb, mod) => function __require2() {
43
+ try {
44
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
45
+ } catch (e) {
46
+ throw mod = 0, e;
47
+ }
48
+ };
32
49
  var __export = (target, all) => {
33
50
  for (var name in all)
34
51
  __defProp(target, name, { get: all[name], enumerable: true });
35
52
  };
53
+ var __copyProps = (to, from, except, desc) => {
54
+ if (from && typeof from === "object" || typeof from === "function") {
55
+ for (let key of __getOwnPropNames(from))
56
+ if (!__hasOwnProp.call(to, key) && key !== except)
57
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
58
+ }
59
+ return to;
60
+ };
61
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
62
+ // If the importer is in node compatibility mode or this is not an ESM
63
+ // file that has been converted to a CommonJS file using a Babel-
64
+ // compatible transform (i.e. "__esModule" has not been set), then set
65
+ // "default" to the CommonJS "module.exports" for node compatibility.
66
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
67
+ mod
68
+ ));
36
69
 
37
70
  // src/lib/errors.ts
38
71
  function handleError(err) {
@@ -3131,7 +3164,7 @@ var init_libphonenumber_js = __esm({
3131
3164
  }
3132
3165
  });
3133
3166
 
3134
- // ../sdk/dist/chunk-6F4YJJKQ.js
3167
+ // ../sdk/dist/chunk-BF4MOZZO.js
3135
3168
  function resourceWorkflowsPath(wid, ...segments) {
3136
3169
  const tail = segments.map((segment) => encodeURIComponent(String(segment))).join("/");
3137
3170
  const base = `w/${encodeURIComponent(wid)}/resource-workflows`;
@@ -3398,6 +3431,7 @@ function createApiModules(apiKey, baseUrl3, customFetch) {
3398
3431
  qualifications: new QualificationsApi(apiKey, baseUrl3, customFetch),
3399
3432
  personas: new PersonasApi(apiKey, baseUrl3, customFetch),
3400
3433
  metrics: new MetricsApi(apiKey, baseUrl3, customFetch),
3434
+ dataReports: new DataReportsApi(apiKey, baseUrl3, customFetch),
3401
3435
  queries: new QueriesApi(apiKey, baseUrl3, customFetch),
3402
3436
  reports: new ReportsApi(apiKey, baseUrl3, customFetch),
3403
3437
  resourceWorkflows: new ResourceWorkflowsApi(apiKey, baseUrl3, customFetch),
@@ -3720,6 +3754,7 @@ function bindMembersMethods(target, members) {
3720
3754
  }
3721
3755
  function bindWorkspacesMethods(target, workspaces, signupRequests) {
3722
3756
  target.getWorkspaces = workspaces.getWorkspaces.bind(workspaces);
3757
+ target.getOrganizationWorkspacePages = workspaces.getOrganizationWorkspacePages.bind(workspaces);
3723
3758
  target.getDeviceAdmissibleWorkspaces = workspaces.getDeviceAdmissibleWorkspaces.bind(workspaces);
3724
3759
  target.getPublicWorkspaces = workspaces.getPublicWorkspaces.bind(workspaces);
3725
3760
  target.getWorkspace = workspaces.getWorkspace.bind(workspaces);
@@ -3915,6 +3950,7 @@ function bindFilesMethods(target, files) {
3915
3950
  target.convertFile = files.convertFile.bind(files);
3916
3951
  target.generateFileUploadUrl = files.generateFileUploadUrl.bind(files);
3917
3952
  target.getFolders = files.getFolders.bind(files);
3953
+ target.getFolderChildren = files.getFolderChildren.bind(files);
3918
3954
  target.getFolder = files.getFolder.bind(files);
3919
3955
  target.createFolder = files.createFolder.bind(files);
3920
3956
  target.updateFolder = files.updateFolder.bind(files);
@@ -3995,6 +4031,7 @@ function bindWorkflowsMethods(target, workflows, workflowNotes, voice, superviso
3995
4031
  target.getWorkflowsActivityBatch = workflows.getWorkflowsActivityBatch.bind(workflows);
3996
4032
  target.getWorkflowDiagram = workflows.getWorkflowDiagram.bind(workflows);
3997
4033
  target.getWorkflowOutline = workflows.getWorkflowOutline.bind(workflows);
4034
+ target.getWorkflowsOutlineBatch = workflows.getWorkflowsOutlineBatch.bind(workflows);
3998
4035
  target.createWorkflow = workflows.createWorkflow.bind(workflows);
3999
4036
  target.updateWorkflow = workflows.updateWorkflow.bind(workflows);
4000
4037
  target.getWorkflowDeletionPreview = workflows.getWorkflowDeletionPreview.bind(workflows);
@@ -4008,6 +4045,7 @@ function bindWorkflowsMethods(target, workflows, workflowNotes, voice, superviso
4008
4045
  target.getTaskChats = workflows.getTaskChats.bind(workflows);
4009
4046
  target.getWorkflowConfigValidation = workflows.getWorkflowConfigValidation.bind(workflows);
4010
4047
  target.getWorkflowPromptClassifications = workflows.getWorkflowPromptClassifications.bind(workflows);
4048
+ target.reviewWorkflowPromptClassifications = workflows.reviewWorkflowPromptClassifications.bind(workflows);
4011
4049
  target.getWorkflowNotes = workflowNotes.getWorkflowNotes.bind(workflowNotes);
4012
4050
  target.createWorkflowNote = workflowNotes.createWorkflowNote.bind(workflowNotes);
4013
4051
  target.updateWorkflowNote = workflowNotes.updateWorkflowNote.bind(workflowNotes);
@@ -4204,6 +4242,12 @@ function bindAppsMethods(target, apps, builders, inquiries, oauth, oauthConnecti
4204
4242
  target.deleteInquiry = inquiries.deleteInquiry.bind(inquiries);
4205
4243
  target.exportInquiriesCsv = inquiries.exportInquiriesCsv.bind(inquiries);
4206
4244
  target.authorize = oauth.authorize.bind(oauth);
4245
+ target.denyAuthorization = oauth.denyAuthorization.bind(oauth);
4246
+ target.getOAuthConsentClient = oauth.getOAuthConsentClient.bind(oauth);
4247
+ target.getMcpConsentTargets = oauth.getMcpConsentTargets.bind(oauth);
4248
+ target.listMcpGrants = oauth.listMcpGrants.bind(oauth);
4249
+ target.narrowMcpGrant = oauth.narrowMcpGrant.bind(oauth);
4250
+ target.revokeMcpGrant = oauth.revokeMcpGrant.bind(oauth);
4207
4251
  target.exchangeOAuthToken = oauth.exchangeOAuthToken.bind(oauth);
4208
4252
  target.getAvailableScopes = oauth.getAvailableScopes.bind(oauth);
4209
4253
  target.getOAuthConnectionStatus = oauthConnections.getConnectionStatus.bind(oauthConnections);
@@ -4301,6 +4345,8 @@ function bindIntegrationsMethods(target, mondayIntegration, discordBots, slackAp
4301
4345
  target.fhirGetEncounterSyncRuns = fhirConnections.fhirGetEncounterSyncRuns.bind(fhirConnections);
4302
4346
  target.fhirRefreshEncounterPatient = fhirConnections.fhirRefreshEncounterPatient.bind(fhirConnections);
4303
4347
  target.fhirBackfillEncounterSync = fhirConnections.fhirBackfillEncounterSync.bind(fhirConnections);
4348
+ target.fhirStartOnboardingImport = fhirConnections.fhirStartOnboardingImport.bind(fhirConnections);
4349
+ target.fhirGetOnboardingImportStatus = fhirConnections.fhirGetOnboardingImportStatus.bind(fhirConnections);
4304
4350
  target.configurePatientSync = patientSyncConnections.configurePatientSync.bind(patientSyncConnections);
4305
4351
  target.getPatientSyncStatus = patientSyncConnections.getPatientSyncStatus.bind(patientSyncConnections);
4306
4352
  target.deletePatientSyncConnection = patientSyncConnections.deletePatientSyncConnection.bind(patientSyncConnections);
@@ -4387,6 +4433,7 @@ function bindIntegrationsMethods(target, mondayIntegration, discordBots, slackAp
4387
4433
  target.listAvailableAppConnections = appConnections.listAvailableAppConnections.bind(appConnections);
4388
4434
  target.listAppConnections = appConnections.listAppConnections.bind(appConnections);
4389
4435
  target.enablePlatformApp = appConnections.enablePlatformApp.bind(appConnections);
4436
+ target.configureZendeskConnection = appConnections.configureZendeskConnection.bind(appConnections);
4390
4437
  target.getPlatformApp = appConnections.getPlatformApp.bind(appConnections);
4391
4438
  target.updatePlatformApp = appConnections.updatePlatformApp.bind(appConnections);
4392
4439
  target.deletePlatformApp = appConnections.deletePlatformApp.bind(appConnections);
@@ -4435,6 +4482,7 @@ function bindOrgMethods(target, org) {
4435
4482
  target.getVoiceTrustProducts = org.getVoiceTrustProducts.bind(org);
4436
4483
  target.syncVoiceTrustProducts = org.syncVoiceTrustProducts.bind(org);
4437
4484
  target.createOrganizationWorkspace = org.createOrganizationWorkspace.bind(org);
4485
+ target.getOrganizationWorkspaces = org.getOrganizationWorkspaces.bind(org);
4438
4486
  target.getOrganizationWorkspace = org.getOrganizationWorkspace.bind(org);
4439
4487
  target.updateOrganizationWorkspace = org.updateOrganizationWorkspace.bind(org);
4440
4488
  target.getOrgBillingCustomer = org.getOrgBillingCustomer.bind(org);
@@ -4444,7 +4492,20 @@ function bindOrgMethods(target, org) {
4444
4492
  target.updateOrganizationMember = org.updateOrganizationMember.bind(org);
4445
4493
  target.listOrgWebhookEndpoints = org.listOrgWebhookEndpoints.bind(org);
4446
4494
  target.getOrgWebhookEndpoint = org.getOrgWebhookEndpoint.bind(org);
4495
+ target.createOrgWebhookEndpoint = org.createOrgWebhookEndpoint.bind(org);
4447
4496
  target.updateOrgWebhookEndpoint = org.updateOrgWebhookEndpoint.bind(org);
4497
+ target.listOrgWebhookEndpointDeliveries = org.listOrgWebhookEndpointDeliveries.bind(org);
4498
+ target.replayOrgWebhookDelivery = org.replayOrgWebhookDelivery.bind(org);
4499
+ target.discardPendingOrgWebhookDeliveries = org.discardPendingOrgWebhookDeliveries.bind(org);
4500
+ target.getOrgWebhookEndpointCoverage = org.getOrgWebhookEndpointCoverage.bind(org);
4501
+ target.testOrgWebhookEndpoint = org.testOrgWebhookEndpoint.bind(org);
4502
+ target.listWorkspaceLabels = org.listWorkspaceLabels.bind(org);
4503
+ target.createWorkspaceLabel = org.createWorkspaceLabel.bind(org);
4504
+ target.updateWorkspaceLabel = org.updateWorkspaceLabel.bind(org);
4505
+ target.deleteWorkspaceLabel = org.deleteWorkspaceLabel.bind(org);
4506
+ target.getWorkspaceLabels = org.getWorkspaceLabels.bind(org);
4507
+ target.setWorkspaceLabels = org.setWorkspaceLabels.bind(org);
4508
+ target.previewWorkspaceScope = org.previewWorkspaceScope.bind(org);
4448
4509
  }
4449
4510
  function bindPronunciationsMethods(target, pronunciations) {
4450
4511
  target.getPronunciationEntries = pronunciations.getPronunciationEntries.bind(pronunciations);
@@ -4583,6 +4644,9 @@ function bindMetricsMethods(target, metrics) {
4583
4644
  target.getMetricSeries = metrics.getMetricSeries.bind(metrics);
4584
4645
  target.computeChatMetrics = metrics.computeChatMetrics.bind(metrics);
4585
4646
  }
4647
+ function bindDataReportsMethods(target, dataReports) {
4648
+ target.previewDataReport = dataReports.previewDataReport.bind(dataReports);
4649
+ }
4586
4650
  function bindQueriesMethods(target, queries) {
4587
4651
  target.getQueryFields = queries.getQueryFields.bind(queries);
4588
4652
  target.validateQuery = queries.validateQuery.bind(queries);
@@ -4652,9 +4716,9 @@ function getRevisionState(workflow, revision) {
4652
4716
  state: revision?.publishedAt != null ? "published" : "draft"
4653
4717
  };
4654
4718
  }
4655
- var AbilitiesApi, ResourceWorkflowsApi, BundlesApi, InstallationsApi, AccessGrantsApi, AgentTasksApi, AgentsApi, AIModelsApi, ApiKeysApi, AppsApi, AssignmentsApi, VoiceApi, AuthApi, BuildersApi, CalendarsApi, CallsApi, CELApi, ChatsApi, ConfluenceApi, CustomToolkitsApi, DataTypesApi, DiscordBotsApi, SlackAppsApi, EventsApi, FeaturesApi, FhirConnectionsApi, InboundFaxStatus, DocumoFaxApi, HealthieApi, FilesApi, InboxesApi, InquiriesApi, AppConnectionsApi, McpServersApi, MemberImportValidationError, MembersApi, MondayIntegrationApi, NotificationRulesApi, OperatorApi, OrgApi, OAuthConnectionsApi, OAuthApi, PhoneNumbersApi, PronunciationsApi, PromptsApi, PersonasApi, QueriesApi, QualificationsApi, ReportsApi, RoutingRulesApi, SalesforceApi, ConnectionSyncApi, HubspotApi, SitesApi, SubscriptionsApi, SupportRequestsApi, CustomersApi, ResellersApi, SupervisorsApi, TasksApi, TemplatesApi, ToolkitsApi, JourneysApi, WorkflowsApi, WorkflowNotesApi, EventRuleObjectType, EventRuleEventType, EventRuleActionType, DriverMode, MEMBER_RELATIONSHIP_KINDS, WorkspaceInvitationsApi, WorkspacesApi, DashboardsApi, DevicesApi, TeamsAppsApi, ExperimentsApi, PatientSyncConnectionsApi, ActivityApi, MotdApi, InterventionRequestsApi, MetricsApi, ProjectsApi, TrackedLinksApi, WORKSPACE_METHOD_NAMES, WORKSPACE_METHOD_NAME_SET, GravityRailClient, WIDGET_SLUGS, CHAT_TYPES, BUILTIN_ASSISTANT_CHAT_TYPES, MEMBER_AGENT_CHAT_TYPES, ActivityGrain, ActivityGroupBy, ActivityOpenItemOrder, ActivityWindowBasis;
4656
- var init_chunk_6F4YJJKQ = __esm({
4657
- "../sdk/dist/chunk-6F4YJJKQ.js"() {
4719
+ var AbilitiesApi, ResourceWorkflowsApi, BundlesApi, InstallationsApi, AccessGrantsApi, AgentTasksApi, AgentsApi, AIModelsApi, ApiKeysApi, AppsApi, AssignmentsApi, VoiceApi, AuthApi, BuildersApi, CalendarsApi, CallsApi, CELApi, ChatsApi, ConfluenceApi, CustomToolkitsApi, DataTypesApi, DiscordBotsApi, SlackAppsApi, EventsApi, FeaturesApi, FhirConnectionsApi, InboundFaxStatus, DocumoFaxApi, HealthieApi, FilesApi, InboxesApi, InquiriesApi, AppConnectionsApi, McpServersApi, MemberImportValidationError, MembersApi, MondayIntegrationApi, NotificationRulesApi, OperatorApi, OrgApi, OAuthConnectionsApi, OAuthApi, PhoneNumbersApi, PronunciationsApi, PromptsApi, PersonasApi, QueriesApi, QualificationsApi, ReportsApi, RoutingRulesApi, SalesforceApi, ConnectionSyncApi, HubspotApi, SitesApi, SubscriptionsApi, SupportRequestsApi, CustomersApi, ResellersApi, SupervisorsApi, TasksApi, TemplatesApi, ToolkitsApi, JourneysApi, WorkflowsApi, WorkflowNotesApi, EventRuleObjectType, EventRuleEventType, EventRuleActionType, DriverMode, MEMBER_RELATIONSHIP_KINDS, WorkspaceInvitationsApi, WorkspacesApi, DashboardsApi, DevicesApi, TeamsAppsApi, ExperimentsApi, PatientSyncConnectionsApi, ActivityApi, MotdApi, InterventionRequestsApi, MetricsApi, DataReportsApi, ProjectsApi, TrackedLinksApi, WORKSPACE_METHOD_NAMES, WORKSPACE_METHOD_NAME_SET, GravityRailClient, WIDGET_SLUGS, CHAT_TYPES, BUILTIN_ASSISTANT_CHAT_TYPES, MEMBER_AGENT_CHAT_TYPES, ActivityGrain, ActivityGroupBy, ActivityOpenItemOrder, ActivityWindowBasis;
4720
+ var init_chunk_BF4MOZZO = __esm({
4721
+ "../sdk/dist/chunk-BF4MOZZO.js"() {
4658
4722
  init_chunk_GCN4OMYU();
4659
4723
  init_libphonenumber_js();
4660
4724
  AbilitiesApi = class extends BaseApiClient {
@@ -7970,6 +8034,36 @@ var init_chunk_6F4YJJKQ = __esm({
7970
8034
  { method: "POST", body: JSON.stringify(data) }
7971
8035
  );
7972
8036
  }
8037
+ /**
8038
+ * Start, resume, override or preview (dry run) an athenahealth connection's
8039
+ * onboarding import. The body is exactly the three mode flags; the server
8040
+ * traverses the connection's configured department/status pairs. Returns
8041
+ * 202 with the Temporal workflow and run ids. Requires `workspace:admin`.
8042
+ */
8043
+ async fhirStartOnboardingImport(wid, connectionId, data = {}) {
8044
+ const body = {
8045
+ dryRun: data.dryRun ?? false,
8046
+ resume: data.resume ?? false,
8047
+ override: data.override ?? false
8048
+ };
8049
+ return this.fetch(
8050
+ `w/${wid}/app-connections/fhir/connections/${connectionId}/onboarding-import`,
8051
+ {
8052
+ method: "POST",
8053
+ body: JSON.stringify(body)
8054
+ }
8055
+ );
8056
+ }
8057
+ /**
8058
+ * Read an athenahealth connection's onboarding-import progress (durable,
8059
+ * approximate totals) and its known Temporal execution. GET-only: never
8060
+ * starts or resumes work. Requires `workspace:admin`.
8061
+ */
8062
+ async fhirGetOnboardingImportStatus(wid, connectionId) {
8063
+ return this.fetch(
8064
+ `w/${wid}/app-connections/fhir/connections/${connectionId}/onboarding-import`
8065
+ );
8066
+ }
7973
8067
  };
7974
8068
  InboundFaxStatus = {
7975
8069
  pending: "pending",
@@ -8172,8 +8266,8 @@ var init_chunk_6F4YJJKQ = __esm({
8172
8266
  * Download one file's bytes via GET ``.../files/{id}/contents/{filename}``.
8173
8267
  *
8174
8268
  * Uses this client's base URL (FastAPI on the app, same-origin ``/api/v2``
8175
- * on scoped site sessions) so the payload does not transit the Next.js
8176
- * ``/api/w/.../files/...`` Lambda proxy, which 500s above the 6MB sync cap.
8269
+ * on scoped site sessions). The Next.js ``/api/w/.../files/...`` route
8270
+ * redirects to this same contents path; calling it directly skips the hop.
8177
8271
  */
8178
8272
  async downloadFileContents(wid, id, filename) {
8179
8273
  const response = await this.fetchRaw(
@@ -8257,9 +8351,9 @@ var init_chunk_6F4YJJKQ = __esm({
8257
8351
  );
8258
8352
  }
8259
8353
  /**
8260
- * Same-origin proxy URL for a version's raw contents. Mirrors the shape of
8261
- * `FileResponse.cdnUrl`: an app-relative Next.js route that authenticates
8262
- * via session cookies and forwards to the versioned contents endpoint.
8354
+ * Same-origin URL for a version's raw contents. The Next.js route
8355
+ * requires a session and redirects to the versioned FastAPI contents
8356
+ * endpoint. Mirrors the shape of `FileResponse.cdnUrl`.
8263
8357
  */
8264
8358
  getFileVersionContentsUrl(wid, fileId, versionNumber) {
8265
8359
  return `/api/w/${wid}/files/${fileId}/versions/${versionNumber}/contents`;
@@ -8291,6 +8385,19 @@ var init_chunk_6F4YJJKQ = __esm({
8291
8385
  const parentId = typeof parentIdOrOpts === "number" ? parentIdOrOpts : parentIdOrOpts.parentId;
8292
8386
  return this.fetch(`w/${wid}/folders?parent_id=${parentId}`);
8293
8387
  }
8388
+ /**
8389
+ * Readable children of many parents in one request.
8390
+ *
8391
+ * Every id comes back as a key. A parent with no readable children maps to
8392
+ * an empty list. The server accepts at most 100 ids per call.
8393
+ */
8394
+ async getFolderChildren(wid, parentIds) {
8395
+ const params = new URLSearchParams();
8396
+ for (const parentId of parentIds) {
8397
+ params.append("parent_ids", String(parentId));
8398
+ }
8399
+ return this.fetch(`w/${wid}/folders/children?${params}`);
8400
+ }
8294
8401
  /** Get a single folder by ID. */
8295
8402
  async getFolder(wid, id) {
8296
8403
  return this.fetch(`w/${wid}/folders/${id}`);
@@ -8698,6 +8805,19 @@ var init_chunk_6F4YJJKQ = __esm({
8698
8805
  body: JSON.stringify(data)
8699
8806
  });
8700
8807
  }
8808
+ /**
8809
+ * Create a public Zendesk Help Center connection with its sync paused.
8810
+ *
8811
+ * The acting Member becomes the sync owner. Later settings edits,
8812
+ * pause/resume, Sync now and run history use the generic connection-sync
8813
+ * methods (`updateConnectionSyncConfig`, `startSyncRun`, `getSyncRuns`).
8814
+ */
8815
+ async configureZendeskConnection(wid, data) {
8816
+ return this.fetch(`w/${wid}/app-connections/zendesk/configure`, {
8817
+ method: "POST",
8818
+ body: JSON.stringify(data)
8819
+ });
8820
+ }
8701
8821
  /**
8702
8822
  * Get platform app connection details by UUID.
8703
8823
  */
@@ -10709,6 +10829,45 @@ var init_chunk_6F4YJJKQ = __esm({
10709
10829
  `o/${orgIdOrUuid}/webhooks/${endpointUuid}/deliveries?limit=${limit}`
10710
10830
  );
10711
10831
  }
10832
+ /**
10833
+ * Requeue one dead-lettered or expired delivery on its existing row.
10834
+ *
10835
+ * The response is identifiers only. The drain signs a fresh timestamp
10836
+ * when it sends; this call does not POST to the receiver.
10837
+ */
10838
+ async replayOrgWebhookDelivery(orgIdOrUuid, endpointUuid, deliveryId) {
10839
+ return this.fetch(
10840
+ `o/${orgIdOrUuid}/webhooks/${endpointUuid}/deliveries/${deliveryId}/replay`,
10841
+ {
10842
+ method: "POST",
10843
+ body: JSON.stringify({})
10844
+ }
10845
+ );
10846
+ }
10847
+ /**
10848
+ * Expire every pending delivery of a paused or disabled endpoint, so a
10849
+ * resume does not re-send a held backlog the receiver keeps rejecting.
10850
+ * Refused with 409 while the endpoint is active. Dead-lettered rows
10851
+ * are untouched; expired rows stay replayable one at a time.
10852
+ */
10853
+ async discardPendingOrgWebhookDeliveries(orgIdOrUuid, endpointUuid) {
10854
+ return this.fetch(
10855
+ `o/${orgIdOrUuid}/webhooks/${endpointUuid}/deliveries/discard-pending`,
10856
+ {
10857
+ method: "POST",
10858
+ body: JSON.stringify({})
10859
+ }
10860
+ );
10861
+ }
10862
+ /**
10863
+ * Which covered workspaces have the subscribed Forms opted in
10864
+ * (`webhookEventsEnabled`). Record events only.
10865
+ */
10866
+ async getOrgWebhookEndpointCoverage(orgIdOrUuid, endpointUuid) {
10867
+ return this.fetch(
10868
+ `o/${orgIdOrUuid}/webhooks/${endpointUuid}/coverage`
10869
+ );
10870
+ }
10712
10871
  /**
10713
10872
  * A representative delivery body for one event type — what the test-send
10714
10873
  * editor is prefilled with, and the same builder the public event catalog
@@ -10770,6 +10929,57 @@ var init_chunk_6F4YJJKQ = __esm({
10770
10929
  method: "DELETE"
10771
10930
  });
10772
10931
  }
10932
+ // =========================================================================
10933
+ // Workspace labels — the organization's own taxonomy of its workspaces
10934
+ // =========================================================================
10935
+ /** Every label of the organization, with workspace and webhook-selector counts. */
10936
+ async listWorkspaceLabels(orgIdOrUuid) {
10937
+ return this.fetch(`o/${orgIdOrUuid}/workspace-labels`);
10938
+ }
10939
+ async createWorkspaceLabel(orgIdOrUuid, data) {
10940
+ return this.fetch(`o/${orgIdOrUuid}/workspace-labels`, {
10941
+ method: "POST",
10942
+ body: JSON.stringify(data)
10943
+ });
10944
+ }
10945
+ /** Rename or recolor a label. The slug never changes. */
10946
+ async updateWorkspaceLabel(orgIdOrUuid, labelUuid, data) {
10947
+ return this.fetch(`o/${orgIdOrUuid}/workspace-labels/${labelUuid}`, {
10948
+ method: "PATCH",
10949
+ body: JSON.stringify(data)
10950
+ });
10951
+ }
10952
+ /** Delete a label. Refused (409) while a webhook label selector requires it. */
10953
+ async deleteWorkspaceLabel(orgIdOrUuid, labelUuid) {
10954
+ return this.fetch(`o/${orgIdOrUuid}/workspace-labels/${labelUuid}`, {
10955
+ method: "DELETE"
10956
+ });
10957
+ }
10958
+ /**
10959
+ * Which workspaces a webhook scope (explicit workspaces plus a label
10960
+ * selector) would cover right now. Both empty means the whole organization.
10961
+ */
10962
+ async previewWorkspaceScope(orgIdOrUuid, data) {
10963
+ return this.fetch(
10964
+ `o/${orgIdOrUuid}/workspace-labels/preview-scope`,
10965
+ { method: "POST", body: JSON.stringify(data) }
10966
+ );
10967
+ }
10968
+ async getWorkspaceLabels(orgIdOrUuid, workspaceUuid) {
10969
+ return this.fetch(
10970
+ `o/${orgIdOrUuid}/workspaces/${workspaceUuid}/labels`
10971
+ );
10972
+ }
10973
+ /**
10974
+ * Replace a workspace's labels with exactly `data.labels` (slugs). A slug the
10975
+ * organization has not used before creates that label.
10976
+ */
10977
+ async setWorkspaceLabels(orgIdOrUuid, workspaceUuid, data) {
10978
+ return this.fetch(
10979
+ `o/${orgIdOrUuid}/workspaces/${workspaceUuid}/labels`,
10980
+ { method: "PUT", body: JSON.stringify(data) }
10981
+ );
10982
+ }
10773
10983
  };
10774
10984
  OAuthConnectionsApi = class extends BaseApiClient {
10775
10985
  async getConnectionStatus(providerSlug) {
@@ -10800,6 +11010,39 @@ var init_chunk_6F4YJJKQ = __esm({
10800
11010
  body: JSON.stringify(request)
10801
11011
  });
10802
11012
  }
11013
+ async denyAuthorization(request) {
11014
+ return this.fetch("oauth/authorize/deny", {
11015
+ method: "POST",
11016
+ body: JSON.stringify(request)
11017
+ });
11018
+ }
11019
+ async getOAuthConsentClient(clientId, redirectUri, resource) {
11020
+ const params = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri });
11021
+ if (resource) params.set("resource", resource);
11022
+ return this.fetch(`oauth/authorize/client?${params.toString()}`);
11023
+ }
11024
+ /** The organizations and workspaces the MCP consent screen may offer. */
11025
+ async getMcpConsentTargets(clientId) {
11026
+ const params = new URLSearchParams({ client_id: clientId });
11027
+ return this.fetch(`oauth/authorize/mcp-targets?${params.toString()}`);
11028
+ }
11029
+ /** The signed-in account's MCP grants. */
11030
+ async listMcpGrants() {
11031
+ return this.fetch("oauth/mcp-grants");
11032
+ }
11033
+ /** Remove organizations or workspaces from one MCP grant. */
11034
+ async narrowMcpGrant(grantId, removeTargetIds) {
11035
+ return this.fetch(`oauth/mcp-grants/${encodeURIComponent(grantId)}`, {
11036
+ method: "PATCH",
11037
+ body: JSON.stringify({ removeTargetIds })
11038
+ });
11039
+ }
11040
+ /** Revoke one MCP grant. */
11041
+ async revokeMcpGrant(grantId) {
11042
+ return this.fetch(`oauth/mcp-grants/${encodeURIComponent(grantId)}`, {
11043
+ method: "DELETE"
11044
+ });
11045
+ }
10803
11046
  async exchangeOAuthToken(request) {
10804
11047
  const formData = new URLSearchParams();
10805
11048
  formData.append("grant_type", request.grant_type);
@@ -13171,6 +13414,20 @@ var init_chunk_6F4YJJKQ = __esm({
13171
13414
  async getWorkflowOutline(wid, id) {
13172
13415
  return this.fetch(`w/${wid}/workflows/${id}/outline`);
13173
13416
  }
13417
+ /**
13418
+ * Outlines for many Workflows in one request. The same shape as
13419
+ * {@link getWorkflowOutline}, keyed by workflow id. Ids the caller cannot
13420
+ * use, and outlines that cannot be read, are absent.
13421
+ *
13422
+ * The route accepts at most 100 ids. Callers with a longer list chunk.
13423
+ */
13424
+ async getWorkflowsOutlineBatch(wid, workflowIds) {
13425
+ const params = new URLSearchParams();
13426
+ params.set("workflowIds", workflowIds.join(","));
13427
+ return this.fetch(
13428
+ `w/${wid}/workflows/outline/batch?${params.toString()}`
13429
+ );
13430
+ }
13174
13431
  /** Create a new workflow in a workspace. */
13175
13432
  async createWorkflow(wid, workflow) {
13176
13433
  return this.fetch(`w/${wid}/workflows`, {
@@ -13269,6 +13526,13 @@ var init_chunk_6F4YJJKQ = __esm({
13269
13526
  `w/${wid}/workflows/${workflowId}/prompt-classifications`
13270
13527
  );
13271
13528
  }
13529
+ /** Review prompt diagnoses and report rebutted findings to Customer Success. */
13530
+ async reviewWorkflowPromptClassifications(wid, workflowId) {
13531
+ return this.fetch(
13532
+ `w/${wid}/workflows/${workflowId}/prompt-classifications`,
13533
+ { method: "POST" }
13534
+ );
13535
+ }
13272
13536
  /**
13273
13537
  * Replay automatic routing for a Chat without performing the transition.
13274
13538
  *
@@ -13902,6 +14166,17 @@ var init_chunk_6F4YJJKQ = __esm({
13902
14166
  async getWorkspaces(options) {
13903
14167
  return this.fetch(`w/?${workspaceDirectoryParams(options)}`);
13904
14168
  }
14169
+ /**
14170
+ * Page 1 of each organization's workspace directory, in one request.
14171
+ * Later pages stay on ``getWorkspaces({ organizationUuid, page })``.
14172
+ */
14173
+ async getOrganizationWorkspacePages(options) {
14174
+ const params = new URLSearchParams();
14175
+ if (options.pageSize !== void 0) params.set("pageSize", String(options.pageSize));
14176
+ if (options.search) params.set("search", options.search);
14177
+ for (const uuid of options.organizationUuids) params.append("organizationUuids", uuid);
14178
+ return this.fetch(`w/organization-pages?${params}`);
14179
+ }
13905
14180
  /** A bounded page of companion-device candidates, with admission checked per row. */
13906
14181
  async getDeviceAdmissibleWorkspaces(options) {
13907
14182
  const params = workspaceDirectoryParams(options);
@@ -15119,6 +15394,19 @@ var init_chunk_6F4YJJKQ = __esm({
15119
15394
  });
15120
15395
  }
15121
15396
  };
15397
+ DataReportsApi = class extends BaseApiClient {
15398
+ /**
15399
+ * Run a Form Reports report, saved or not, with the given parameter values.
15400
+ * The result is what the Agent would get: record rows or aggregate groups
15401
+ * within the tool's row and group caps, plus the text sent to the Agent.
15402
+ */
15403
+ async previewDataReport(wid, request) {
15404
+ return this.fetch(`w/${wid}/data-reports/preview`, {
15405
+ method: "POST",
15406
+ body: JSON.stringify(request)
15407
+ });
15408
+ }
15409
+ };
15122
15410
  ProjectsApi = class extends BaseApiClient {
15123
15411
  /** List projects (README frontmatter summaries). */
15124
15412
  async getProjects(wid, options = {}) {
@@ -15307,6 +15595,7 @@ var init_chunk_6F4YJJKQ = __esm({
15307
15595
  "configureHubspot",
15308
15596
  "configureMondayConnection",
15309
15597
  "configureSalesforce",
15598
+ "configureZendeskConnection",
15310
15599
  "convertEmail",
15311
15600
  "convertFile",
15312
15601
  "createAbility",
@@ -15503,6 +15792,7 @@ var init_chunk_6F4YJJKQ = __esm({
15503
15792
  "fhirGetCsvImportSettings",
15504
15793
  "fhirGetEncounterSyncRuns",
15505
15794
  "fhirGetEncounterSyncStatus",
15795
+ "fhirGetOnboardingImportStatus",
15506
15796
  "fhirImportPatient",
15507
15797
  "fhirLinkMember",
15508
15798
  "fhirListLinkedMembers",
@@ -15511,6 +15801,7 @@ var init_chunk_6F4YJJKQ = __esm({
15511
15801
  "fhirSearchLocations",
15512
15802
  "fhirSearchPatients",
15513
15803
  "fhirSearchPractitioners",
15804
+ "fhirStartOnboardingImport",
15514
15805
  "fhirSyncMember",
15515
15806
  "fhirUnlinkMember",
15516
15807
  "fhirUpdateCsvImportSettings",
@@ -15667,6 +15958,7 @@ var init_chunk_6F4YJJKQ = __esm({
15667
15958
  "importSiteSourceZip",
15668
15959
  "installDocumoFax",
15669
15960
  "listChatRecordings",
15961
+ "previewDataReport",
15670
15962
  "previewQuery",
15671
15963
  "publishSiteSource",
15672
15964
  "publishDataTypeDraft",
@@ -15690,6 +15982,7 @@ var init_chunk_6F4YJJKQ = __esm({
15690
15982
  "getFiles",
15691
15983
  "getFirstRunState",
15692
15984
  "getFolder",
15985
+ "getFolderChildren",
15693
15986
  "getFolderMemberAccess",
15694
15987
  "getFolderSharing",
15695
15988
  "getFolders",
@@ -15864,6 +16157,7 @@ var init_chunk_6F4YJJKQ = __esm({
15864
16157
  "getWorkflowConfigValidation",
15865
16158
  "getWorkflowFeedback",
15866
16159
  "getWorkflowPromptClassifications",
16160
+ "reviewWorkflowPromptClassifications",
15867
16161
  "getWorkflowContributors",
15868
16162
  "getWorkflowDeletionPreview",
15869
16163
  "getWorkflowDiagram",
@@ -15875,6 +16169,7 @@ var init_chunk_6F4YJJKQ = __esm({
15875
16169
  "getWorkflowTemplates",
15876
16170
  "getWorkflows",
15877
16171
  "getWorkflowsActivityBatch",
16172
+ "getWorkflowsOutlineBatch",
15878
16173
  "getWorkspace",
15879
16174
  "getWorkspaceActivityCounts",
15880
16175
  "getWorkspaceBuilder",
@@ -16409,6 +16704,8 @@ var init_chunk_6F4YJJKQ = __esm({
16409
16704
  validateQuery;
16410
16705
  previewQuery;
16411
16706
  runQuery;
16707
+ // Form Reports
16708
+ previewDataReport;
16412
16709
  listPersonas;
16413
16710
  getPersona;
16414
16711
  createPersona;
@@ -16593,6 +16890,7 @@ var init_chunk_6F4YJJKQ = __esm({
16593
16890
  inspectPrompt;
16594
16891
  // Workspaces API
16595
16892
  getWorkspaces;
16893
+ getOrganizationWorkspacePages;
16596
16894
  getDeviceAdmissibleWorkspaces;
16597
16895
  getPublicWorkspaces;
16598
16896
  getWorkspace;
@@ -16679,6 +16977,7 @@ var init_chunk_6F4YJJKQ = __esm({
16679
16977
  getVoiceTrustProducts;
16680
16978
  syncVoiceTrustProducts;
16681
16979
  createOrganizationWorkspace;
16980
+ getOrganizationWorkspaces;
16682
16981
  getOrganizationWorkspace;
16683
16982
  updateOrganizationWorkspace;
16684
16983
  getOrgBillingCustomer;
@@ -16688,7 +16987,20 @@ var init_chunk_6F4YJJKQ = __esm({
16688
16987
  updateOrganizationMember;
16689
16988
  listOrgWebhookEndpoints;
16690
16989
  getOrgWebhookEndpoint;
16990
+ createOrgWebhookEndpoint;
16691
16991
  updateOrgWebhookEndpoint;
16992
+ listOrgWebhookEndpointDeliveries;
16993
+ replayOrgWebhookDelivery;
16994
+ discardPendingOrgWebhookDeliveries;
16995
+ getOrgWebhookEndpointCoverage;
16996
+ testOrgWebhookEndpoint;
16997
+ listWorkspaceLabels;
16998
+ createWorkspaceLabel;
16999
+ updateWorkspaceLabel;
17000
+ deleteWorkspaceLabel;
17001
+ getWorkspaceLabels;
17002
+ setWorkspaceLabels;
17003
+ previewWorkspaceScope;
16692
17004
  getVapidPublicKey;
16693
17005
  registerPushSubscription;
16694
17006
  unregisterPushSubscription;
@@ -16829,6 +17141,7 @@ var init_chunk_6F4YJJKQ = __esm({
16829
17141
  convertFile;
16830
17142
  generateFileUploadUrl;
16831
17143
  getFolders;
17144
+ getFolderChildren;
16832
17145
  getFolder;
16833
17146
  createFolder;
16834
17147
  updateFolder;
@@ -16886,6 +17199,7 @@ var init_chunk_6F4YJJKQ = __esm({
16886
17199
  getWorkflowsActivityBatch;
16887
17200
  getWorkflowDiagram;
16888
17201
  getWorkflowOutline;
17202
+ getWorkflowsOutlineBatch;
16889
17203
  createWorkflow;
16890
17204
  updateWorkflow;
16891
17205
  getWorkflowDeletionPreview;
@@ -16899,6 +17213,7 @@ var init_chunk_6F4YJJKQ = __esm({
16899
17213
  getTaskChats;
16900
17214
  getWorkflowConfigValidation;
16901
17215
  getWorkflowPromptClassifications;
17216
+ reviewWorkflowPromptClassifications;
16902
17217
  getWorkflowNotes;
16903
17218
  createWorkflowNote;
16904
17219
  updateWorkflowNote;
@@ -17097,6 +17412,12 @@ var init_chunk_6F4YJJKQ = __esm({
17097
17412
  deleteInquiry;
17098
17413
  exportInquiriesCsv;
17099
17414
  authorize;
17415
+ denyAuthorization;
17416
+ getOAuthConsentClient;
17417
+ getMcpConsentTargets;
17418
+ listMcpGrants;
17419
+ narrowMcpGrant;
17420
+ revokeMcpGrant;
17100
17421
  exchangeOAuthToken;
17101
17422
  getAvailableScopes;
17102
17423
  getOAuthConnectionStatus;
@@ -17198,6 +17519,8 @@ var init_chunk_6F4YJJKQ = __esm({
17198
17519
  fhirGetEncounterSyncRuns;
17199
17520
  fhirRefreshEncounterPatient;
17200
17521
  fhirBackfillEncounterSync;
17522
+ fhirStartOnboardingImport;
17523
+ fhirGetOnboardingImportStatus;
17201
17524
  // Healthie API
17202
17525
  getDocumoFaxStatus;
17203
17526
  getDocumoFaxSetup;
@@ -17290,6 +17613,7 @@ var init_chunk_6F4YJJKQ = __esm({
17290
17613
  listAvailableAppConnections;
17291
17614
  listAppConnections;
17292
17615
  enablePlatformApp;
17616
+ configureZendeskConnection;
17293
17617
  getPlatformApp;
17294
17618
  updatePlatformApp;
17295
17619
  deletePlatformApp;
@@ -17370,6 +17694,7 @@ var init_chunk_6F4YJJKQ = __esm({
17370
17694
  bindPersonasMethods(this, apis.personas);
17371
17695
  bindMetricsMethods(this, apis.metrics);
17372
17696
  bindQueriesMethods(this, apis.queries);
17697
+ bindDataReportsMethods(this, apis.dataReports);
17373
17698
  bindDashboardsMethods(this, apis.dashboards);
17374
17699
  bindActivityMethods(this, apis.activity);
17375
17700
  bindMotdMethods(this, apis.motd);
@@ -17549,9 +17874,9 @@ var init_chunk_6F4YJJKQ = __esm({
17549
17874
  }
17550
17875
  });
17551
17876
 
17552
- // ../sdk/dist/chunk-MMDSZ25F.js
17553
- var init_chunk_MMDSZ25F = __esm({
17554
- "../sdk/dist/chunk-MMDSZ25F.js"() {
17877
+ // ../sdk/dist/chunk-HXVJF54M.js
17878
+ var init_chunk_HXVJF54M = __esm({
17879
+ "../sdk/dist/chunk-HXVJF54M.js"() {
17555
17880
  }
17556
17881
  });
17557
17882
 
@@ -17606,8 +17931,8 @@ var init_chunk_6KPGCPGW = __esm({
17606
17931
  var SEARCHABLE_EVENT_RULE_SOURCE_FIELDS, ActivityEventType, EntityKind;
17607
17932
  var init_dist = __esm({
17608
17933
  "../sdk/dist/index.js"() {
17609
- init_chunk_6F4YJJKQ();
17610
- init_chunk_MMDSZ25F();
17934
+ init_chunk_BF4MOZZO();
17935
+ init_chunk_HXVJF54M();
17611
17936
  init_chunk_6KPGCPGW();
17612
17937
  init_chunk_GCN4OMYU();
17613
17938
  SEARCHABLE_EVENT_RULE_SOURCE_FIELDS = [
@@ -17693,6 +18018,7 @@ var init_dist = __esm({
17693
18018
  escalation: "escalation",
17694
18019
  inbox: "inbox",
17695
18020
  phone_number: "phone_number",
18021
+ recording: "recording",
17696
18022
  voicemail: "voicemail",
17697
18023
  domain: "domain",
17698
18024
  import: "import",
@@ -18894,7 +19220,7 @@ function readBlockScalar(state, parentIndent, props) {
18894
19220
  state.position = linePosition + column;
18895
19221
  throwError(state, "tab characters must not be used in indentation");
18896
19222
  }
18897
- if (column < maxLeadingIndent) {
19223
+ if (column >= parentIndent && column < maxLeadingIndent) {
18898
19224
  state.position = linePosition + column;
18899
19225
  throwError(state, "bad indentation of a mapping entry");
18900
19226
  }
@@ -19104,13 +19430,16 @@ function readBlockMapping(state, nodeIndent, flowIndent, props) {
19104
19430
  ch = state.input.charCodeAt(++state.position);
19105
19431
  if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
19106
19432
  if (!mappingOpened) {
19107
- restoreState(state, beforeKey);
19108
- addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
19433
+ state.events.splice(beforeKey.eventsLength, 0, {
19434
+ type: EVENT_ID.MAPPING,
19435
+ start: beforeKey.position,
19436
+ anchorStart: props.anchorStart,
19437
+ anchorEnd: props.anchorEnd,
19438
+ tagStart: props.tagStart,
19439
+ tagEnd: props.tagEnd,
19440
+ style: COLLECTION_STYLE.BLOCK
19441
+ });
19109
19442
  mappingOpened = true;
19110
- parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true);
19111
- ch = state.input.charCodeAt(state.position);
19112
- while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
19113
- state.position++;
19114
19443
  }
19115
19444
  detected = true;
19116
19445
  atExplicitKey = false;
@@ -20369,6 +20698,1650 @@ var init_config = __esm({
20369
20698
  };
20370
20699
  }
20371
20700
  });
20701
+
20702
+ // ../../node_modules/graceful-fs/polyfills.js
20703
+ var require_polyfills = __commonJS({
20704
+ "../../node_modules/graceful-fs/polyfills.js"(exports$1, module) {
20705
+ var constants = __require("constants");
20706
+ var origCwd = process.cwd;
20707
+ var cwd = null;
20708
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
20709
+ process.cwd = function() {
20710
+ if (!cwd)
20711
+ cwd = origCwd.call(process);
20712
+ return cwd;
20713
+ };
20714
+ try {
20715
+ process.cwd();
20716
+ } catch (er) {
20717
+ }
20718
+ if (typeof process.chdir === "function") {
20719
+ chdir = process.chdir;
20720
+ process.chdir = function(d) {
20721
+ cwd = null;
20722
+ chdir.call(process, d);
20723
+ };
20724
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
20725
+ }
20726
+ var chdir;
20727
+ module.exports = patch;
20728
+ function patch(fs3) {
20729
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
20730
+ patchLchmod(fs3);
20731
+ }
20732
+ if (!fs3.lutimes) {
20733
+ patchLutimes(fs3);
20734
+ }
20735
+ fs3.chown = chownFix(fs3.chown);
20736
+ fs3.fchown = chownFix(fs3.fchown);
20737
+ fs3.lchown = chownFix(fs3.lchown);
20738
+ fs3.chmod = chmodFix(fs3.chmod);
20739
+ fs3.fchmod = chmodFix(fs3.fchmod);
20740
+ fs3.lchmod = chmodFix(fs3.lchmod);
20741
+ fs3.chownSync = chownFixSync(fs3.chownSync);
20742
+ fs3.fchownSync = chownFixSync(fs3.fchownSync);
20743
+ fs3.lchownSync = chownFixSync(fs3.lchownSync);
20744
+ fs3.chmodSync = chmodFixSync(fs3.chmodSync);
20745
+ fs3.fchmodSync = chmodFixSync(fs3.fchmodSync);
20746
+ fs3.lchmodSync = chmodFixSync(fs3.lchmodSync);
20747
+ fs3.stat = statFix(fs3.stat);
20748
+ fs3.fstat = statFix(fs3.fstat);
20749
+ fs3.lstat = statFix(fs3.lstat);
20750
+ fs3.statSync = statFixSync(fs3.statSync);
20751
+ fs3.fstatSync = statFixSync(fs3.fstatSync);
20752
+ fs3.lstatSync = statFixSync(fs3.lstatSync);
20753
+ if (fs3.chmod && !fs3.lchmod) {
20754
+ fs3.lchmod = function(path4, mode, cb) {
20755
+ if (cb) process.nextTick(cb);
20756
+ };
20757
+ fs3.lchmodSync = function() {
20758
+ };
20759
+ }
20760
+ if (fs3.chown && !fs3.lchown) {
20761
+ fs3.lchown = function(path4, uid, gid, cb) {
20762
+ if (cb) process.nextTick(cb);
20763
+ };
20764
+ fs3.lchownSync = function() {
20765
+ };
20766
+ }
20767
+ if (platform === "win32") {
20768
+ fs3.rename = typeof fs3.rename !== "function" ? fs3.rename : (function(fs$rename) {
20769
+ function rename(from, to, cb) {
20770
+ var start = Date.now();
20771
+ var backoff = 0;
20772
+ fs$rename(from, to, function CB(er) {
20773
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
20774
+ setTimeout(function() {
20775
+ fs3.stat(to, function(stater, st) {
20776
+ if (stater && stater.code === "ENOENT")
20777
+ fs$rename(from, to, CB);
20778
+ else
20779
+ cb(er);
20780
+ });
20781
+ }, backoff);
20782
+ if (backoff < 100)
20783
+ backoff += 10;
20784
+ return;
20785
+ }
20786
+ if (cb) cb(er);
20787
+ });
20788
+ }
20789
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
20790
+ return rename;
20791
+ })(fs3.rename);
20792
+ }
20793
+ fs3.read = typeof fs3.read !== "function" ? fs3.read : (function(fs$read) {
20794
+ function read(fd, buffer, offset, length, position, callback_) {
20795
+ var callback;
20796
+ if (callback_ && typeof callback_ === "function") {
20797
+ var eagCounter = 0;
20798
+ callback = function(er, _, __) {
20799
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
20800
+ eagCounter++;
20801
+ return fs$read.call(fs3, fd, buffer, offset, length, position, callback);
20802
+ }
20803
+ callback_.apply(this, arguments);
20804
+ };
20805
+ }
20806
+ return fs$read.call(fs3, fd, buffer, offset, length, position, callback);
20807
+ }
20808
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
20809
+ return read;
20810
+ })(fs3.read);
20811
+ fs3.readSync = typeof fs3.readSync !== "function" ? fs3.readSync : /* @__PURE__ */ (function(fs$readSync) {
20812
+ return function(fd, buffer, offset, length, position) {
20813
+ var eagCounter = 0;
20814
+ while (true) {
20815
+ try {
20816
+ return fs$readSync.call(fs3, fd, buffer, offset, length, position);
20817
+ } catch (er) {
20818
+ if (er.code === "EAGAIN" && eagCounter < 10) {
20819
+ eagCounter++;
20820
+ continue;
20821
+ }
20822
+ throw er;
20823
+ }
20824
+ }
20825
+ };
20826
+ })(fs3.readSync);
20827
+ function patchLchmod(fs4) {
20828
+ fs4.lchmod = function(path4, mode, callback) {
20829
+ fs4.open(
20830
+ path4,
20831
+ constants.O_WRONLY | constants.O_SYMLINK,
20832
+ mode,
20833
+ function(err, fd) {
20834
+ if (err) {
20835
+ if (callback) callback(err);
20836
+ return;
20837
+ }
20838
+ fs4.fchmod(fd, mode, function(err2) {
20839
+ fs4.close(fd, function(err22) {
20840
+ if (callback) callback(err2 || err22);
20841
+ });
20842
+ });
20843
+ }
20844
+ );
20845
+ };
20846
+ fs4.lchmodSync = function(path4, mode) {
20847
+ var fd = fs4.openSync(path4, constants.O_WRONLY | constants.O_SYMLINK, mode);
20848
+ var threw = true;
20849
+ var ret;
20850
+ try {
20851
+ ret = fs4.fchmodSync(fd, mode);
20852
+ threw = false;
20853
+ } finally {
20854
+ if (threw) {
20855
+ try {
20856
+ fs4.closeSync(fd);
20857
+ } catch (er) {
20858
+ }
20859
+ } else {
20860
+ fs4.closeSync(fd);
20861
+ }
20862
+ }
20863
+ return ret;
20864
+ };
20865
+ }
20866
+ function patchLutimes(fs4) {
20867
+ if (constants.hasOwnProperty("O_SYMLINK") && fs4.futimes) {
20868
+ fs4.lutimes = function(path4, at, mt, cb) {
20869
+ fs4.open(path4, constants.O_SYMLINK, function(er, fd) {
20870
+ if (er) {
20871
+ if (cb) cb(er);
20872
+ return;
20873
+ }
20874
+ fs4.futimes(fd, at, mt, function(er2) {
20875
+ fs4.close(fd, function(er22) {
20876
+ if (cb) cb(er2 || er22);
20877
+ });
20878
+ });
20879
+ });
20880
+ };
20881
+ fs4.lutimesSync = function(path4, at, mt) {
20882
+ var fd = fs4.openSync(path4, constants.O_SYMLINK);
20883
+ var ret;
20884
+ var threw = true;
20885
+ try {
20886
+ ret = fs4.futimesSync(fd, at, mt);
20887
+ threw = false;
20888
+ } finally {
20889
+ if (threw) {
20890
+ try {
20891
+ fs4.closeSync(fd);
20892
+ } catch (er) {
20893
+ }
20894
+ } else {
20895
+ fs4.closeSync(fd);
20896
+ }
20897
+ }
20898
+ return ret;
20899
+ };
20900
+ } else if (fs4.futimes) {
20901
+ fs4.lutimes = function(_a, _b, _c, cb) {
20902
+ if (cb) process.nextTick(cb);
20903
+ };
20904
+ fs4.lutimesSync = function() {
20905
+ };
20906
+ }
20907
+ }
20908
+ function chmodFix(orig) {
20909
+ if (!orig) return orig;
20910
+ return function(target, mode, cb) {
20911
+ return orig.call(fs3, target, mode, function(er) {
20912
+ if (chownErOk(er)) er = null;
20913
+ if (cb) cb.apply(this, arguments);
20914
+ });
20915
+ };
20916
+ }
20917
+ function chmodFixSync(orig) {
20918
+ if (!orig) return orig;
20919
+ return function(target, mode) {
20920
+ try {
20921
+ return orig.call(fs3, target, mode);
20922
+ } catch (er) {
20923
+ if (!chownErOk(er)) throw er;
20924
+ }
20925
+ };
20926
+ }
20927
+ function chownFix(orig) {
20928
+ if (!orig) return orig;
20929
+ return function(target, uid, gid, cb) {
20930
+ return orig.call(fs3, target, uid, gid, function(er) {
20931
+ if (chownErOk(er)) er = null;
20932
+ if (cb) cb.apply(this, arguments);
20933
+ });
20934
+ };
20935
+ }
20936
+ function chownFixSync(orig) {
20937
+ if (!orig) return orig;
20938
+ return function(target, uid, gid) {
20939
+ try {
20940
+ return orig.call(fs3, target, uid, gid);
20941
+ } catch (er) {
20942
+ if (!chownErOk(er)) throw er;
20943
+ }
20944
+ };
20945
+ }
20946
+ function statFix(orig) {
20947
+ if (!orig) return orig;
20948
+ return function(target, options, cb) {
20949
+ if (typeof options === "function") {
20950
+ cb = options;
20951
+ options = null;
20952
+ }
20953
+ function callback(er, stats) {
20954
+ if (stats) {
20955
+ if (stats.uid < 0) stats.uid += 4294967296;
20956
+ if (stats.gid < 0) stats.gid += 4294967296;
20957
+ }
20958
+ if (cb) cb.apply(this, arguments);
20959
+ }
20960
+ return options ? orig.call(fs3, target, options, callback) : orig.call(fs3, target, callback);
20961
+ };
20962
+ }
20963
+ function statFixSync(orig) {
20964
+ if (!orig) return orig;
20965
+ return function(target, options) {
20966
+ var stats = options ? orig.call(fs3, target, options) : orig.call(fs3, target);
20967
+ if (stats) {
20968
+ if (stats.uid < 0) stats.uid += 4294967296;
20969
+ if (stats.gid < 0) stats.gid += 4294967296;
20970
+ }
20971
+ return stats;
20972
+ };
20973
+ }
20974
+ function chownErOk(er) {
20975
+ if (!er)
20976
+ return true;
20977
+ if (er.code === "ENOSYS")
20978
+ return true;
20979
+ var nonroot = !process.getuid || process.getuid() !== 0;
20980
+ if (nonroot) {
20981
+ if (er.code === "EINVAL" || er.code === "EPERM")
20982
+ return true;
20983
+ }
20984
+ return false;
20985
+ }
20986
+ }
20987
+ }
20988
+ });
20989
+
20990
+ // ../../node_modules/graceful-fs/legacy-streams.js
20991
+ var require_legacy_streams = __commonJS({
20992
+ "../../node_modules/graceful-fs/legacy-streams.js"(exports$1, module) {
20993
+ var Stream = __require("stream").Stream;
20994
+ module.exports = legacy;
20995
+ function legacy(fs3) {
20996
+ return {
20997
+ ReadStream,
20998
+ WriteStream
20999
+ };
21000
+ function ReadStream(path4, options) {
21001
+ if (!(this instanceof ReadStream)) return new ReadStream(path4, options);
21002
+ Stream.call(this);
21003
+ var self = this;
21004
+ this.path = path4;
21005
+ this.fd = null;
21006
+ this.readable = true;
21007
+ this.paused = false;
21008
+ this.flags = "r";
21009
+ this.mode = 438;
21010
+ this.bufferSize = 64 * 1024;
21011
+ options = options || {};
21012
+ var keys = Object.keys(options);
21013
+ for (var index = 0, length = keys.length; index < length; index++) {
21014
+ var key = keys[index];
21015
+ this[key] = options[key];
21016
+ }
21017
+ if (this.encoding) this.setEncoding(this.encoding);
21018
+ if (this.start !== void 0) {
21019
+ if ("number" !== typeof this.start) {
21020
+ throw TypeError("start must be a Number");
21021
+ }
21022
+ if (this.end === void 0) {
21023
+ this.end = Infinity;
21024
+ } else if ("number" !== typeof this.end) {
21025
+ throw TypeError("end must be a Number");
21026
+ }
21027
+ if (this.start > this.end) {
21028
+ throw new Error("start must be <= end");
21029
+ }
21030
+ this.pos = this.start;
21031
+ }
21032
+ if (this.fd !== null) {
21033
+ process.nextTick(function() {
21034
+ self._read();
21035
+ });
21036
+ return;
21037
+ }
21038
+ fs3.open(this.path, this.flags, this.mode, function(err, fd) {
21039
+ if (err) {
21040
+ self.emit("error", err);
21041
+ self.readable = false;
21042
+ return;
21043
+ }
21044
+ self.fd = fd;
21045
+ self.emit("open", fd);
21046
+ self._read();
21047
+ });
21048
+ }
21049
+ function WriteStream(path4, options) {
21050
+ if (!(this instanceof WriteStream)) return new WriteStream(path4, options);
21051
+ Stream.call(this);
21052
+ this.path = path4;
21053
+ this.fd = null;
21054
+ this.writable = true;
21055
+ this.flags = "w";
21056
+ this.encoding = "binary";
21057
+ this.mode = 438;
21058
+ this.bytesWritten = 0;
21059
+ options = options || {};
21060
+ var keys = Object.keys(options);
21061
+ for (var index = 0, length = keys.length; index < length; index++) {
21062
+ var key = keys[index];
21063
+ this[key] = options[key];
21064
+ }
21065
+ if (this.start !== void 0) {
21066
+ if ("number" !== typeof this.start) {
21067
+ throw TypeError("start must be a Number");
21068
+ }
21069
+ if (this.start < 0) {
21070
+ throw new Error("start must be >= zero");
21071
+ }
21072
+ this.pos = this.start;
21073
+ }
21074
+ this.busy = false;
21075
+ this._queue = [];
21076
+ if (this.fd === null) {
21077
+ this._open = fs3.open;
21078
+ this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
21079
+ this.flush();
21080
+ }
21081
+ }
21082
+ }
21083
+ }
21084
+ });
21085
+
21086
+ // ../../node_modules/graceful-fs/clone.js
21087
+ var require_clone = __commonJS({
21088
+ "../../node_modules/graceful-fs/clone.js"(exports$1, module) {
21089
+ module.exports = clone;
21090
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
21091
+ return obj.__proto__;
21092
+ };
21093
+ function clone(obj) {
21094
+ if (obj === null || typeof obj !== "object")
21095
+ return obj;
21096
+ if (obj instanceof Object)
21097
+ var copy = { __proto__: getPrototypeOf(obj) };
21098
+ else
21099
+ var copy = /* @__PURE__ */ Object.create(null);
21100
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
21101
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
21102
+ });
21103
+ return copy;
21104
+ }
21105
+ }
21106
+ });
21107
+
21108
+ // ../../node_modules/graceful-fs/graceful-fs.js
21109
+ var require_graceful_fs = __commonJS({
21110
+ "../../node_modules/graceful-fs/graceful-fs.js"(exports$1, module) {
21111
+ var fs3 = __require("fs");
21112
+ var polyfills = require_polyfills();
21113
+ var legacy = require_legacy_streams();
21114
+ var clone = require_clone();
21115
+ var util = __require("util");
21116
+ var gracefulQueue;
21117
+ var previousSymbol;
21118
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
21119
+ gracefulQueue = /* @__PURE__ */ Symbol.for("graceful-fs.queue");
21120
+ previousSymbol = /* @__PURE__ */ Symbol.for("graceful-fs.previous");
21121
+ } else {
21122
+ gracefulQueue = "___graceful-fs.queue";
21123
+ previousSymbol = "___graceful-fs.previous";
21124
+ }
21125
+ function noop() {
21126
+ }
21127
+ function publishQueue(context, queue2) {
21128
+ Object.defineProperty(context, gracefulQueue, {
21129
+ get: function() {
21130
+ return queue2;
21131
+ }
21132
+ });
21133
+ }
21134
+ var debug = noop;
21135
+ if (util.debuglog)
21136
+ debug = util.debuglog("gfs4");
21137
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
21138
+ debug = function() {
21139
+ var m = util.format.apply(util, arguments);
21140
+ m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
21141
+ console.error(m);
21142
+ };
21143
+ if (!fs3[gracefulQueue]) {
21144
+ queue = global[gracefulQueue] || [];
21145
+ publishQueue(fs3, queue);
21146
+ fs3.close = (function(fs$close) {
21147
+ function close(fd, cb) {
21148
+ return fs$close.call(fs3, fd, function(err) {
21149
+ if (!err) {
21150
+ resetQueue();
21151
+ }
21152
+ if (typeof cb === "function")
21153
+ cb.apply(this, arguments);
21154
+ });
21155
+ }
21156
+ Object.defineProperty(close, previousSymbol, {
21157
+ value: fs$close
21158
+ });
21159
+ return close;
21160
+ })(fs3.close);
21161
+ fs3.closeSync = (function(fs$closeSync) {
21162
+ function closeSync(fd) {
21163
+ fs$closeSync.apply(fs3, arguments);
21164
+ resetQueue();
21165
+ }
21166
+ Object.defineProperty(closeSync, previousSymbol, {
21167
+ value: fs$closeSync
21168
+ });
21169
+ return closeSync;
21170
+ })(fs3.closeSync);
21171
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
21172
+ process.on("exit", function() {
21173
+ debug(fs3[gracefulQueue]);
21174
+ __require("assert").equal(fs3[gracefulQueue].length, 0);
21175
+ });
21176
+ }
21177
+ }
21178
+ var queue;
21179
+ if (!global[gracefulQueue]) {
21180
+ publishQueue(global, fs3[gracefulQueue]);
21181
+ }
21182
+ module.exports = patch(clone(fs3));
21183
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs3.__patched) {
21184
+ module.exports = patch(fs3);
21185
+ fs3.__patched = true;
21186
+ }
21187
+ function patch(fs4) {
21188
+ polyfills(fs4);
21189
+ fs4.gracefulify = patch;
21190
+ fs4.createReadStream = createReadStream;
21191
+ fs4.createWriteStream = createWriteStream2;
21192
+ var fs$readFile = fs4.readFile;
21193
+ fs4.readFile = readFile3;
21194
+ function readFile3(path4, options, cb) {
21195
+ if (typeof options === "function")
21196
+ cb = options, options = null;
21197
+ return go$readFile(path4, options, cb);
21198
+ function go$readFile(path5, options2, cb2, startTime) {
21199
+ return fs$readFile(path5, options2, function(err) {
21200
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
21201
+ enqueue([go$readFile, [path5, options2, cb2], err, startTime || Date.now(), Date.now()]);
21202
+ else {
21203
+ if (typeof cb2 === "function")
21204
+ cb2.apply(this, arguments);
21205
+ }
21206
+ });
21207
+ }
21208
+ }
21209
+ var fs$writeFile = fs4.writeFile;
21210
+ fs4.writeFile = writeFile2;
21211
+ function writeFile2(path4, data, options, cb) {
21212
+ if (typeof options === "function")
21213
+ cb = options, options = null;
21214
+ return go$writeFile(path4, data, options, cb);
21215
+ function go$writeFile(path5, data2, options2, cb2, startTime) {
21216
+ return fs$writeFile(path5, data2, options2, function(err) {
21217
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
21218
+ enqueue([go$writeFile, [path5, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
21219
+ else {
21220
+ if (typeof cb2 === "function")
21221
+ cb2.apply(this, arguments);
21222
+ }
21223
+ });
21224
+ }
21225
+ }
21226
+ var fs$appendFile = fs4.appendFile;
21227
+ if (fs$appendFile)
21228
+ fs4.appendFile = appendFile;
21229
+ function appendFile(path4, data, options, cb) {
21230
+ if (typeof options === "function")
21231
+ cb = options, options = null;
21232
+ return go$appendFile(path4, data, options, cb);
21233
+ function go$appendFile(path5, data2, options2, cb2, startTime) {
21234
+ return fs$appendFile(path5, data2, options2, function(err) {
21235
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
21236
+ enqueue([go$appendFile, [path5, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
21237
+ else {
21238
+ if (typeof cb2 === "function")
21239
+ cb2.apply(this, arguments);
21240
+ }
21241
+ });
21242
+ }
21243
+ }
21244
+ var fs$copyFile = fs4.copyFile;
21245
+ if (fs$copyFile)
21246
+ fs4.copyFile = copyFile;
21247
+ function copyFile(src, dest, flags, cb) {
21248
+ if (typeof flags === "function") {
21249
+ cb = flags;
21250
+ flags = 0;
21251
+ }
21252
+ return go$copyFile(src, dest, flags, cb);
21253
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
21254
+ return fs$copyFile(src2, dest2, flags2, function(err) {
21255
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
21256
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
21257
+ else {
21258
+ if (typeof cb2 === "function")
21259
+ cb2.apply(this, arguments);
21260
+ }
21261
+ });
21262
+ }
21263
+ }
21264
+ var fs$readdir = fs4.readdir;
21265
+ fs4.readdir = readdir;
21266
+ var noReaddirOptionVersions = /^v[0-5]\./;
21267
+ function readdir(path4, options, cb) {
21268
+ if (typeof options === "function")
21269
+ cb = options, options = null;
21270
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path5, options2, cb2, startTime) {
21271
+ return fs$readdir(path5, fs$readdirCallback(
21272
+ path5,
21273
+ options2,
21274
+ cb2,
21275
+ startTime
21276
+ ));
21277
+ } : function go$readdir2(path5, options2, cb2, startTime) {
21278
+ return fs$readdir(path5, options2, fs$readdirCallback(
21279
+ path5,
21280
+ options2,
21281
+ cb2,
21282
+ startTime
21283
+ ));
21284
+ };
21285
+ return go$readdir(path4, options, cb);
21286
+ function fs$readdirCallback(path5, options2, cb2, startTime) {
21287
+ return function(err, files) {
21288
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
21289
+ enqueue([
21290
+ go$readdir,
21291
+ [path5, options2, cb2],
21292
+ err,
21293
+ startTime || Date.now(),
21294
+ Date.now()
21295
+ ]);
21296
+ else {
21297
+ if (files && files.sort)
21298
+ files.sort();
21299
+ if (typeof cb2 === "function")
21300
+ cb2.call(this, err, files);
21301
+ }
21302
+ };
21303
+ }
21304
+ }
21305
+ if (process.version.substr(0, 4) === "v0.8") {
21306
+ var legStreams = legacy(fs4);
21307
+ ReadStream = legStreams.ReadStream;
21308
+ WriteStream = legStreams.WriteStream;
21309
+ }
21310
+ var fs$ReadStream = fs4.ReadStream;
21311
+ if (fs$ReadStream) {
21312
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
21313
+ ReadStream.prototype.open = ReadStream$open;
21314
+ }
21315
+ var fs$WriteStream = fs4.WriteStream;
21316
+ if (fs$WriteStream) {
21317
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
21318
+ WriteStream.prototype.open = WriteStream$open;
21319
+ }
21320
+ Object.defineProperty(fs4, "ReadStream", {
21321
+ get: function() {
21322
+ return ReadStream;
21323
+ },
21324
+ set: function(val) {
21325
+ ReadStream = val;
21326
+ },
21327
+ enumerable: true,
21328
+ configurable: true
21329
+ });
21330
+ Object.defineProperty(fs4, "WriteStream", {
21331
+ get: function() {
21332
+ return WriteStream;
21333
+ },
21334
+ set: function(val) {
21335
+ WriteStream = val;
21336
+ },
21337
+ enumerable: true,
21338
+ configurable: true
21339
+ });
21340
+ var FileReadStream = ReadStream;
21341
+ Object.defineProperty(fs4, "FileReadStream", {
21342
+ get: function() {
21343
+ return FileReadStream;
21344
+ },
21345
+ set: function(val) {
21346
+ FileReadStream = val;
21347
+ },
21348
+ enumerable: true,
21349
+ configurable: true
21350
+ });
21351
+ var FileWriteStream = WriteStream;
21352
+ Object.defineProperty(fs4, "FileWriteStream", {
21353
+ get: function() {
21354
+ return FileWriteStream;
21355
+ },
21356
+ set: function(val) {
21357
+ FileWriteStream = val;
21358
+ },
21359
+ enumerable: true,
21360
+ configurable: true
21361
+ });
21362
+ function ReadStream(path4, options) {
21363
+ if (this instanceof ReadStream)
21364
+ return fs$ReadStream.apply(this, arguments), this;
21365
+ else
21366
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
21367
+ }
21368
+ function ReadStream$open() {
21369
+ var that = this;
21370
+ open(that.path, that.flags, that.mode, function(err, fd) {
21371
+ if (err) {
21372
+ if (that.autoClose)
21373
+ that.destroy();
21374
+ that.emit("error", err);
21375
+ } else {
21376
+ that.fd = fd;
21377
+ that.emit("open", fd);
21378
+ that.read();
21379
+ }
21380
+ });
21381
+ }
21382
+ function WriteStream(path4, options) {
21383
+ if (this instanceof WriteStream)
21384
+ return fs$WriteStream.apply(this, arguments), this;
21385
+ else
21386
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
21387
+ }
21388
+ function WriteStream$open() {
21389
+ var that = this;
21390
+ open(that.path, that.flags, that.mode, function(err, fd) {
21391
+ if (err) {
21392
+ that.destroy();
21393
+ that.emit("error", err);
21394
+ } else {
21395
+ that.fd = fd;
21396
+ that.emit("open", fd);
21397
+ }
21398
+ });
21399
+ }
21400
+ function createReadStream(path4, options) {
21401
+ return new fs4.ReadStream(path4, options);
21402
+ }
21403
+ function createWriteStream2(path4, options) {
21404
+ return new fs4.WriteStream(path4, options);
21405
+ }
21406
+ var fs$open = fs4.open;
21407
+ fs4.open = open;
21408
+ function open(path4, flags, mode, cb) {
21409
+ if (typeof mode === "function")
21410
+ cb = mode, mode = null;
21411
+ return go$open(path4, flags, mode, cb);
21412
+ function go$open(path5, flags2, mode2, cb2, startTime) {
21413
+ return fs$open(path5, flags2, mode2, function(err, fd) {
21414
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
21415
+ enqueue([go$open, [path5, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
21416
+ else {
21417
+ if (typeof cb2 === "function")
21418
+ cb2.apply(this, arguments);
21419
+ }
21420
+ });
21421
+ }
21422
+ }
21423
+ return fs4;
21424
+ }
21425
+ function enqueue(elem) {
21426
+ debug("ENQUEUE", elem[0].name, elem[1]);
21427
+ fs3[gracefulQueue].push(elem);
21428
+ retry();
21429
+ }
21430
+ var retryTimer;
21431
+ function resetQueue() {
21432
+ var now = Date.now();
21433
+ for (var i = 0; i < fs3[gracefulQueue].length; ++i) {
21434
+ if (fs3[gracefulQueue][i].length > 2) {
21435
+ fs3[gracefulQueue][i][3] = now;
21436
+ fs3[gracefulQueue][i][4] = now;
21437
+ }
21438
+ }
21439
+ retry();
21440
+ }
21441
+ function retry() {
21442
+ clearTimeout(retryTimer);
21443
+ retryTimer = void 0;
21444
+ if (fs3[gracefulQueue].length === 0)
21445
+ return;
21446
+ var elem = fs3[gracefulQueue].shift();
21447
+ var fn = elem[0];
21448
+ var args = elem[1];
21449
+ var err = elem[2];
21450
+ var startTime = elem[3];
21451
+ var lastTime = elem[4];
21452
+ if (startTime === void 0) {
21453
+ debug("RETRY", fn.name, args);
21454
+ fn.apply(null, args);
21455
+ } else if (Date.now() - startTime >= 6e4) {
21456
+ debug("TIMEOUT", fn.name, args);
21457
+ var cb = args.pop();
21458
+ if (typeof cb === "function")
21459
+ cb.call(null, err);
21460
+ } else {
21461
+ var sinceAttempt = Date.now() - lastTime;
21462
+ var sinceStart = Math.max(lastTime - startTime, 1);
21463
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
21464
+ if (sinceAttempt >= desiredDelay) {
21465
+ debug("RETRY", fn.name, args);
21466
+ fn.apply(null, args.concat([startTime]));
21467
+ } else {
21468
+ fs3[gracefulQueue].push(elem);
21469
+ }
21470
+ }
21471
+ if (retryTimer === void 0) {
21472
+ retryTimer = setTimeout(retry, 0);
21473
+ }
21474
+ }
21475
+ }
21476
+ });
21477
+
21478
+ // ../../node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js
21479
+ var require_retry_operation = __commonJS({
21480
+ "../../node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(exports$1, module) {
21481
+ function RetryOperation(timeouts, options) {
21482
+ if (typeof options === "boolean") {
21483
+ options = { forever: options };
21484
+ }
21485
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
21486
+ this._timeouts = timeouts;
21487
+ this._options = options || {};
21488
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
21489
+ this._fn = null;
21490
+ this._errors = [];
21491
+ this._attempts = 1;
21492
+ this._operationTimeout = null;
21493
+ this._operationTimeoutCb = null;
21494
+ this._timeout = null;
21495
+ this._operationStart = null;
21496
+ if (this._options.forever) {
21497
+ this._cachedTimeouts = this._timeouts.slice(0);
21498
+ }
21499
+ }
21500
+ module.exports = RetryOperation;
21501
+ RetryOperation.prototype.reset = function() {
21502
+ this._attempts = 1;
21503
+ this._timeouts = this._originalTimeouts;
21504
+ };
21505
+ RetryOperation.prototype.stop = function() {
21506
+ if (this._timeout) {
21507
+ clearTimeout(this._timeout);
21508
+ }
21509
+ this._timeouts = [];
21510
+ this._cachedTimeouts = null;
21511
+ };
21512
+ RetryOperation.prototype.retry = function(err) {
21513
+ if (this._timeout) {
21514
+ clearTimeout(this._timeout);
21515
+ }
21516
+ if (!err) {
21517
+ return false;
21518
+ }
21519
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
21520
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
21521
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
21522
+ return false;
21523
+ }
21524
+ this._errors.push(err);
21525
+ var timeout = this._timeouts.shift();
21526
+ if (timeout === void 0) {
21527
+ if (this._cachedTimeouts) {
21528
+ this._errors.splice(this._errors.length - 1, this._errors.length);
21529
+ this._timeouts = this._cachedTimeouts.slice(0);
21530
+ timeout = this._timeouts.shift();
21531
+ } else {
21532
+ return false;
21533
+ }
21534
+ }
21535
+ var self = this;
21536
+ var timer = setTimeout(function() {
21537
+ self._attempts++;
21538
+ if (self._operationTimeoutCb) {
21539
+ self._timeout = setTimeout(function() {
21540
+ self._operationTimeoutCb(self._attempts);
21541
+ }, self._operationTimeout);
21542
+ if (self._options.unref) {
21543
+ self._timeout.unref();
21544
+ }
21545
+ }
21546
+ self._fn(self._attempts);
21547
+ }, timeout);
21548
+ if (this._options.unref) {
21549
+ timer.unref();
21550
+ }
21551
+ return true;
21552
+ };
21553
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
21554
+ this._fn = fn;
21555
+ if (timeoutOps) {
21556
+ if (timeoutOps.timeout) {
21557
+ this._operationTimeout = timeoutOps.timeout;
21558
+ }
21559
+ if (timeoutOps.cb) {
21560
+ this._operationTimeoutCb = timeoutOps.cb;
21561
+ }
21562
+ }
21563
+ var self = this;
21564
+ if (this._operationTimeoutCb) {
21565
+ this._timeout = setTimeout(function() {
21566
+ self._operationTimeoutCb();
21567
+ }, self._operationTimeout);
21568
+ }
21569
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
21570
+ this._fn(this._attempts);
21571
+ };
21572
+ RetryOperation.prototype.try = function(fn) {
21573
+ console.log("Using RetryOperation.try() is deprecated");
21574
+ this.attempt(fn);
21575
+ };
21576
+ RetryOperation.prototype.start = function(fn) {
21577
+ console.log("Using RetryOperation.start() is deprecated");
21578
+ this.attempt(fn);
21579
+ };
21580
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
21581
+ RetryOperation.prototype.errors = function() {
21582
+ return this._errors;
21583
+ };
21584
+ RetryOperation.prototype.attempts = function() {
21585
+ return this._attempts;
21586
+ };
21587
+ RetryOperation.prototype.mainError = function() {
21588
+ if (this._errors.length === 0) {
21589
+ return null;
21590
+ }
21591
+ var counts = {};
21592
+ var mainError = null;
21593
+ var mainErrorCount = 0;
21594
+ for (var i = 0; i < this._errors.length; i++) {
21595
+ var error = this._errors[i];
21596
+ var message = error.message;
21597
+ var count = (counts[message] || 0) + 1;
21598
+ counts[message] = count;
21599
+ if (count >= mainErrorCount) {
21600
+ mainError = error;
21601
+ mainErrorCount = count;
21602
+ }
21603
+ }
21604
+ return mainError;
21605
+ };
21606
+ }
21607
+ });
21608
+
21609
+ // ../../node_modules/proper-lockfile/node_modules/retry/lib/retry.js
21610
+ var require_retry = __commonJS({
21611
+ "../../node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(exports$1) {
21612
+ var RetryOperation = require_retry_operation();
21613
+ exports$1.operation = function(options) {
21614
+ var timeouts = exports$1.timeouts(options);
21615
+ return new RetryOperation(timeouts, {
21616
+ forever: options && options.forever,
21617
+ unref: options && options.unref,
21618
+ maxRetryTime: options && options.maxRetryTime
21619
+ });
21620
+ };
21621
+ exports$1.timeouts = function(options) {
21622
+ if (options instanceof Array) {
21623
+ return [].concat(options);
21624
+ }
21625
+ var opts = {
21626
+ retries: 10,
21627
+ factor: 2,
21628
+ minTimeout: 1 * 1e3,
21629
+ maxTimeout: Infinity,
21630
+ randomize: false
21631
+ };
21632
+ for (var key in options) {
21633
+ opts[key] = options[key];
21634
+ }
21635
+ if (opts.minTimeout > opts.maxTimeout) {
21636
+ throw new Error("minTimeout is greater than maxTimeout");
21637
+ }
21638
+ var timeouts = [];
21639
+ for (var i = 0; i < opts.retries; i++) {
21640
+ timeouts.push(this.createTimeout(i, opts));
21641
+ }
21642
+ if (options && options.forever && !timeouts.length) {
21643
+ timeouts.push(this.createTimeout(i, opts));
21644
+ }
21645
+ timeouts.sort(function(a, b) {
21646
+ return a - b;
21647
+ });
21648
+ return timeouts;
21649
+ };
21650
+ exports$1.createTimeout = function(attempt, opts) {
21651
+ var random = opts.randomize ? Math.random() + 1 : 1;
21652
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
21653
+ timeout = Math.min(timeout, opts.maxTimeout);
21654
+ return timeout;
21655
+ };
21656
+ exports$1.wrap = function(obj, options, methods) {
21657
+ if (options instanceof Array) {
21658
+ methods = options;
21659
+ options = null;
21660
+ }
21661
+ if (!methods) {
21662
+ methods = [];
21663
+ for (var key in obj) {
21664
+ if (typeof obj[key] === "function") {
21665
+ methods.push(key);
21666
+ }
21667
+ }
21668
+ }
21669
+ for (var i = 0; i < methods.length; i++) {
21670
+ var method = methods[i];
21671
+ var original = obj[method];
21672
+ obj[method] = function retryWrapper(original2) {
21673
+ var op = exports$1.operation(options);
21674
+ var args = Array.prototype.slice.call(arguments, 1);
21675
+ var callback = args.pop();
21676
+ args.push(function(err) {
21677
+ if (op.retry(err)) {
21678
+ return;
21679
+ }
21680
+ if (err) {
21681
+ arguments[0] = op.mainError();
21682
+ }
21683
+ callback.apply(this, arguments);
21684
+ });
21685
+ op.attempt(function() {
21686
+ original2.apply(obj, args);
21687
+ });
21688
+ }.bind(obj, original);
21689
+ obj[method].options = options;
21690
+ }
21691
+ };
21692
+ }
21693
+ });
21694
+
21695
+ // ../../node_modules/proper-lockfile/node_modules/retry/index.js
21696
+ var require_retry2 = __commonJS({
21697
+ "../../node_modules/proper-lockfile/node_modules/retry/index.js"(exports$1, module) {
21698
+ module.exports = require_retry();
21699
+ }
21700
+ });
21701
+
21702
+ // ../../node_modules/signal-exit/signals.js
21703
+ var require_signals = __commonJS({
21704
+ "../../node_modules/signal-exit/signals.js"(exports$1, module) {
21705
+ module.exports = [
21706
+ "SIGABRT",
21707
+ "SIGALRM",
21708
+ "SIGHUP",
21709
+ "SIGINT",
21710
+ "SIGTERM"
21711
+ ];
21712
+ if (process.platform !== "win32") {
21713
+ module.exports.push(
21714
+ "SIGVTALRM",
21715
+ "SIGXCPU",
21716
+ "SIGXFSZ",
21717
+ "SIGUSR2",
21718
+ "SIGTRAP",
21719
+ "SIGSYS",
21720
+ "SIGQUIT",
21721
+ "SIGIOT"
21722
+ // should detect profiler and enable/disable accordingly.
21723
+ // see #21
21724
+ // 'SIGPROF'
21725
+ );
21726
+ }
21727
+ if (process.platform === "linux") {
21728
+ module.exports.push(
21729
+ "SIGIO",
21730
+ "SIGPOLL",
21731
+ "SIGPWR",
21732
+ "SIGSTKFLT",
21733
+ "SIGUNUSED"
21734
+ );
21735
+ }
21736
+ }
21737
+ });
21738
+
21739
+ // ../../node_modules/signal-exit/index.js
21740
+ var require_signal_exit = __commonJS({
21741
+ "../../node_modules/signal-exit/index.js"(exports$1, module) {
21742
+ var process2 = global.process;
21743
+ var processOk = function(process3) {
21744
+ return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
21745
+ };
21746
+ if (!processOk(process2)) {
21747
+ module.exports = function() {
21748
+ return function() {
21749
+ };
21750
+ };
21751
+ } else {
21752
+ assert = __require("assert");
21753
+ signals = require_signals();
21754
+ isWin = /^win/i.test(process2.platform);
21755
+ EE = __require("events");
21756
+ if (typeof EE !== "function") {
21757
+ EE = EE.EventEmitter;
21758
+ }
21759
+ if (process2.__signal_exit_emitter__) {
21760
+ emitter = process2.__signal_exit_emitter__;
21761
+ } else {
21762
+ emitter = process2.__signal_exit_emitter__ = new EE();
21763
+ emitter.count = 0;
21764
+ emitter.emitted = {};
21765
+ }
21766
+ if (!emitter.infinite) {
21767
+ emitter.setMaxListeners(Infinity);
21768
+ emitter.infinite = true;
21769
+ }
21770
+ module.exports = function(cb, opts) {
21771
+ if (!processOk(global.process)) {
21772
+ return function() {
21773
+ };
21774
+ }
21775
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
21776
+ if (loaded === false) {
21777
+ load2();
21778
+ }
21779
+ var ev = "exit";
21780
+ if (opts && opts.alwaysLast) {
21781
+ ev = "afterexit";
21782
+ }
21783
+ var remove = function() {
21784
+ emitter.removeListener(ev, cb);
21785
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
21786
+ unload();
21787
+ }
21788
+ };
21789
+ emitter.on(ev, cb);
21790
+ return remove;
21791
+ };
21792
+ unload = function unload2() {
21793
+ if (!loaded || !processOk(global.process)) {
21794
+ return;
21795
+ }
21796
+ loaded = false;
21797
+ signals.forEach(function(sig) {
21798
+ try {
21799
+ process2.removeListener(sig, sigListeners[sig]);
21800
+ } catch (er) {
21801
+ }
21802
+ });
21803
+ process2.emit = originalProcessEmit;
21804
+ process2.reallyExit = originalProcessReallyExit;
21805
+ emitter.count -= 1;
21806
+ };
21807
+ module.exports.unload = unload;
21808
+ emit = function emit2(event, code, signal) {
21809
+ if (emitter.emitted[event]) {
21810
+ return;
21811
+ }
21812
+ emitter.emitted[event] = true;
21813
+ emitter.emit(event, code, signal);
21814
+ };
21815
+ sigListeners = {};
21816
+ signals.forEach(function(sig) {
21817
+ sigListeners[sig] = function listener() {
21818
+ if (!processOk(global.process)) {
21819
+ return;
21820
+ }
21821
+ var listeners = process2.listeners(sig);
21822
+ if (listeners.length === emitter.count) {
21823
+ unload();
21824
+ emit("exit", null, sig);
21825
+ emit("afterexit", null, sig);
21826
+ if (isWin && sig === "SIGHUP") {
21827
+ sig = "SIGINT";
21828
+ }
21829
+ process2.kill(process2.pid, sig);
21830
+ }
21831
+ };
21832
+ });
21833
+ module.exports.signals = function() {
21834
+ return signals;
21835
+ };
21836
+ loaded = false;
21837
+ load2 = function load3() {
21838
+ if (loaded || !processOk(global.process)) {
21839
+ return;
21840
+ }
21841
+ loaded = true;
21842
+ emitter.count += 1;
21843
+ signals = signals.filter(function(sig) {
21844
+ try {
21845
+ process2.on(sig, sigListeners[sig]);
21846
+ return true;
21847
+ } catch (er) {
21848
+ return false;
21849
+ }
21850
+ });
21851
+ process2.emit = processEmit;
21852
+ process2.reallyExit = processReallyExit;
21853
+ };
21854
+ module.exports.load = load2;
21855
+ originalProcessReallyExit = process2.reallyExit;
21856
+ processReallyExit = function processReallyExit2(code) {
21857
+ if (!processOk(global.process)) {
21858
+ return;
21859
+ }
21860
+ process2.exitCode = code || /* istanbul ignore next */
21861
+ 0;
21862
+ emit("exit", process2.exitCode, null);
21863
+ emit("afterexit", process2.exitCode, null);
21864
+ originalProcessReallyExit.call(process2, process2.exitCode);
21865
+ };
21866
+ originalProcessEmit = process2.emit;
21867
+ processEmit = function processEmit2(ev, arg) {
21868
+ if (ev === "exit" && processOk(global.process)) {
21869
+ if (arg !== void 0) {
21870
+ process2.exitCode = arg;
21871
+ }
21872
+ var ret = originalProcessEmit.apply(this, arguments);
21873
+ emit("exit", process2.exitCode, null);
21874
+ emit("afterexit", process2.exitCode, null);
21875
+ return ret;
21876
+ } else {
21877
+ return originalProcessEmit.apply(this, arguments);
21878
+ }
21879
+ };
21880
+ }
21881
+ var assert;
21882
+ var signals;
21883
+ var isWin;
21884
+ var EE;
21885
+ var emitter;
21886
+ var unload;
21887
+ var emit;
21888
+ var sigListeners;
21889
+ var loaded;
21890
+ var load2;
21891
+ var originalProcessReallyExit;
21892
+ var processReallyExit;
21893
+ var originalProcessEmit;
21894
+ var processEmit;
21895
+ }
21896
+ });
21897
+
21898
+ // ../../node_modules/proper-lockfile/lib/mtime-precision.js
21899
+ var require_mtime_precision = __commonJS({
21900
+ "../../node_modules/proper-lockfile/lib/mtime-precision.js"(exports$1, module) {
21901
+ var cacheSymbol = /* @__PURE__ */ Symbol();
21902
+ function probe(file, fs3, callback) {
21903
+ const cachedPrecision = fs3[cacheSymbol];
21904
+ if (cachedPrecision) {
21905
+ return fs3.stat(file, (err, stat) => {
21906
+ if (err) {
21907
+ return callback(err);
21908
+ }
21909
+ callback(null, stat.mtime, cachedPrecision);
21910
+ });
21911
+ }
21912
+ const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
21913
+ fs3.utimes(file, mtime, mtime, (err) => {
21914
+ if (err) {
21915
+ return callback(err);
21916
+ }
21917
+ fs3.stat(file, (err2, stat) => {
21918
+ if (err2) {
21919
+ return callback(err2);
21920
+ }
21921
+ const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
21922
+ Object.defineProperty(fs3, cacheSymbol, { value: precision });
21923
+ callback(null, stat.mtime, precision);
21924
+ });
21925
+ });
21926
+ }
21927
+ function getMtime(precision) {
21928
+ let now = Date.now();
21929
+ if (precision === "s") {
21930
+ now = Math.ceil(now / 1e3) * 1e3;
21931
+ }
21932
+ return new Date(now);
21933
+ }
21934
+ module.exports.probe = probe;
21935
+ module.exports.getMtime = getMtime;
21936
+ }
21937
+ });
21938
+
21939
+ // ../../node_modules/proper-lockfile/lib/lockfile.js
21940
+ var require_lockfile = __commonJS({
21941
+ "../../node_modules/proper-lockfile/lib/lockfile.js"(exports$1, module) {
21942
+ var path4 = __require("path");
21943
+ var fs3 = require_graceful_fs();
21944
+ var retry = require_retry2();
21945
+ var onExit = require_signal_exit();
21946
+ var mtimePrecision = require_mtime_precision();
21947
+ var locks = {};
21948
+ function getLockFile(file, options) {
21949
+ return options.lockfilePath || `${file}.lock`;
21950
+ }
21951
+ function resolveCanonicalPath(file, options, callback) {
21952
+ if (!options.realpath) {
21953
+ return callback(null, path4.resolve(file));
21954
+ }
21955
+ options.fs.realpath(file, callback);
21956
+ }
21957
+ function acquireLock(file, options, callback) {
21958
+ const lockfilePath = getLockFile(file, options);
21959
+ options.fs.mkdir(lockfilePath, (err) => {
21960
+ if (!err) {
21961
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
21962
+ if (err2) {
21963
+ options.fs.rmdir(lockfilePath, () => {
21964
+ });
21965
+ return callback(err2);
21966
+ }
21967
+ callback(null, mtime, mtimePrecision2);
21968
+ });
21969
+ }
21970
+ if (err.code !== "EEXIST") {
21971
+ return callback(err);
21972
+ }
21973
+ if (options.stale <= 0) {
21974
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
21975
+ }
21976
+ options.fs.stat(lockfilePath, (err2, stat) => {
21977
+ if (err2) {
21978
+ if (err2.code === "ENOENT") {
21979
+ return acquireLock(file, { ...options, stale: 0 }, callback);
21980
+ }
21981
+ return callback(err2);
21982
+ }
21983
+ if (!isLockStale(stat, options)) {
21984
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
21985
+ }
21986
+ removeLock(file, options, (err3) => {
21987
+ if (err3) {
21988
+ return callback(err3);
21989
+ }
21990
+ acquireLock(file, { ...options, stale: 0 }, callback);
21991
+ });
21992
+ });
21993
+ });
21994
+ }
21995
+ function isLockStale(stat, options) {
21996
+ return stat.mtime.getTime() < Date.now() - options.stale;
21997
+ }
21998
+ function removeLock(file, options, callback) {
21999
+ options.fs.rmdir(getLockFile(file, options), (err) => {
22000
+ if (err && err.code !== "ENOENT") {
22001
+ return callback(err);
22002
+ }
22003
+ callback();
22004
+ });
22005
+ }
22006
+ function updateLock(file, options) {
22007
+ const lock2 = locks[file];
22008
+ if (lock2.updateTimeout) {
22009
+ return;
22010
+ }
22011
+ lock2.updateDelay = lock2.updateDelay || options.update;
22012
+ lock2.updateTimeout = setTimeout(() => {
22013
+ lock2.updateTimeout = null;
22014
+ options.fs.stat(lock2.lockfilePath, (err, stat) => {
22015
+ const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
22016
+ if (err) {
22017
+ if (err.code === "ENOENT" || isOverThreshold) {
22018
+ return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
22019
+ }
22020
+ lock2.updateDelay = 1e3;
22021
+ return updateLock(file, options);
22022
+ }
22023
+ const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime();
22024
+ if (!isMtimeOurs) {
22025
+ return setLockAsCompromised(
22026
+ file,
22027
+ lock2,
22028
+ Object.assign(
22029
+ new Error("Unable to update lock within the stale threshold"),
22030
+ { code: "ECOMPROMISED" }
22031
+ )
22032
+ );
22033
+ }
22034
+ const mtime = mtimePrecision.getMtime(lock2.mtimePrecision);
22035
+ options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
22036
+ const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now();
22037
+ if (lock2.released) {
22038
+ return;
22039
+ }
22040
+ if (err2) {
22041
+ if (err2.code === "ENOENT" || isOverThreshold2) {
22042
+ return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
22043
+ }
22044
+ lock2.updateDelay = 1e3;
22045
+ return updateLock(file, options);
22046
+ }
22047
+ lock2.mtime = mtime;
22048
+ lock2.lastUpdate = Date.now();
22049
+ lock2.updateDelay = null;
22050
+ updateLock(file, options);
22051
+ });
22052
+ });
22053
+ }, lock2.updateDelay);
22054
+ if (lock2.updateTimeout.unref) {
22055
+ lock2.updateTimeout.unref();
22056
+ }
22057
+ }
22058
+ function setLockAsCompromised(file, lock2, err) {
22059
+ lock2.released = true;
22060
+ if (lock2.updateTimeout) {
22061
+ clearTimeout(lock2.updateTimeout);
22062
+ }
22063
+ if (locks[file] === lock2) {
22064
+ delete locks[file];
22065
+ }
22066
+ lock2.options.onCompromised(err);
22067
+ }
22068
+ function lock(file, options, callback) {
22069
+ options = {
22070
+ stale: 1e4,
22071
+ update: null,
22072
+ realpath: true,
22073
+ retries: 0,
22074
+ fs: fs3,
22075
+ onCompromised: (err) => {
22076
+ throw err;
22077
+ },
22078
+ ...options
22079
+ };
22080
+ options.retries = options.retries || 0;
22081
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
22082
+ options.stale = Math.max(options.stale || 0, 2e3);
22083
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
22084
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1e3);
22085
+ resolveCanonicalPath(file, options, (err, file2) => {
22086
+ if (err) {
22087
+ return callback(err);
22088
+ }
22089
+ const operation = retry.operation(options.retries);
22090
+ operation.attempt(() => {
22091
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
22092
+ if (operation.retry(err2)) {
22093
+ return;
22094
+ }
22095
+ if (err2) {
22096
+ return callback(operation.mainError());
22097
+ }
22098
+ const lock2 = locks[file2] = {
22099
+ lockfilePath: getLockFile(file2, options),
22100
+ mtime,
22101
+ mtimePrecision: mtimePrecision2,
22102
+ options,
22103
+ lastUpdate: Date.now()
22104
+ };
22105
+ updateLock(file2, options);
22106
+ callback(null, (releasedCallback) => {
22107
+ if (lock2.released) {
22108
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
22109
+ }
22110
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
22111
+ });
22112
+ });
22113
+ });
22114
+ });
22115
+ }
22116
+ function unlock(file, options, callback) {
22117
+ options = {
22118
+ fs: fs3,
22119
+ realpath: true,
22120
+ ...options
22121
+ };
22122
+ resolveCanonicalPath(file, options, (err, file2) => {
22123
+ if (err) {
22124
+ return callback(err);
22125
+ }
22126
+ const lock2 = locks[file2];
22127
+ if (!lock2) {
22128
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
22129
+ }
22130
+ lock2.updateTimeout && clearTimeout(lock2.updateTimeout);
22131
+ lock2.released = true;
22132
+ delete locks[file2];
22133
+ removeLock(file2, options, callback);
22134
+ });
22135
+ }
22136
+ function check(file, options, callback) {
22137
+ options = {
22138
+ stale: 1e4,
22139
+ realpath: true,
22140
+ fs: fs3,
22141
+ ...options
22142
+ };
22143
+ options.stale = Math.max(options.stale || 0, 2e3);
22144
+ resolveCanonicalPath(file, options, (err, file2) => {
22145
+ if (err) {
22146
+ return callback(err);
22147
+ }
22148
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
22149
+ if (err2) {
22150
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
22151
+ }
22152
+ return callback(null, !isLockStale(stat, options));
22153
+ });
22154
+ });
22155
+ }
22156
+ function getLocks() {
22157
+ return locks;
22158
+ }
22159
+ onExit(() => {
22160
+ for (const file in locks) {
22161
+ const options = locks[file].options;
22162
+ try {
22163
+ options.fs.rmdirSync(getLockFile(file, options));
22164
+ } catch (e) {
22165
+ }
22166
+ }
22167
+ });
22168
+ module.exports.lock = lock;
22169
+ module.exports.unlock = unlock;
22170
+ module.exports.check = check;
22171
+ module.exports.getLocks = getLocks;
22172
+ }
22173
+ });
22174
+
22175
+ // ../../node_modules/proper-lockfile/lib/adapter.js
22176
+ var require_adapter = __commonJS({
22177
+ "../../node_modules/proper-lockfile/lib/adapter.js"(exports$1, module) {
22178
+ var fs3 = require_graceful_fs();
22179
+ function createSyncFs(fs4) {
22180
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
22181
+ const newFs = { ...fs4 };
22182
+ methods.forEach((method) => {
22183
+ newFs[method] = (...args) => {
22184
+ const callback = args.pop();
22185
+ let ret;
22186
+ try {
22187
+ ret = fs4[`${method}Sync`](...args);
22188
+ } catch (err) {
22189
+ return callback(err);
22190
+ }
22191
+ callback(null, ret);
22192
+ };
22193
+ });
22194
+ return newFs;
22195
+ }
22196
+ function toPromise(method) {
22197
+ return (...args) => new Promise((resolve3, reject) => {
22198
+ args.push((err, result2) => {
22199
+ if (err) {
22200
+ reject(err);
22201
+ } else {
22202
+ resolve3(result2);
22203
+ }
22204
+ });
22205
+ method(...args);
22206
+ });
22207
+ }
22208
+ function toSync(method) {
22209
+ return (...args) => {
22210
+ let err;
22211
+ let result2;
22212
+ args.push((_err, _result) => {
22213
+ err = _err;
22214
+ result2 = _result;
22215
+ });
22216
+ method(...args);
22217
+ if (err) {
22218
+ throw err;
22219
+ }
22220
+ return result2;
22221
+ };
22222
+ }
22223
+ function toSyncOptions(options) {
22224
+ options = { ...options };
22225
+ options.fs = createSyncFs(options.fs || fs3);
22226
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
22227
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
22228
+ }
22229
+ return options;
22230
+ }
22231
+ module.exports = {
22232
+ toPromise,
22233
+ toSync,
22234
+ toSyncOptions
22235
+ };
22236
+ }
22237
+ });
22238
+
22239
+ // ../../node_modules/proper-lockfile/index.js
22240
+ var require_proper_lockfile = __commonJS({
22241
+ "../../node_modules/proper-lockfile/index.js"(exports$1, module) {
22242
+ var lockfile2 = require_lockfile();
22243
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
22244
+ async function lock(file, options) {
22245
+ const release = await toPromise(lockfile2.lock)(file, options);
22246
+ return toPromise(release);
22247
+ }
22248
+ function lockSync(file, options) {
22249
+ const release = toSync(lockfile2.lock)(file, toSyncOptions(options));
22250
+ return toSync(release);
22251
+ }
22252
+ function unlock(file, options) {
22253
+ return toPromise(lockfile2.unlock)(file, options);
22254
+ }
22255
+ function unlockSync(file, options) {
22256
+ return toSync(lockfile2.unlock)(file, toSyncOptions(options));
22257
+ }
22258
+ function check(file, options) {
22259
+ return toPromise(lockfile2.check)(file, options);
22260
+ }
22261
+ function checkSync(file, options) {
22262
+ return toSync(lockfile2.check)(file, toSyncOptions(options));
22263
+ }
22264
+ module.exports = lock;
22265
+ module.exports.lock = lock;
22266
+ module.exports.unlock = unlock;
22267
+ module.exports.lockSync = lockSync;
22268
+ module.exports.unlockSync = unlockSync;
22269
+ module.exports.check = check;
22270
+ module.exports.checkSync = checkSync;
22271
+ }
22272
+ });
22273
+
22274
+ // package.json
22275
+ var package_default;
22276
+ var init_package = __esm({
22277
+ "package.json"() {
22278
+ package_default = {
22279
+ name: "@gravity-rail/cli",
22280
+ version: "0.55.0",
22281
+ description: "Gravity Rail CLI \u2014 manage workspaces from the command line",
22282
+ type: "module",
22283
+ bin: {
22284
+ gr: "./dist/gr.js"
22285
+ },
22286
+ exports: {
22287
+ ".": {
22288
+ types: "./dist/lib.d.ts",
22289
+ import: "./dist/lib.js"
22290
+ },
22291
+ "./lib": {
22292
+ types: "./dist/lib.d.ts",
22293
+ import: "./dist/lib.js"
22294
+ },
22295
+ "./cli-utils": {
22296
+ types: "./dist/cli-utils.d.ts",
22297
+ import: "./dist/cli-utils.js"
22298
+ }
22299
+ },
22300
+ files: [
22301
+ "dist"
22302
+ ],
22303
+ license: "MIT",
22304
+ repository: {
22305
+ type: "git",
22306
+ url: "https://developer.gravityrail.com"
22307
+ },
22308
+ homepage: "https://developer.gravityrail.com",
22309
+ keywords: [
22310
+ "gravity-rail",
22311
+ "cli",
22312
+ "healthcare",
22313
+ "workspace"
22314
+ ],
22315
+ engines: {
22316
+ node: ">=18"
22317
+ },
22318
+ scripts: {
22319
+ build: "tsup",
22320
+ "generate:skill-docs": "tsx scripts/generate-skill-docs.ts",
22321
+ clean: "rm -rf dist",
22322
+ typecheck: "tsc --noEmit",
22323
+ test: "jest --forceExit",
22324
+ "test:ci": "jest --forceExit --passWithNoTests --coverage --coverageReporters=json-summary --coverageReporters=text-summary"
22325
+ },
22326
+ dependencies: {
22327
+ "@gravity-rail/sdk": "workspace:^",
22328
+ "js-yaml": "^5.4.3",
22329
+ "proper-lockfile": "^4.1.2"
22330
+ },
22331
+ devDependencies: {
22332
+ "@gravity-rail/sandbox": "workspace:*",
22333
+ "@types/jest": "^30.0.0",
22334
+ "@types/node": "^26.6.4",
22335
+ "@types/proper-lockfile": "^4.1.4",
22336
+ jest: "^30.5.2",
22337
+ "ts-jest": "29.4.9",
22338
+ tsup: "^8.5.1",
22339
+ typescript: "^6.0.3",
22340
+ undici: "6.28.1"
22341
+ }
22342
+ };
22343
+ }
22344
+ });
20372
22345
  var DEFAULT_PROFILE, CredentialsManager;
20373
22346
  var init_credentials_manager = __esm({
20374
22347
  "src/cli-utils/credentials-manager.ts"() {
@@ -20733,7 +22706,7 @@ function validateTokenResponse(tokenData) {
20733
22706
  if (tokenData.expires_in != null) {
20734
22707
  const raw = Number(tokenData.expires_in);
20735
22708
  if (!Number.isFinite(raw) || raw < 60 || raw > 31536e3) {
20736
- stderr(` Warning: unusual expires_in value (${tokenData.expires_in}), using default`);
22709
+ stderr(" Warning: unusual expires_in value in the token response, using default");
20737
22710
  } else {
20738
22711
  expiresIn = raw;
20739
22712
  }
@@ -20953,7 +22926,8 @@ async function performOAuthFlow(options) {
20953
22926
  method: "POST",
20954
22927
  headers: {
20955
22928
  ...auth.headers,
20956
- "Content-Type": "application/x-www-form-urlencoded"
22929
+ "Content-Type": "application/x-www-form-urlencoded",
22930
+ "User-Agent": TOKEN_REQUEST_USER_AGENT
20957
22931
  },
20958
22932
  body: new URLSearchParams({
20959
22933
  grant_type: "authorization_code",
@@ -20990,53 +22964,150 @@ async function performOAuthFlow(options) {
20990
22964
  return { accessToken, credentials: creds };
20991
22965
  }
20992
22966
  }
20993
- async function refreshAccessToken(envConfig, creds, credentialsManager, env, profile) {
20994
- if (!creds.refreshToken || !creds.clientId) {
22967
+ function parseOAuthErrorCode(body) {
22968
+ try {
22969
+ const parsed = JSON.parse(body);
22970
+ if (parsed && typeof parsed === "object") {
22971
+ const code = parsed.error;
22972
+ if (typeof code === "string") return code;
22973
+ }
22974
+ } catch {
22975
+ }
22976
+ return void 0;
22977
+ }
22978
+ function isFreshEnough(creds) {
22979
+ return !creds.expiresAt || new Date(creds.expiresAt).getTime() > Date.now() + ACCESS_TOKEN_EXPIRY_BUFFER_MS;
22980
+ }
22981
+ async function acquireRefreshLock(credentialsPath) {
22982
+ try {
22983
+ const cacheDir = dirname$1(credentialsPath);
22984
+ if (!existsSync(cacheDir)) {
22985
+ mkdirSync(cacheDir, { recursive: true, mode: 448 });
22986
+ }
22987
+ return await import_proper_lockfile.default.lock(credentialsPath, {
22988
+ realpath: false,
22989
+ retries: REFRESH_LOCK_RETRIES,
22990
+ // The library default throws from a timer, which would crash the
22991
+ // command. Losing the lock mid-refresh is worth a warning, not that.
22992
+ // The library has already dropped its in-process record of the lock
22993
+ // by the time this runs, so the `release()` in `refreshAccessToken`'s
22994
+ // `finally` is refused (ENOTACQUIRED) and can never remove a lock
22995
+ // another process has since taken.
22996
+ onCompromised: () => {
22997
+ stderr(
22998
+ " Warning: lost the credential refresh lock; another gr process may refresh at the same time"
22999
+ );
23000
+ }
23001
+ });
23002
+ } catch {
23003
+ throw new Error(REFRESH_LOCK_FAILED);
23004
+ }
23005
+ }
23006
+ async function refreshAccessToken(envConfig, _creds, credentialsManager, env, profile) {
23007
+ const profileName = credentialsManager.resolveProfileName(profile, env);
23008
+ const release = await acquireRefreshLock(credentialsManager.getCredentialsFilePath(env));
23009
+ try {
23010
+ return await refreshUnderLock(envConfig, credentialsManager, env, profileName);
23011
+ } finally {
23012
+ await release().catch(() => void 0);
23013
+ }
23014
+ }
23015
+ async function refreshUnderLock(envConfig, credentialsManager, env, profileName) {
23016
+ const stored = credentialsManager.load(env, profileName);
23017
+ if (stored?.accessToken && isFreshEnough(stored)) {
23018
+ return stored;
23019
+ }
23020
+ if (!stored?.refreshToken || !stored.clientId) {
20995
23021
  stderr(" Cannot refresh: missing credentials (re-login required)");
20996
23022
  return null;
20997
23023
  }
20998
- const profileName = credentialsManager.resolveProfileName(profile, env);
20999
- const tokenUrl = `${envConfig.apiUrl}/api/v2/oauth/token`;
21000
- const auth = tokenRequestAuth(creds.clientId, creds.clientSecret);
23024
+ const presentedRefreshToken = stored.refreshToken;
23025
+ const auth = tokenRequestAuth(stored.clientId, stored.clientSecret);
23026
+ let response;
21001
23027
  try {
21002
- const response = await fetch(tokenUrl, {
23028
+ response = await fetch(`${envConfig.apiUrl}/api/v2/oauth/token`, {
21003
23029
  method: "POST",
21004
23030
  headers: {
21005
23031
  ...auth.headers,
21006
- "Content-Type": "application/x-www-form-urlencoded"
23032
+ "Content-Type": "application/x-www-form-urlencoded",
23033
+ "User-Agent": TOKEN_REQUEST_USER_AGENT
21007
23034
  },
21008
23035
  body: new URLSearchParams({
21009
23036
  grant_type: "refresh_token",
21010
- refresh_token: creds.refreshToken,
23037
+ refresh_token: presentedRefreshToken,
21011
23038
  ...auth.params
21012
- })
23039
+ }),
23040
+ // Bounds the request and the body reads below. Never retried: a
23041
+ // second POST of the same token is itself a reuse.
23042
+ //
23043
+ // Known residual: an abort only stops *this* side. If the server
23044
+ // commits the rotation after the deadline, the response carrying the
23045
+ // successor is lost and the stored token is spent; the next refresh
23046
+ // of it is a genuine invalid_grant and clears the profile. The client
23047
+ // cannot recover an unseen successor; the deadline is long enough
23048
+ // that this needs a token endpoint stalled for 15 s, not a slow one.
23049
+ signal: AbortSignal.timeout(REFRESH_REQUEST_TIMEOUT_MS)
21013
23050
  });
21014
- if (!response.ok) {
21015
- const body = await response.text();
21016
- const isExpiredRefresh = isOAuthError(body, "invalid_grant");
21017
- if (isExpiredRefresh) {
21018
- stderr(" Refresh token expired, re-login required");
21019
- } else {
21020
- stderr(` Token refresh failed (${response.status}), clearing credentials`);
23051
+ } catch {
23052
+ throw new Error(REFRESH_REQUEST_FAILED);
23053
+ }
23054
+ if (!response.ok) {
23055
+ let body;
23056
+ try {
23057
+ body = await response.text();
23058
+ } catch {
23059
+ throw new Error(REFRESH_REQUEST_FAILED);
23060
+ }
23061
+ if (response.status === 400 && parseOAuthErrorCode(body) === "invalid_grant") {
23062
+ const current = credentialsManager.load(env, profileName);
23063
+ if (!current) {
23064
+ stderr(" The server rejected the stored refresh token; re-login required");
23065
+ return null;
23066
+ }
23067
+ if (current.refreshToken === presentedRefreshToken) {
23068
+ credentialsManager.clear(env, profileName);
23069
+ stderr(" The server rejected the stored refresh token; re-login required");
23070
+ return null;
21021
23071
  }
21022
- credentialsManager.clear(env, profileName);
23072
+ throw new Error(REFRESH_SUPERSEDED);
23073
+ }
23074
+ if (parseOAuthErrorCode(body) === "invalid_client") {
23075
+ stderr(" The server no longer recognises this profile's OAuth client; re-login required");
21023
23076
  return null;
21024
23077
  }
21025
- const tokenData = await response.json();
21026
- const { accessToken, refreshToken, expiresIn } = validateTokenResponse(tokenData);
21027
- const updated = {
21028
- ...creds,
21029
- accessToken,
21030
- refreshToken: refreshToken ?? creds.refreshToken,
21031
- expiresAt: new Date(Date.now() + expiresIn * 1e3).toISOString()
21032
- };
21033
- credentialsManager.save(env, updated, profileName);
21034
- return updated;
21035
- } catch (err) {
21036
- stderr(` Token refresh error: ${err instanceof Error ? err.message : "unknown"}`);
21037
- credentialsManager.clear(env, profileName);
23078
+ throw new Error(REFRESH_FAILED);
23079
+ }
23080
+ let tokens;
23081
+ try {
23082
+ tokens = validateTokenResponse(await response.json());
23083
+ } catch {
23084
+ throw new Error(REFRESH_BAD_RESPONSE);
23085
+ }
23086
+ const latest = credentialsManager.load(env, profileName);
23087
+ if (!latest) {
23088
+ stderr(" Cannot refresh: missing credentials (re-login required)");
21038
23089
  return null;
21039
23090
  }
23091
+ if (latest.clientId !== stored.clientId || latest.refreshToken !== presentedRefreshToken) {
23092
+ if (latest.accessToken && isFreshEnough(latest)) {
23093
+ return latest;
23094
+ }
23095
+ throw new Error(REFRESH_SUPERSEDED);
23096
+ }
23097
+ const updated = {
23098
+ ...latest,
23099
+ accessToken: tokens.accessToken,
23100
+ // A server may omit `refresh_token` when it does not rotate; the
23101
+ // presented token then stays valid.
23102
+ refreshToken: tokens.refreshToken ?? presentedRefreshToken,
23103
+ expiresAt: new Date(Date.now() + tokens.expiresIn * 1e3).toISOString()
23104
+ };
23105
+ try {
23106
+ credentialsManager.save(env, updated, profileName);
23107
+ } catch {
23108
+ throw new Error(REFRESH_SAVE_FAILED);
23109
+ }
23110
+ return updated;
21040
23111
  }
21041
23112
  async function resolveNonInteractiveAuth(options) {
21042
23113
  const { env, envConfig, credentialsManager, profile } = options;
@@ -21061,12 +23132,23 @@ async function resolveNonInteractiveAuth(options) {
21061
23132
  if (!refreshed?.accessToken) return null;
21062
23133
  return { accessToken: refreshed.accessToken, credentials: refreshed };
21063
23134
  }
21064
- var ACCESS_TOKEN_EXPIRY_BUFFER_MS, FIRST_PARTY_CLIENT_METADATA_FIELD;
23135
+ var import_proper_lockfile, ACCESS_TOKEN_EXPIRY_BUFFER_MS, TOKEN_REQUEST_USER_AGENT, REFRESH_REQUEST_TIMEOUT_MS, REFRESH_LOCK_RETRIES, REFRESH_LOCK_FAILED, REFRESH_REQUEST_FAILED, REFRESH_FAILED, REFRESH_SUPERSEDED, REFRESH_BAD_RESPONSE, REFRESH_SAVE_FAILED, FIRST_PARTY_CLIENT_METADATA_FIELD;
21065
23136
  var init_auth = __esm({
21066
23137
  "src/cli-utils/auth.ts"() {
23138
+ import_proper_lockfile = __toESM(require_proper_lockfile());
23139
+ init_package();
21067
23140
  init_config();
21068
23141
  init_credentials_manager();
21069
23142
  ACCESS_TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1e3;
23143
+ TOKEN_REQUEST_USER_AGENT = `gravityrail-cli/${package_default.version}`;
23144
+ REFRESH_REQUEST_TIMEOUT_MS = 15e3;
23145
+ REFRESH_LOCK_RETRIES = { retries: 23, factor: 2, minTimeout: 100, maxTimeout: 1e3 };
23146
+ REFRESH_LOCK_FAILED = "Could not lock the credential store to refresh the access token (another gr process may still be refreshing). Stored credentials were kept; retry the command.";
23147
+ REFRESH_REQUEST_FAILED = "Token refresh did not complete (network error or timeout). Stored credentials were kept; retry the command.";
23148
+ REFRESH_FAILED = "Token refresh failed. Stored credentials were kept; retry the command, and log in again if it keeps failing.";
23149
+ REFRESH_SUPERSEDED = "Token refresh was rejected, but the stored credentials changed meanwhile and were kept. Retry the command.";
23150
+ REFRESH_BAD_RESPONSE = "Token refresh returned an unusable response. Stored credentials were kept; retry the command.";
23151
+ REFRESH_SAVE_FAILED = "Token refresh succeeded, but the new credentials could not be saved. Retry the command, and log in again if it keeps failing.";
21070
23152
  FIRST_PARTY_CLIENT_METADATA_FIELD = "gravityrail_first_party_cli_client_id";
21071
23153
  }
21072
23154
  });
@@ -22428,6 +24510,9 @@ function commandNeedsJsonBody(cmd, parsedArgs) {
22428
24510
  }
22429
24511
  return false;
22430
24512
  }
24513
+ if (cmd.acceptsJsonInput === true) {
24514
+ return true;
24515
+ }
22431
24516
  if (parsedArgs.data !== void 0 || parsedArgs.file !== void 0) {
22432
24517
  return true;
22433
24518
  }
@@ -22949,7 +25034,7 @@ var CommandRegistry = class {
22949
25034
  lines.push(" Requires: --allow-write");
22950
25035
  }
22951
25036
  const action = cmd.path[cmd.path.length - 1] ?? "";
22952
- const showsJsonHints = action === "create" || action === "update" || cmd.args?.some((a) => a.name === "data" || a.name === "file");
25037
+ const showsJsonHints = action === "create" || action === "update" || cmd.args?.some((a) => a.name === "data");
22953
25038
  if (cmd.args && cmd.args.length > 0) {
22954
25039
  lines.push("", "Arguments:");
22955
25040
  for (const arg of cmd.args) {
@@ -23282,6 +25367,8 @@ Optional
23282
25367
  chatModelConfig (object|null) Chat model overrides (temperature, thinking, \u2026)
23283
25368
  realtimeModelId (string|null) Voice/realtime model (see \`gr ai-models realtime\`)
23284
25369
  e.g. "xai:realtime:voice-agent-2" (Grok Voice Think Fast 2)
25370
+ or opt in to "xai:realtime:voice-agent-3" (Grok Voice
25371
+ 3.0; not yet cleared for strict-routing workflows)
23285
25372
  Native models auto-fill tts=native + default voice when
23286
25373
  realtimeModelConfig is omitted.
23287
25374
  realtimeModelConfig (object|null) Realtime config. Native example:
@@ -23303,6 +25390,10 @@ One-shot workflow voice WITHOUT creating an agent (preferred for "use Grok Voice
23303
25390
  gr workflows update --id <wf> -d '{"realtimeModelId":"xai:realtime:voice-agent-2"}'
23304
25391
  gr workflows publish --workflow-id <wf>
23305
25392
 
25393
+ Opt a workflow into Grok Voice 3.0 (same xAI voices as 2.0; not the default):
25394
+ gr workflows update --id <wf> -d '{"realtimeModelId":"xai:realtime:voice-agent-3"}'
25395
+ gr workflows publish --workflow-id <wf>
25396
+
23306
25397
  List models:
23307
25398
  gr ai-models chat | realtime | voice
23308
25399
  `;
@@ -23332,6 +25423,7 @@ ${AGENT_FIELD_REFERENCE}`,
23332
25423
  ],
23333
25424
  updateExamples: [
23334
25425
  `gr agents update --id 42 -d '{"realtimeModelId":"xai:realtime:voice-agent-2"}'`,
25426
+ `gr agents update --id 42 -d '{"realtimeModelId":"xai:realtime:voice-agent-3"}'`,
23335
25427
  "gr agents update --id 42 --file agent.json"
23336
25428
  ]
23337
25429
  })
@@ -25214,6 +27306,9 @@ Assistant / models (live on the DRAFT revision \u2014 publish to go live)
25214
27306
  update: null = voice off
25215
27307
  One-shot voice example:
25216
27308
  {"realtimeModelId":"xai:realtime:voice-agent-2"}
27309
+ Opt in to Grok Voice 3.0 (not the default; not yet
27310
+ cleared for routingMode "strict"):
27311
+ {"realtimeModelId":"xai:realtime:voice-agent-3"}
25217
27312
  A native model named WITHOUT a config gets
25218
27313
  tts=native + the provider fallback voice
25219
27314
  (xAI \u2192 xai:voice:eve, not cosmo). Explicit config:
@@ -25280,6 +27375,24 @@ var NOTE_COLUMNS = [
25280
27375
  },
25281
27376
  COL.created()
25282
27377
  ];
27378
+ var CONFIG_HEALTH_COLUMNS = [
27379
+ { header: "SEVERITY", getValue: (item) => String(item.severity ?? "") },
27380
+ { header: "CODE", getValue: (item) => String(item.code ?? "") },
27381
+ { header: "SUBJECT", getValue: (item) => String(item.subject?.type ?? "") },
27382
+ {
27383
+ header: "SUBJECT-ID",
27384
+ getValue: (item) => String(item.subject?.id ?? "")
27385
+ },
27386
+ {
27387
+ header: "TASK",
27388
+ getValue: (item) => String(item.remediation?.focus?.taskId ?? "")
27389
+ },
27390
+ {
27391
+ header: "MESSAGE",
27392
+ getValue: (item) => String(item.message ?? ""),
27393
+ maxWidth: 80
27394
+ }
27395
+ ];
25283
27396
  var CONTRIBUTOR_COLUMNS = [
25284
27397
  COL.id(),
25285
27398
  {
@@ -25480,6 +27593,26 @@ var workflowsDomain = {
25480
27593
  outputData(result2, ctx);
25481
27594
  }
25482
27595
  },
27596
+ // Config health (draft revision)
27597
+ {
27598
+ path: ["workflows", "validate-config"],
27599
+ description: "Report the workflow's configuration health issues (draft revision) \u2014 the same findings the editor shows",
27600
+ requiresWorkspace: true,
27601
+ args: [{ name: "id", description: "Workflow ID", required: true }],
27602
+ handler: async ({ ctx, workspace, args }) => {
27603
+ const result2 = await requireAuth(ctx).apiClient.getWorkflowConfigValidation(
27604
+ workspace,
27605
+ requireNumber(args, "id")
27606
+ );
27607
+ if (ctx.outputFormat === "json" || ctx.outputFormat === "jsonl") {
27608
+ outputData(result2, ctx);
27609
+ } else {
27610
+ outputData(result2.configHealthIssues ?? [], ctx, CONFIG_HEALTH_COLUMNS);
27611
+ stderr2(`issues=${(result2.configHealthIssues ?? []).length}
27612
+ `);
27613
+ }
27614
+ }
27615
+ },
25483
27616
  // Diagram
25484
27617
  {
25485
27618
  path: ["workflows", "diagram"],
@@ -25946,6 +28079,20 @@ ${WORKFLOW_FIELD_REFERENCE}`,
25946
28079
  ]
25947
28080
  };
25948
28081
  init_errors();
28082
+
28083
+ // src/lib/workspace-labels.ts
28084
+ init_errors();
28085
+ function parseLabelList(value) {
28086
+ if (value === void 0 || value === null || value === false) return [];
28087
+ const raw = Array.isArray(value) ? value.map(String) : [String(value)];
28088
+ const labels = raw.flatMap((entry) => entry.split(",")).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
28089
+ if (labels.length === 0 && raw.some((entry) => entry.trim().length > 0)) {
28090
+ throw new CLIError("--labels must name at least one label");
28091
+ }
28092
+ return labels;
28093
+ }
28094
+
28095
+ // src/domains/workspaces.ts
25949
28096
  init_output();
25950
28097
  init_pagination();
25951
28098
  init_context();
@@ -26760,11 +28907,16 @@ var workspacesDomain = {
26760
28907
  {
26761
28908
  name: "timezone",
26762
28909
  description: "IANA time zone (e.g. America/New_York). The create API does not take one, so the command waits for provisioning to finish and then sets it with a follow-up update. Without it the workspace has no timezone and Journey send windows and Routines run in UTC."
28910
+ },
28911
+ {
28912
+ name: "labels",
28913
+ description: "Comma-separated workspace labels to apply right after creation (e.g. production,sponsor-acme). Labels the organization has not used before are created. Webhook endpoints that select on these labels start covering the workspace at once."
26763
28914
  }
26764
28915
  ],
26765
28916
  examples: [
26766
28917
  'gr workspaces create --org <org-uuid> --name "Front Desk"',
26767
- 'gr workspaces create --org <org-uuid> --name "Front Desk" --timezone America/Chicago'
28918
+ 'gr workspaces create --org <org-uuid> --name "Front Desk" --timezone America/Chicago',
28919
+ 'gr workspaces create --org <org-uuid> --name "Front Desk" --labels production,sponsor-acme'
26768
28920
  ],
26769
28921
  handler: async ({ ctx, args }) => {
26770
28922
  const orgUuid = args.org ?? args["org-uuid"];
@@ -26772,6 +28924,7 @@ var workspacesDomain = {
26772
28924
  if (!orgUuid) throw new CLIError("Missing required argument: --org <org-uuid>");
26773
28925
  if (!name) throw new CLIError("Missing required argument: --name");
26774
28926
  const timezone = typeof args.timezone === "string" ? normalizeIanaTimeZone(args.timezone) : void 0;
28927
+ const labels = parseLabelList(args.labels);
26775
28928
  const payload = { name };
26776
28929
  if (args.slug) payload.slug = String(args.slug);
26777
28930
  if (args.template) payload.templateWorkspaceUuid = String(args.template);
@@ -26788,6 +28941,18 @@ var workspacesDomain = {
26788
28941
  }
26789
28942
  throw err;
26790
28943
  }
28944
+ if (labels.length > 0) {
28945
+ try {
28946
+ await client3.setWorkspaceLabels(orgUuid, result2.uuid, { labels });
28947
+ } catch (err) {
28948
+ const reason = err instanceof Error ? err.message : String(err);
28949
+ throw new CLIError(
28950
+ `Workspace ${result2.uuid} was created but its labels were not set: ${reason}
28951
+ Apply them with:
28952
+ gr org workspaces labels set --org ${orgUuid} --workspace-uuid ${result2.uuid} --labels ${labels.join(",")} --allow-write`
28953
+ );
28954
+ }
28955
+ }
26791
28956
  if (timezone) {
26792
28957
  const wsUuid = result2.uuid;
26793
28958
  stderr2(`Waiting for workspace ${wsUuid} to finish provisioning...`);
@@ -29322,6 +31487,73 @@ function parseIdList(value) {
29322
31487
  return num;
29323
31488
  });
29324
31489
  }
31490
+ function toGrantEntry(grant) {
31491
+ return { granteeMemberId: grant.granteeMemberId, accessMode: grant.accessMode };
31492
+ }
31493
+ var SHARING_COLUMNS = [
31494
+ { header: "ACCESS", getValue: (item) => item.access },
31495
+ {
31496
+ header: "SHAREABLE",
31497
+ getValue: (item) => String(item.shareable ?? "")
31498
+ },
31499
+ { header: "OWNER", getValue: (item) => String(item.ownerId ?? "") },
31500
+ { header: "GRANTS", getValue: (item) => String(item.grants.length) },
31501
+ {
31502
+ header: "ROLES",
31503
+ getValue: (item) => (item.roleAssociations ?? []).map((role) => role.memberRoleName).join(", ")
31504
+ }
31505
+ ];
31506
+ function sharingCommands(spec) {
31507
+ const { prefix, entityName, getMethod, updateMethod } = spec;
31508
+ const idArg2 = { name: "id", description: `${entityName} ID`, required: true };
31509
+ const cli = ["gr", ...prefix, "sharing"].join(" ");
31510
+ return [
31511
+ {
31512
+ path: [...prefix, "sharing", "get"],
31513
+ description: `Show a ${entityName}'s access level, grants and role associations`,
31514
+ requiresWorkspace: true,
31515
+ args: [idArg2],
31516
+ examples: [`${cli} get -w $WID --id 12`],
31517
+ handler: async ({ ctx, workspace, args }) => {
31518
+ const state = await requireAuth(ctx).apiClient[getMethod](
31519
+ workspace,
31520
+ requireNumber(args, "id")
31521
+ );
31522
+ outputData(state, ctx, SHARING_COLUMNS);
31523
+ }
31524
+ },
31525
+ {
31526
+ path: [...prefix, "sharing", "set"],
31527
+ description: `Change a ${entityName}'s sharing. The API replaces the whole sharing state, so this command reads the current state first and overrides only the keys you pass \u2014 omitting "grants" or "roleAssociations" keeps the existing ones rather than clearing them. Pass them explicitly (e.g. "grants": []) to replace.`,
31528
+ mutates: true,
31529
+ requiresWorkspace: true,
31530
+ args: [idArg2],
31531
+ examples: [
31532
+ `${cli} set -w $WID --id 12 --allow-write -d '{"access":"workspace"}'`,
31533
+ `${cli} set -w $WID --id 12 --allow-write -d '{"access":"private","grants":[]}'`
31534
+ ],
31535
+ handler: async ({ ctx, workspace, args, data }) => {
31536
+ if (data === void 0 || data === null || typeof data !== "object") {
31537
+ throw new CLIError(
31538
+ `Provide the fields to change as JSON via --data, --file, or stdin (e.g. '{"access":"workspace"}')`
31539
+ );
31540
+ }
31541
+ const patch = data;
31542
+ const client3 = requireAuth(ctx).apiClient;
31543
+ const id = requireNumber(args, "id");
31544
+ const current = await client3[getMethod](workspace, id);
31545
+ const next = {
31546
+ access: patch.access ?? current.access,
31547
+ shareable: patch.shareable ?? current.shareable ?? null,
31548
+ grants: patch.grants ?? current.grants.map(toGrantEntry),
31549
+ roleAssociations: patch.roleAssociations ?? current.roleAssociations ?? []
31550
+ };
31551
+ const state = await client3[updateMethod](workspace, id, next);
31552
+ outputData(state, ctx, SHARING_COLUMNS);
31553
+ }
31554
+ }
31555
+ ];
31556
+ }
29325
31557
  var COLUMNS10 = [
29326
31558
  COL.id(),
29327
31559
  COL.name(),
@@ -29483,6 +31715,18 @@ ${FILE_FIELD_REFERENCE}`
29483
31715
  outputData(results, ctx, folderSearchColumns(results));
29484
31716
  }
29485
31717
  },
31718
+ ...sharingCommands({
31719
+ prefix: ["files", "folders"],
31720
+ entityName: "folder",
31721
+ getMethod: "getFolderSharing",
31722
+ updateMethod: "updateFolderSharing"
31723
+ }),
31724
+ ...sharingCommands({
31725
+ prefix: ["files"],
31726
+ entityName: "file",
31727
+ getMethod: "getFileSharing",
31728
+ updateMethod: "updateFileSharing"
31729
+ }),
29486
31730
  // Labels sub-resource
29487
31731
  ...crudCommands({
29488
31732
  prefix: ["files", "labels"],
@@ -31404,7 +33648,7 @@ var OBS_COLUMNS = [
31404
33648
  ];
31405
33649
  var metricsDomain = {
31406
33650
  name: "metrics",
31407
- description: "Customer-defined outcome metrics (CEL expression or LLM rubric) with time-series readout",
33651
+ description: "Customer-defined outcome metrics (CEL expression, LLM rubric, Member cohort count, or an aggregate over Form records) with time-series readout",
31408
33652
  commands: [
31409
33653
  ...crudCommands({
31410
33654
  prefix: ["metrics"],
@@ -31417,14 +33661,16 @@ var metricsDomain = {
31417
33661
  columns: COLUMNS11,
31418
33662
  paginationSupport: "full",
31419
33663
  createExamples: [
31420
- `yarn gr metrics create -w $WID --allow-write --data '{"name":"SMS Channel Rate","metricType":"expression","celExpression":"chat.channel == \\"phone-sms\\"","unit":"rate"}'`,
31421
- `yarn gr metrics create -w $WID --allow-write --data '{"name":"Qualified Engagement","metricType":"rubric","evaluationPrompt":"Did the user show buying intent?","unit":"rate"}'`
33664
+ `yarn gr metrics create -w $WID --allow-write --data '{"name":"SMS Channel Rate","metricType":"expression","celExpression":"chat.channel == \\"phone-sms\\"","unit":"rate","workflowIds":[]}'`,
33665
+ `yarn gr metrics create -w $WID --allow-write --data '{"name":"Qualified Engagement","metricType":"rubric","evaluationPrompt":"Did the user show buying intent?","unit":"rate","workflowIds":[]}'`,
33666
+ `yarn gr metrics create -w $WID --allow-write --data '{"name":"HRV daily average","metricType":"record_aggregate","source":"data_record","sourceConfig":{"record":{"dataType":"daily_readings","aggregation":"avg","field":"record.hrv","dateField":"record.measured_on","groupBy":"record.athlete"}},"targetValue":65}'`,
33667
+ `yarn gr metrics create -w $WID --allow-write --data '{"name":"Open lab results","metricType":"record_aggregate","source":"data_record","sourceConfig":{"record":{"dataType":"lab_results","aggregation":"count","where":{"kind":"compare","field":"record.status","op":"eq","value":"open"}}}}'`
31422
33668
  ],
31423
- createHelp: "Create a metric definition. metricType is expression (CEL) or rubric (LLM). MVP source is chat only."
33669
+ createHelp: `Create a metric definition. metricType is expression (CEL) or rubric (LLM) for one reading per chat (pass workflowIds, [] for every workflow); filter_count for the daily size of a saved Member filter (source "member_filter", kind "gauge", sourceConfig.memberFilterId); or record_aggregate for an aggregate over a Form's records, computed from the records each time the series is read (source "data_record", sourceConfig.record). sourceConfig.record takes dataType (Form id or slug), aggregation (count | countDistinct | sum | avg | min | max), field (record.<fieldSlug>; required for all but count, a number field for sum/avg/min/max), dateField (a date or datetime field, default record.createdAt), where (Query IR predicate, see "yarn gr queries syntax") and groupBy (record.<fieldSlug>, one series per value). A record metric needs records:read to save and to read, and records:admin when it names an adminOnly field.`
31424
33670
  }),
31425
33671
  {
31426
33672
  path: ["metrics", "observations"],
31427
- description: "List raw observations for a metric in a date range (may include PHI reason)",
33673
+ description: "List raw observations for a metric in a date range (may include PHI reason). Not available for record_aggregate metrics, which store none: read their series",
31428
33674
  args: [
31429
33675
  { name: "id", required: true, description: "Metric ID" },
31430
33676
  {
@@ -31462,7 +33708,7 @@ var metricsDomain = {
31462
33708
  },
31463
33709
  {
31464
33710
  path: ["metrics", "series"],
31465
- description: "Time-bucketed aggregation for a metric (numeric only)",
33711
+ description: "Time-bucketed aggregation for a metric. A record_aggregate metric is computed from its Form records on each call and, with groupBy, also returns one series per group",
31466
33712
  args: [
31467
33713
  { name: "id", required: true, description: "Metric ID" },
31468
33714
  {
@@ -31478,7 +33724,7 @@ var metricsDomain = {
31478
33724
  { name: "bucket", description: "day | week (default day)" },
31479
33725
  {
31480
33726
  name: "aggregation",
31481
- description: "avg | sum | count | rate | last | passes (default varies by metric)"
33727
+ description: "avg | sum | count | rate | last | passes (default varies by metric). Omit for a record_aggregate metric: its definition names the aggregation"
31482
33728
  }
31483
33729
  ],
31484
33730
  requiresWorkspace: true,
@@ -31658,8 +33904,10 @@ function buildModelEvalBatchJobs(scenarios, models, rounds, warmup, realtimeMode
31658
33904
  var REALTIME_AUDIO_USD_PER_MIN = {
31659
33905
  "xai:realtime:voice-agent": 0.05,
31660
33906
  // Grok Voice Think Fast 1
31661
- "xai:realtime:voice-agent-2": 0.08
31662
- // Grok Voice Think Fast 2
33907
+ "xai:realtime:voice-agent-2": 0.08,
33908
+ // Grok Voice Think Fast 2 (pinned grok-voice-2.0)
33909
+ "xai:realtime:voice-agent-3": 0.08
33910
+ // Grok Voice 3.0 — same audio rate as 2.0
31663
33911
  };
31664
33912
  var DEFAULT_REALTIME_AUDIO_USD_PER_MIN = 0.08;
31665
33913
  var EST_AUDIO_MIN_PER_RUN = 3;
@@ -32489,6 +34737,91 @@ var qualificationsDomain = {
32489
34737
  ]
32490
34738
  };
32491
34739
 
34740
+ // src/domains/data-reports.ts
34741
+ init_output();
34742
+ init_context();
34743
+ init_errors();
34744
+ init_config();
34745
+ function parseRecordScope(value) {
34746
+ if (value === void 0) return void 0;
34747
+ if (value === "currentMember" || value === "allRecords") return value;
34748
+ throw new CLIError("--record-scope must be currentMember or allRecords");
34749
+ }
34750
+ function parseParameters(value) {
34751
+ if (value === void 0) return void 0;
34752
+ let parsed;
34753
+ try {
34754
+ parsed = typeof value === "string" ? JSON.parse(value) : value;
34755
+ } catch {
34756
+ throw new CLIError("--parameters must be a JSON object");
34757
+ }
34758
+ if (!isRecord(parsed)) throw new CLIError("--parameters must be a JSON object");
34759
+ const values = {};
34760
+ for (const [name, parameter] of Object.entries(parsed)) {
34761
+ if (typeof parameter !== "boolean" && typeof parameter !== "number" && typeof parameter !== "string") {
34762
+ throw new CLIError(`--parameters value for '${name}' must be a boolean, number or string`);
34763
+ }
34764
+ values[name] = parameter;
34765
+ }
34766
+ return values;
34767
+ }
34768
+ function buildPreviewRequest(data, args) {
34769
+ if (!isRecord(data)) {
34770
+ throw new CLIError("Report JSON required (--data, --file, or stdin)");
34771
+ }
34772
+ let request;
34773
+ if ("report" in data) {
34774
+ if (!isRecord(data.report)) {
34775
+ throw new CLIError("The request's 'report' must be a JSON object");
34776
+ }
34777
+ request = { ...data };
34778
+ } else if ("dataTypeUuid" in data && "query" in data) {
34779
+ request = { report: data };
34780
+ } else {
34781
+ throw new CLIError(
34782
+ "Body must be a request with a 'report' object, or a bare report with dataTypeUuid and query"
34783
+ );
34784
+ }
34785
+ const recordScope = parseRecordScope(args["record-scope"]);
34786
+ if (recordScope) request.recordScope = recordScope;
34787
+ const parameters = parseParameters(args["parameters"]);
34788
+ if (parameters) request.parameters = parameters;
34789
+ return request;
34790
+ }
34791
+ var dataReportsDomain = {
34792
+ name: "data-reports",
34793
+ description: "Form Reports: preview a report as the Agent would run it",
34794
+ commands: [
34795
+ {
34796
+ path: ["data-reports", "preview"],
34797
+ description: "Run a Form Reports report, saved or not, as the signed-in Member and show the rows or groups the Agent would get. Rows return at most 50 per call and aggregates at most 200 groups. Needs the agents:write and records:read scopes.",
34798
+ requiresWorkspace: true,
34799
+ acceptsJsonInput: true,
34800
+ args: [
34801
+ {
34802
+ name: "record-scope",
34803
+ description: "currentMember (default) limits the report to the signed-in Member's records; allRecords covers every record that Member may read",
34804
+ required: false
34805
+ },
34806
+ {
34807
+ name: "parameters",
34808
+ description: `Parameter values as a JSON object, e.g. '{"days":7}'. Omitted parameters use their defaults`,
34809
+ required: false
34810
+ }
34811
+ ],
34812
+ examples: [
34813
+ `yarn gr data-reports preview -w $UUID --record-scope allRecords --parameters '{"days":7}' --file report.json`,
34814
+ `yarn gr data-reports preview -w $UUID --data '{"report":{"name":"recent","description":"Latest rows","dataTypeUuid":"<form uuid>","query":{"sort":[{"field":"record.createdAt","dir":"desc"}],"limit":5}},"recordScope":"allRecords"}'`
34815
+ ],
34816
+ handler: async ({ ctx, workspace, args, data }) => {
34817
+ const request = buildPreviewRequest(data, args);
34818
+ const result2 = await requireAuth(ctx).apiClient.previewDataReport(workspace, request);
34819
+ outputSingle(result2, ctx);
34820
+ }
34821
+ }
34822
+ ]
34823
+ };
34824
+
32492
34825
  // src/domains/queries.ts
32493
34826
  init_output();
32494
34827
  init_context();
@@ -33421,6 +35754,9 @@ var abilitiesDomain = {
33421
35754
  description: "Allow creation before required app connections are configured"
33422
35755
  }
33423
35756
  ],
35757
+ examples: [
35758
+ 'yarn gr abilities enable --ability-type integration:data_reports --workflow-id 12 -w $UUID --data \'{"recordScope":"currentMember","reports":[{"name":"recent_entries","description":"The latest entries for this Member","dataTypeUuid":"<form uuid>","query":{"sort":[{"field":"record.createdAt","dir":"desc"}],"limit":5}}]}\' # Form Reports: no app editor; try a report first with `yarn gr data-reports preview`'
35759
+ ],
33424
35760
  handler: async ({ ctx, workspace, args, data }) => {
33425
35761
  const abilityType = args["ability-type"];
33426
35762
  if (typeof abilityType !== "string") throw new CLIError("--ability-type is required");
@@ -33940,7 +36276,8 @@ var NO_UUID_LOOKUP = /* @__PURE__ */ new Set([
33940
36276
  "import",
33941
36277
  "invoice",
33942
36278
  "workspace_config",
33943
- "data_record"
36279
+ "data_record",
36280
+ "recording"
33944
36281
  ]);
33945
36282
  var HYDRATORS = {
33946
36283
  workspace: async ({ client: client3 }, ref) => (await client3.getWorkspace(ref.uuid)).name,
@@ -34773,7 +37110,7 @@ var aiModelsDomain = {
34773
37110
  },
34774
37111
  {
34775
37112
  path: ["ai-models", "realtime"],
34776
- description: "List realtime/voice stacks (use as realtimeModelId). e.g. xai:realtime:voice-agent-2 = Grok Voice Think Fast 2",
37113
+ description: "List realtime/voice stacks (use as realtimeModelId). e.g. xai:realtime:voice-agent-2 = Grok Voice Think Fast 2 (default); xai:realtime:voice-agent-3 = Grok Voice 3.0 (explicit opt-in)",
34777
37114
  requiresWorkspace: false,
34778
37115
  handler: async ({ ctx }) => {
34779
37116
  const result2 = await requireAuth(ctx).apiClient.getRealtimeModels();
@@ -36321,6 +38658,7 @@ init_dist();
36321
38658
  init_context();
36322
38659
  init_errors();
36323
38660
  init_output();
38661
+ init_pagination();
36324
38662
  var ORG_COLUMNS = [
36325
38663
  { header: "ID", getValue: (item) => String(item.organizationId ?? "") },
36326
38664
  { header: "NAME", getValue: (item) => item.organizationName || "" },
@@ -36926,6 +39264,17 @@ var ORG_WEBHOOK_COLUMNS = [
36926
39264
  header: "WORKSPACES",
36927
39265
  getValue: (item) => item.limitedToWorkspaces ? item.workspaceUuids.join(",") : "all (organization-wide)",
36928
39266
  maxWidth: 80
39267
+ },
39268
+ {
39269
+ // A workspace is covered when it carries ALL of these labels (in
39270
+ // addition to the explicit WORKSPACES).
39271
+ header: "LABELS",
39272
+ getValue: (item) => (item.labelSelector ?? []).map((label) => label.slug).join("+"),
39273
+ maxWidth: 60
39274
+ },
39275
+ {
39276
+ header: "RECENT FAILURES",
39277
+ getValue: (item) => (item.recentFailures ?? []).map((failure) => `${failure.failureClass} (${failure.count})`).join(", ")
36929
39278
  }
36930
39279
  ];
36931
39280
  function requireWebhookEndpointUuid(args) {
@@ -36960,9 +39309,298 @@ function webhookStatusCommand(action) {
36960
39309
  }
36961
39310
  };
36962
39311
  }
39312
+ var ORG_WORKSPACE_COLUMNS = [
39313
+ { header: "UUID", getValue: (item) => item.uuid },
39314
+ { header: "NAME", getValue: (item) => item.name, maxWidth: 40 },
39315
+ { header: "SLUG", getValue: (item) => item.slug },
39316
+ { header: "STATUS", getValue: (item) => String(item.status) },
39317
+ { header: "TIMEZONE", getValue: (item) => item.timezone ?? "-" },
39318
+ { header: "CREATED", getValue: (item) => item.createdAt }
39319
+ ];
39320
+ var orgWorkspaceCommands = [
39321
+ {
39322
+ path: ["org", "workspaces", "list"],
39323
+ description: "List every workspace in an organization, newest page first (read-only). Prefer this over `gr workspaces list --org` for anything fleet-wide: that command reads an unpaginated endpoint and sees only the first page of workspaces. Use --all to fetch the complete list.",
39324
+ requiresWorkspace: false,
39325
+ args: [
39326
+ ORG_UUID_ARG2,
39327
+ { name: "page", description: "Page number (default: 1)" },
39328
+ { name: "page-size", description: "Page size" },
39329
+ { name: "all", description: "Fetch all pages", isFlag: true },
39330
+ { name: "search", description: "Filter by name or slug (server-side)" }
39331
+ ],
39332
+ examples: [
39333
+ "yarn gr org workspaces list --org $ORG_UUID --all",
39334
+ "yarn gr org workspaces list --org $ORG_UUID --search gastro -o json"
39335
+ ],
39336
+ handler: async (hctx) => {
39337
+ const orgRef = requireOrgRef(hctx.args);
39338
+ const pag = parsePaginationArgs(hctx.args);
39339
+ const search = typeof hctx.args.search === "string" ? hctx.args.search : void 0;
39340
+ const client3 = requireAuth(hctx.ctx).apiClient;
39341
+ if (pag.all) {
39342
+ const allItems = await fetchAllPages(
39343
+ ({ page, pageSize }) => client3.getOrganizationWorkspaces(orgRef, {
39344
+ page,
39345
+ pageSize,
39346
+ ...search ? { search } : {}
39347
+ })
39348
+ );
39349
+ outputData(allItems, hctx.ctx, ORG_WORKSPACE_COLUMNS);
39350
+ return;
39351
+ }
39352
+ const options = {};
39353
+ if (pag.page) options.page = pag.page;
39354
+ if (pag.pageSize) options.pageSize = pag.pageSize;
39355
+ if (search) options.search = search;
39356
+ const result2 = await client3.getOrganizationWorkspaces(orgRef, options);
39357
+ outputData(listResult(result2, true), hctx.ctx, ORG_WORKSPACE_COLUMNS);
39358
+ }
39359
+ }
39360
+ ];
39361
+ function requireArg2(args, name) {
39362
+ const value = args[name];
39363
+ if (typeof value !== "string" || !value.trim()) {
39364
+ throw new CLIError(`Missing required argument: --${name}`);
39365
+ }
39366
+ return value.trim();
39367
+ }
39368
+ function optionalArg(args, name) {
39369
+ const value = args[name];
39370
+ if (value === void 0) return void 0;
39371
+ if (typeof value !== "string" || !value.trim()) {
39372
+ throw new CLIError(`Invalid argument: --${name}`);
39373
+ }
39374
+ return value.trim();
39375
+ }
39376
+ var DELIVERY_LOG_COLUMNS = [
39377
+ { header: "EVENT", getValue: (item) => item.eventType },
39378
+ { header: "STATUS", getValue: (item) => item.status },
39379
+ { header: "DEDUPE KEY", getValue: (item) => item.dedupeKey, maxWidth: 48 },
39380
+ { header: "OCCURRED", getValue: (item) => item.occurredAt },
39381
+ { header: "ATTEMPTS", getValue: (item) => String(item.attempts) },
39382
+ { header: "LAST FAILURE", getValue: (item) => item.lastFailureClass || "\u2014" }
39383
+ ];
36963
39384
  var webhookCommands = [
36964
39385
  webhookStatusCommand("pause"),
36965
39386
  webhookStatusCommand("resume"),
39387
+ {
39388
+ path: ["org", "webhooks", "create"],
39389
+ description: "Create an organization webhook endpoint. The signing secret is printed once in this response and is not shown again. Requires organization admin access.",
39390
+ mutates: true,
39391
+ requiresWorkspace: false,
39392
+ args: [
39393
+ ORG_UUID_ARG2,
39394
+ { name: "name", description: "Endpoint name", required: true },
39395
+ { name: "url", description: "HTTPS endpoint URL", required: true },
39396
+ {
39397
+ name: "event-type",
39398
+ description: "Subscribed event type (repeat for more than one)",
39399
+ required: true,
39400
+ repeatable: true
39401
+ },
39402
+ {
39403
+ name: "workspace-uuid",
39404
+ description: "Limit coverage to this workspace (repeatable). Omit to cover every workspace in the organization.",
39405
+ repeatable: true
39406
+ },
39407
+ {
39408
+ name: "signing-secret",
39409
+ description: "Client-supplied signing secret. Omit to have one generated."
39410
+ }
39411
+ ],
39412
+ examples: [
39413
+ 'yarn gr org webhooks create --org $ORG_UUID --name "Rysun" --url https://example.com/hook --event-type data_record.created --allow-write'
39414
+ ],
39415
+ handler: async (hctx) => {
39416
+ const eventTypes = repeatedValues(hctx.args, "event-type");
39417
+ if (eventTypes.length === 0) {
39418
+ throw new CLIError("Missing required argument: --event-type");
39419
+ }
39420
+ const signingSecret = optionalArg(hctx.args, "signing-secret");
39421
+ const created = await requireAuth(hctx.ctx).apiClient.createOrgWebhookEndpoint(
39422
+ requireOrgRef(hctx.args),
39423
+ {
39424
+ name: requireArg2(hctx.args, "name"),
39425
+ url: requireArg2(hctx.args, "url"),
39426
+ eventTypes,
39427
+ workspaceUuids: repeatedValues(hctx.args, "workspace-uuid"),
39428
+ ...signingSecret ? { signingSecret } : {}
39429
+ }
39430
+ );
39431
+ hint(hctx.ctx, ["Signing secret is in this response and is not shown again."]);
39432
+ outputSingle(created, hctx.ctx);
39433
+ }
39434
+ },
39435
+ {
39436
+ path: ["org", "webhooks", "update"],
39437
+ description: "Update an organization webhook endpoint. A rotated signing secret is not echoed. Requires organization admin access.",
39438
+ mutates: true,
39439
+ requiresWorkspace: false,
39440
+ args: [
39441
+ ORG_UUID_ARG2,
39442
+ { name: "endpoint-uuid", aliases: ["id"], description: "Endpoint UUID", required: true },
39443
+ { name: "name", description: "New endpoint name" },
39444
+ { name: "url", description: "New HTTPS endpoint URL" },
39445
+ {
39446
+ name: "event-type",
39447
+ description: "Replace the subscription list (repeat for more than one)",
39448
+ repeatable: true
39449
+ },
39450
+ {
39451
+ name: "workspace-uuid",
39452
+ description: "Replace workspace coverage with this workspace (repeatable)",
39453
+ repeatable: true
39454
+ },
39455
+ {
39456
+ name: "all-workspaces",
39457
+ description: "Cover every workspace in the organization",
39458
+ isFlag: true
39459
+ },
39460
+ { name: "status", description: "active or paused" },
39461
+ {
39462
+ name: "signing-secret",
39463
+ description: "Rotate the signing secret. The new value is not printed."
39464
+ }
39465
+ ],
39466
+ examples: [
39467
+ "yarn gr org webhooks update --org $ORG_UUID --endpoint-uuid $ENDPOINT_UUID --status paused --allow-write"
39468
+ ],
39469
+ handler: async (hctx) => {
39470
+ const workspaceUuids = repeatedValues(hctx.args, "workspace-uuid");
39471
+ const allWorkspaces = hctx.args["all-workspaces"] === true;
39472
+ if (allWorkspaces && workspaceUuids.length > 0) {
39473
+ throw new CLIError("Pass either --all-workspaces or --workspace-uuid, not both");
39474
+ }
39475
+ const eventTypes = repeatedValues(hctx.args, "event-type");
39476
+ const status = optionalArg(hctx.args, "status");
39477
+ if (status !== void 0 && status !== "active" && status !== "paused") {
39478
+ throw new CLIError("--status must be active or paused");
39479
+ }
39480
+ const signingSecret = optionalArg(hctx.args, "signing-secret");
39481
+ const data = {};
39482
+ const name = optionalArg(hctx.args, "name");
39483
+ const url = optionalArg(hctx.args, "url");
39484
+ if (name) data.name = name;
39485
+ if (url) data.url = url;
39486
+ if (eventTypes.length > 0) data.eventTypes = eventTypes;
39487
+ if (allWorkspaces) data.workspaceUuids = [];
39488
+ else if (workspaceUuids.length > 0) data.workspaceUuids = workspaceUuids;
39489
+ if (status) data.status = status;
39490
+ if (signingSecret) data.signingSecret = signingSecret;
39491
+ if (Object.keys(data).length === 0) {
39492
+ throw new CLIError("Nothing to update");
39493
+ }
39494
+ const result2 = await requireAuth(hctx.ctx).apiClient.updateOrgWebhookEndpoint(
39495
+ requireOrgRef(hctx.args),
39496
+ requireWebhookEndpointUuid(hctx.args),
39497
+ data
39498
+ );
39499
+ const { signingSecret: _rotatedSecret, ...printable } = result2;
39500
+ outputSingle(printable, hctx.ctx, ORG_WEBHOOK_COLUMNS);
39501
+ }
39502
+ },
39503
+ {
39504
+ path: ["org", "webhooks", "test-send"],
39505
+ description: "Send one test payload to an endpoint. Writes no delivery row. Requires organization admin access.",
39506
+ mutates: true,
39507
+ requiresWorkspace: false,
39508
+ args: [
39509
+ ORG_UUID_ARG2,
39510
+ { name: "endpoint-uuid", aliases: ["id"], description: "Endpoint UUID", required: true },
39511
+ { name: "event-type", description: "Event type to send", required: true },
39512
+ {
39513
+ name: "payload",
39514
+ description: "JSON object to send instead of the server sample"
39515
+ }
39516
+ ],
39517
+ examples: [
39518
+ "yarn gr org webhooks test-send --org $ORG_UUID --endpoint-uuid $ENDPOINT_UUID --event-type data_record.created --allow-write"
39519
+ ],
39520
+ handler: async (hctx) => {
39521
+ const rawPayload = optionalArg(hctx.args, "payload");
39522
+ let payload;
39523
+ if (rawPayload !== void 0) {
39524
+ let parsed;
39525
+ try {
39526
+ parsed = JSON.parse(rawPayload);
39527
+ } catch {
39528
+ throw new CLIError("--payload must be a JSON object");
39529
+ }
39530
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
39531
+ throw new CLIError("--payload must be a JSON object");
39532
+ }
39533
+ payload = parsed;
39534
+ }
39535
+ const result2 = await requireAuth(hctx.ctx).apiClient.testOrgWebhookEndpoint(
39536
+ requireOrgRef(hctx.args),
39537
+ requireWebhookEndpointUuid(hctx.args),
39538
+ {
39539
+ eventType: requireArg2(hctx.args, "event-type"),
39540
+ ...payload ? { payload } : {}
39541
+ }
39542
+ );
39543
+ outputSingle(result2, hctx.ctx);
39544
+ }
39545
+ },
39546
+ {
39547
+ path: ["org", "webhooks", "deliveries"],
39548
+ description: "Delivery log for one organization webhook endpoint. Event type, status, dedupe key, occurred-at, attempt count, and last failure class. The event envelope is not printed.",
39549
+ requiresWorkspace: false,
39550
+ args: [
39551
+ ORG_UUID_ARG2,
39552
+ { name: "endpoint-uuid", aliases: ["id"], description: "Endpoint UUID", required: true },
39553
+ { name: "limit", description: "Page size (default 50)" }
39554
+ ],
39555
+ examples: ["yarn gr org webhooks deliveries --org $ORG_UUID --endpoint-uuid $ENDPOINT_UUID"],
39556
+ handler: async (hctx) => {
39557
+ const limitRaw = optionalArg(hctx.args, "limit");
39558
+ let limit = 50;
39559
+ if (limitRaw !== void 0) {
39560
+ limit = Number(limitRaw);
39561
+ if (!Number.isInteger(limit) || limit < 1) {
39562
+ throw new CLIError("--limit must be a positive integer");
39563
+ }
39564
+ }
39565
+ const page = await requireAuth(hctx.ctx).apiClient.listOrgWebhookEndpointDeliveries(
39566
+ requireOrgRef(hctx.args),
39567
+ requireWebhookEndpointUuid(hctx.args),
39568
+ limit
39569
+ );
39570
+ const rows = page.items.map((item) => {
39571
+ const latest = item.attempts.at(-1);
39572
+ return {
39573
+ eventType: item.eventType,
39574
+ status: item.status,
39575
+ dedupeKey: item.dedupeKey,
39576
+ occurredAt: item.occurredAt,
39577
+ attempts: item.attempts.length,
39578
+ lastFailureClass: latest?.failureClass ?? latest?.errorType ?? ""
39579
+ };
39580
+ });
39581
+ outputData(rows, hctx.ctx, DELIVERY_LOG_COLUMNS);
39582
+ }
39583
+ },
39584
+ {
39585
+ path: ["org", "webhooks", "discard-pending"],
39586
+ description: "Expire a paused or disabled endpoint's pending deliveries so a resume does not re-send a backlog the receiver keeps rejecting. Dead-lettered deliveries are untouched; expired ones stay replayable. Requires organization admin access.",
39587
+ mutates: true,
39588
+ requiresWorkspace: false,
39589
+ args: [
39590
+ ORG_UUID_ARG2,
39591
+ { name: "endpoint-uuid", aliases: ["id"], description: "Endpoint UUID", required: true }
39592
+ ],
39593
+ examples: [
39594
+ "yarn gr org webhooks discard-pending --org $ORG_UUID --endpoint-uuid $ENDPOINT_UUID --allow-write"
39595
+ ],
39596
+ handler: async (hctx) => {
39597
+ const result2 = await requireAuth(hctx.ctx).apiClient.discardPendingOrgWebhookDeliveries(
39598
+ requireOrgRef(hctx.args),
39599
+ requireWebhookEndpointUuid(hctx.args)
39600
+ );
39601
+ outputSingle(result2, hctx.ctx);
39602
+ }
39603
+ },
36966
39604
  {
36967
39605
  path: ["org", "webhooks", "list"],
36968
39606
  description: "List an organization's webhook endpoints (read-only). Each row carries the destination host fingerprint and a masked signing secret, never the URL or a usable secret.",
@@ -36995,9 +39633,93 @@ var webhookCommands = [
36995
39633
  }
36996
39634
  }
36997
39635
  ];
39636
+ var WORKSPACE_LABEL_COLUMNS = [
39637
+ { header: "SLUG", getValue: (item) => item.slug },
39638
+ { header: "NAME", getValue: (item) => item.name },
39639
+ { header: "WORKSPACES", getValue: (item) => String(item.workspaceCount) },
39640
+ { header: "WEBHOOK SELECTORS", getValue: (item) => String(item.webhookSelectorCount) },
39641
+ { header: "UUID", getValue: (item) => item.uuid }
39642
+ ];
39643
+ var LABEL_SUMMARY_COLUMNS = [
39644
+ { header: "SLUG", getValue: (item) => item.slug },
39645
+ { header: "NAME", getValue: (item) => item.name },
39646
+ { header: "UUID", getValue: (item) => item.uuid }
39647
+ ];
39648
+ function requireWorkspaceUuidArg(args) {
39649
+ const value = args["workspace-uuid"] ?? args.workspace;
39650
+ if (typeof value !== "string" || !value.trim()) {
39651
+ throw new CLIError("Missing required argument: --workspace-uuid");
39652
+ }
39653
+ return value.trim();
39654
+ }
39655
+ var WORKSPACE_UUID_ARG = {
39656
+ name: "workspace-uuid",
39657
+ aliases: ["workspace"],
39658
+ description: "Workspace UUID (a workspace of this organization)",
39659
+ required: true
39660
+ };
39661
+ var workspaceLabelCommands = [
39662
+ {
39663
+ path: ["org", "labels", "list"],
39664
+ description: "List the organization's workspace labels, with how many workspaces carry each and how many webhook label selectors require it",
39665
+ requiresWorkspace: false,
39666
+ args: [ORG_UUID_ARG2],
39667
+ examples: ["yarn gr org labels list --org $ORG_UUID -o json"],
39668
+ handler: async (hctx) => {
39669
+ const result2 = await requireAuth(hctx.ctx).apiClient.listWorkspaceLabels(
39670
+ requireOrgRef(hctx.args)
39671
+ );
39672
+ outputData(result2, hctx.ctx, WORKSPACE_LABEL_COLUMNS);
39673
+ }
39674
+ },
39675
+ {
39676
+ path: ["org", "workspaces", "labels", "get"],
39677
+ description: "Show the labels one workspace of the organization carries",
39678
+ requiresWorkspace: false,
39679
+ args: [ORG_UUID_ARG2, WORKSPACE_UUID_ARG],
39680
+ examples: [
39681
+ "yarn gr org workspaces labels get --org $ORG_UUID --workspace-uuid $WORKSPACE_UUID -o json"
39682
+ ],
39683
+ handler: async (hctx) => {
39684
+ const result2 = await requireAuth(hctx.ctx).apiClient.getWorkspaceLabels(
39685
+ requireOrgRef(hctx.args),
39686
+ requireWorkspaceUuidArg(hctx.args)
39687
+ );
39688
+ outputData(result2.labels, hctx.ctx, LABEL_SUMMARY_COLUMNS);
39689
+ }
39690
+ },
39691
+ {
39692
+ path: ["org", "workspaces", "labels", "set"],
39693
+ description: "Replace a workspace's labels with exactly the given set. Requires organization admin access. Labels the organization has not used before are created. Webhook endpoints selecting on these labels start or stop covering the workspace immediately.",
39694
+ mutates: true,
39695
+ requiresWorkspace: false,
39696
+ args: [
39697
+ ORG_UUID_ARG2,
39698
+ WORKSPACE_UUID_ARG,
39699
+ {
39700
+ name: "labels",
39701
+ description: "Comma-separated label slugs; pass an empty string to remove all labels",
39702
+ required: true
39703
+ }
39704
+ ],
39705
+ examples: [
39706
+ "yarn gr org workspaces labels set --org $ORG_UUID --workspace-uuid $WORKSPACE_UUID --labels production,sponsor-acme --allow-write"
39707
+ ],
39708
+ handler: async (hctx) => {
39709
+ const raw = hctx.args.labels;
39710
+ if (raw === void 0) throw new CLIError("Missing required argument: --labels");
39711
+ const result2 = await requireAuth(hctx.ctx).apiClient.setWorkspaceLabels(
39712
+ requireOrgRef(hctx.args),
39713
+ requireWorkspaceUuidArg(hctx.args),
39714
+ { labels: raw === "" ? [] : parseLabelList(raw) }
39715
+ );
39716
+ outputData(result2.labels, hctx.ctx, LABEL_SUMMARY_COLUMNS);
39717
+ }
39718
+ }
39719
+ ];
36998
39720
  var orgDomain = {
36999
39721
  name: "org",
37000
- description: "Organization membership, domains, and webhook endpoints",
39722
+ description: "Organization membership, domains, webhook endpoints, and workspace labels",
37001
39723
  commands: [
37002
39724
  {
37003
39725
  path: ["org", "list"],
@@ -37022,7 +39744,9 @@ var orgDomain = {
37022
39744
  }
37023
39745
  },
37024
39746
  ...domainCommands,
39747
+ ...orgWorkspaceCommands,
37025
39748
  ...webhookCommands,
39749
+ ...workspaceLabelCommands,
37026
39750
  orgMemberUpdateCommand()
37027
39751
  ]
37028
39752
  };
@@ -40392,6 +43116,71 @@ var ENCOUNTER_RUN_COLUMNS = [
40392
43116
  getValue: (item) => summarizeReasons(item.attribution?.collections, "errorReasonCounts")
40393
43117
  }
40394
43118
  ];
43119
+ var ONBOARDING_START_COLUMNS = [
43120
+ { header: "MODE", getValue: (item) => item.mode ?? "" },
43121
+ { header: "WORKFLOW ID", getValue: (item) => item.workflowId ?? "" },
43122
+ { header: "RUN ID", getValue: (item) => item.runId ?? "" }
43123
+ ];
43124
+ var ONBOARDING_PAIR_COLUMNS = [
43125
+ { header: "DEPARTMENT", getValue: (item) => String(item.departmentId ?? "") },
43126
+ { header: "PATIENT STATUS", getValue: (item) => item.patientStatus ?? "" },
43127
+ { header: "STATUS", getValue: (item) => item.status ?? "" },
43128
+ { header: "STOP REASON", getValue: (item) => item.stopReason ?? "" },
43129
+ { header: "GEN", getValue: (item) => String(item.generation ?? "") },
43130
+ { header: "NEXT OFFSET", getValue: (item) => String(item.nextOffset ?? "") },
43131
+ { header: "PAGES (RUN)", getValue: (item) => String(item.pagesDone ?? 0) },
43132
+ { header: "~FETCHED", getValue: (item) => String(item.totals?.fetched ?? 0) },
43133
+ { header: "~APPLIED", getValue: (item) => String(item.totals?.applied ?? 0) },
43134
+ { header: "~SKIPPED", getValue: (item) => String(item.totals?.skipped ?? 0) },
43135
+ { header: "~FAILED", getValue: (item) => String(item.totals?.failed ?? 0) },
43136
+ { header: "RUN ID", getValue: (item) => item.runId ?? "" }
43137
+ ];
43138
+ var RESUMABLE_PAIR_STATUSES = /* @__PURE__ */ new Set([
43139
+ "failed",
43140
+ "aborted",
43141
+ "truncated",
43142
+ "pending",
43143
+ "running",
43144
+ "waiting"
43145
+ ]);
43146
+ function onboardingStatusLines(status, connectionId) {
43147
+ const lines = [];
43148
+ const execution = status.execution;
43149
+ if (execution) {
43150
+ const failure = execution.failureCode ? ` (failure: ${execution.failureCode})` : "";
43151
+ lines.push(
43152
+ `Temporal execution: ${execution.workflowId} run ${execution.runId ?? "-"} \u2014 ${execution.status}${failure}`
43153
+ );
43154
+ } else {
43155
+ lines.push("Temporal execution: none recorded");
43156
+ }
43157
+ if (status.waitingUntil) {
43158
+ lines.push(
43159
+ `Waiting for the operator window (21:00\u201308:00 America/New_York) until ${status.waitingUntil}`
43160
+ );
43161
+ }
43162
+ if (status.preview) {
43163
+ const previewPairs = status.preview.pairs ?? [];
43164
+ const admitted = previewPairs.reduce((n, p) => n + (p.totals?.admitted ?? 0), 0);
43165
+ const notAdmitted = previewPairs.reduce(
43166
+ (n, p) => n + (p.totals?.notAdmitted ?? 0),
43167
+ 0
43168
+ );
43169
+ lines.push(
43170
+ `Latest preview: ${previewPairs.length} pair(s), ~${admitted} admission-eligible (incl. already-linked), ~${notAdmitted} not admitted (read-only)`
43171
+ );
43172
+ }
43173
+ lines.push("Counts are approximate.");
43174
+ const unfinished = (status.pairs ?? []).some(
43175
+ (p) => p.inCurrentCohort && RESUMABLE_PAIR_STATUSES.has(p.status) && p.runId
43176
+ );
43177
+ if (unfinished && execution?.status !== "running") {
43178
+ lines.push(
43179
+ `Unfinished pairs continue only on an explicit resume: gr fhir-connections onboarding-import start --id ${connectionId} --resume --allow-write`
43180
+ );
43181
+ }
43182
+ return lines;
43183
+ }
40395
43184
  var fhirConnectionsDomain = {
40396
43185
  name: "fhir-connections",
40397
43186
  description: "Manage FHIR connections",
@@ -40437,8 +43226,8 @@ var fhirConnectionsDomain = {
40437
43226
  ],
40438
43227
  examples: [
40439
43228
  "fhir-connections encounter-sync runs --id 12",
40440
- "fhir-connections encounter-sync runs --id 12 --output json",
40441
- "fhir-connections encounter-sync runs --id 12 --limit 5 --output json"
43229
+ "fhir-connections encounter-sync runs --id 12 --output-format json",
43230
+ "fhir-connections encounter-sync runs --id 12 --limit 5 --output-format json"
40442
43231
  ],
40443
43232
  handler: async ({ ctx, workspace, args }) => {
40444
43233
  const limit = args["limit"] ? Number(args["limit"]) : 20;
@@ -40449,6 +43238,77 @@ var fhirConnectionsDomain = {
40449
43238
  );
40450
43239
  outputData(runs, ctx, ENCOUNTER_RUN_COLUMNS);
40451
43240
  }
43241
+ },
43242
+ {
43243
+ // athenahealth onboarding import (PR-C): one explicit, audited
43244
+ // operator execution per connection, at most 50 pages per pair per
43245
+ // run. Thin over the SDK; the server decides everything.
43246
+ path: ["fhir-connections", "onboarding-import", "start"],
43247
+ description: "Start an athenahealth onboarding import (or --resume / --override / --dry-run preview)",
43248
+ requiresWorkspace: true,
43249
+ mutates: true,
43250
+ args: [
43251
+ { name: "id", description: "FHIR connection ID", required: true },
43252
+ {
43253
+ name: "dry-run",
43254
+ description: "Preview: read and classify admission only, write no Members",
43255
+ isFlag: true
43256
+ },
43257
+ {
43258
+ name: "resume",
43259
+ description: "Continue unfinished (failed, truncated, aborted) pairs at their stored frontier",
43260
+ isFlag: true
43261
+ },
43262
+ {
43263
+ name: "override",
43264
+ description: "Rescan completed pairs from offset 0 under a new generation",
43265
+ isFlag: true
43266
+ }
43267
+ ],
43268
+ examples: [
43269
+ "fhir-connections onboarding-import start --id 12 --dry-run --allow-write",
43270
+ "fhir-connections onboarding-import start --id 12 --allow-write",
43271
+ "fhir-connections onboarding-import start --id 12 --resume --allow-write"
43272
+ ],
43273
+ handler: async ({ ctx, workspace, args }) => {
43274
+ const connectionId = requireNumber(args, "id");
43275
+ const started = await requireAuth(ctx).apiClient.fhirStartOnboardingImport(
43276
+ workspace,
43277
+ connectionId,
43278
+ {
43279
+ dryRun: args["dry-run"] === true,
43280
+ resume: args["resume"] === true,
43281
+ override: args["override"] === true
43282
+ }
43283
+ );
43284
+ outputSingle(started, ctx, ONBOARDING_START_COLUMNS);
43285
+ hint(ctx, [
43286
+ `Started. Follow progress with: gr fhir-connections onboarding-import status --id ${connectionId}`
43287
+ ]);
43288
+ }
43289
+ },
43290
+ {
43291
+ path: ["fhir-connections", "onboarding-import", "status"],
43292
+ description: "Show athenahealth onboarding-import progress and its Temporal execution (read-only)",
43293
+ requiresWorkspace: true,
43294
+ args: [{ name: "id", description: "FHIR connection ID", required: true }],
43295
+ examples: [
43296
+ "fhir-connections onboarding-import status --id 12",
43297
+ "fhir-connections onboarding-import status --id 12 --output-format json"
43298
+ ],
43299
+ handler: async ({ ctx, workspace, args }) => {
43300
+ const connectionId = requireNumber(args, "id");
43301
+ const status = await requireAuth(ctx).apiClient.fhirGetOnboardingImportStatus(
43302
+ workspace,
43303
+ connectionId
43304
+ );
43305
+ if (ctx.jq || (ctx.outputFormat ?? "table") !== "table") {
43306
+ outputSingle(status, ctx);
43307
+ return;
43308
+ }
43309
+ outputData(status.pairs, ctx, ONBOARDING_PAIR_COLUMNS);
43310
+ hint(ctx, onboardingStatusLines(status, connectionId));
43311
+ }
40452
43312
  }
40453
43313
  ]
40454
43314
  };
@@ -40795,15 +43655,18 @@ var hubspotDomain = {
40795
43655
  mutates: true,
40796
43656
  requiresWorkspace: true,
40797
43657
  examples: [
40798
- "# HubSpot setup is a 4-step flow \u2014 this command is step 1:",
43658
+ "# When the response shows platformAppAvailable=true, the workspace connects through",
43659
+ "# the shared Gravity Rail HubSpot app: install, then authorize. That's all.",
43660
+ "gr hubspot install -w <ws> --allow-write",
43661
+ "gr hubspot authorize -w <ws> --allow-write # then open the returned authorizeUrl",
43662
+ "",
43663
+ "# To use your own HubSpot app instead (a Projects-platform app; HubSpot no longer",
43664
+ "# allows new private or developer apps):",
40799
43665
  '# 1. install -> creates the connection; the response includes the OAuth "callbackUrl"',
40800
- "# 2. in HubSpot: create a private/developer app whose Redirect URL is that callbackUrl,",
40801
- "# with CRM scopes (contacts/companies/deals read+write). Copy the Client ID + Secret.",
43666
+ "# 2. in HubSpot: give your app that callbackUrl as a Redirect URL, with CRM scopes",
43667
+ "# (contacts/companies/deals read+write). Copy the Client ID + Secret.",
40802
43668
  "# 3. configure -> save that Client ID / Secret",
40803
- '# 4. authorize -> returns an "authorizeUrl"; open it to grant access. status then',
40804
- "# reports configured=true and connected=true.",
40805
- "",
40806
- "gr hubspot install -w <ws> --allow-write",
43669
+ '# 4. authorize -> returns an "authorizeUrl"; open it to grant access.',
40807
43670
  "gr hubspot status -w <ws> # read back callbackUrl + configured/connected",
40808
43671
  `gr hubspot configure -w <ws> --allow-write -d '{"clientId":"...","clientSecret":"..."}'`,
40809
43672
  "gr hubspot authorize -w <ws> --allow-write # then open the returned authorizeUrl"
@@ -41828,6 +44691,7 @@ function registerPublicDomains(registry) {
41828
44691
  registry.register(calendarsDomain);
41829
44692
  registry.register(qualificationsDomain);
41830
44693
  registry.register(queriesDomain);
44694
+ registry.register(dataReportsDomain);
41831
44695
  registry.register(personasDomain);
41832
44696
  registry.register(metricsDomain);
41833
44697
  registry.register(journeysDomain);
@@ -46395,11 +49259,8 @@ var topLevelCommands = [
46395
49259
  // src/lib.ts
46396
49260
  init_concierge_api();
46397
49261
 
46398
- // package.json
46399
- var package_default = {
46400
- version: "0.53.0"};
46401
-
46402
49262
  // src/gr.ts
49263
+ init_package();
46403
49264
  var VERSION = package_default.version;
46404
49265
  function createRegistry() {
46405
49266
  const registry = new CommandRegistry();
@@ -46481,7 +49342,7 @@ main().catch(handleError);
46481
49342
  /*! Bundled license information:
46482
49343
 
46483
49344
  js-yaml/dist/js-yaml.mjs:
46484
- (*! js-yaml 5.4.2 https://github.com/nodeca/js-yaml @license MIT *)
49345
+ (*! js-yaml 5.4.3 https://github.com/nodeca/js-yaml @license MIT *)
46485
49346
  */
46486
49347
  //# sourceMappingURL=gr.js.map
46487
49348
  //# sourceMappingURL=gr.js.map