@jinshuju/cli 0.26.0 → 0.28.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.
@@ -1,3 +1,4 @@
1
+ import { HttpError } from '../errors.js';
1
2
  import { FILTER_OPTION, FILTERS_OPTION, UsageError, parseFilter, parseSort, resolveContainer } from '../options.js';
2
3
  import { call } from '../spec.js';
3
4
  import { isRecord } from '../values.js';
@@ -63,9 +64,105 @@ export function sortRules(input) {
63
64
  * — so the confirmation is a flag, and leaving it out is the safe outcome
64
65
  * rather than a question nobody is there to answer.
65
66
  */
66
- export function confirmed(input, what) {
67
+ export function confirmed(input, what, outcome = 'is permanent') {
67
68
  if (!input.options.yes)
68
- throw new UsageError(`${what} is permanent; pass --yes to go ahead`);
69
+ throw new UsageError(`${what} ${outcome}; pass --yes to go ahead`);
70
+ }
71
+ /**
72
+ * How many forms or tables one delete takes. A delete that has to be confirmed
73
+ * first, as Jiri's are, reads what each one would take with it before asking,
74
+ * and one confirmation covers at most this many: taking more would read ahead
75
+ * for batches nobody is asked about yet.
76
+ */
77
+ const TRASH_BATCH = 20;
78
+ /**
79
+ * How many of a batch's requests are in flight at once. Each form or table is a
80
+ * request of its own, and a batch of 20 sent one after another took seconds; a
81
+ * few at a time stays well inside what the API takes from one caller.
82
+ */
83
+ const TRASH_CONCURRENCY = 5;
84
+ /**
85
+ * Sends one request per token and answers every outcome, in the order given. The
86
+ * first goes alone, so a session that has to refresh its token does so once
87
+ * rather than from several requests at the same moment; the rest a few at a time.
88
+ */
89
+ async function eachToken(tokens, send) {
90
+ const settle = (token) => send(token).then((value) => ({ token, value }), (error) => ({ token, error: error }));
91
+ const outcomes = [await settle(tokens[0])];
92
+ let next = 1;
93
+ const worker = async () => {
94
+ while (next < tokens.length) {
95
+ const index = next++;
96
+ outcomes[index] = await settle(tokens[index]);
97
+ }
98
+ };
99
+ await Promise.all(Array.from({ length: Math.min(TRASH_CONCURRENCY, tokens.length - 1) }, worker));
100
+ return outcomes;
101
+ }
102
+ /**
103
+ * Moves each form or table named to the trash, one request apiece, a few at a
104
+ * time (`eachToken`). Every one is tried, so one refused does not leave the rest
105
+ * standing, and the error lists what went beside what did not: read as
106
+ * all-or-nothing, it would invite the moved ones to be deleted again or the
107
+ * refused ones to be taken for done. It exits the way the first failure would
108
+ * have, and under `--output json` its body carries every token's refusal, not
109
+ * the first one's alone.
110
+ */
111
+ export async function trash(client, input, kind) {
112
+ if (input.rest.length > TRASH_BATCH) {
113
+ throw new UsageError(`${kind} delete takes at most ${TRASH_BATCH} ${kind}s at a time, got ${input.rest.length}; ` +
114
+ 'delete the rest in another call once these are done');
115
+ }
116
+ if (input.options.preview) {
117
+ if (input.options.yes)
118
+ throw new UsageError('--preview and --yes are alternatives, not both');
119
+ return previewTrash(client, input, kind);
120
+ }
121
+ const many = input.rest.length > 1;
122
+ confirmed(input, `Deleting ${kind}${many ? 's' : ''} ${input.rest.join(', ')}`, `moves ${many ? 'them' : 'it'} to the trash`);
123
+ const outcomes = await eachToken(input.rest, (token) => client.request(kind === 'form'
124
+ ? call('deleteForm', { path: { form_token: token } })
125
+ : call('deleteTable', { path: { table_token: token } })));
126
+ const deleted = outcomes.flatMap((outcome) => ('value' in outcome ? [outcome.token] : []));
127
+ const failures = outcomes.flatMap((outcome) => ('error' in outcome ? [outcome] : []));
128
+ if (failures.length === 0)
129
+ return { deleted };
130
+ const lines = failures.map(({ token, error }) => {
131
+ const outcome = error instanceof HttpError ? 'not deleted' : 'may or may not be deleted';
132
+ return ` ${token} ${outcome}: ${error.message.replaceAll('\n', '\n ')}`;
133
+ });
134
+ const first = failures[0].error;
135
+ const body = {
136
+ deleted,
137
+ failures: failures.map(({ token, error }) => error instanceof HttpError ? { token, status: error.status, body: error.body } : { token, message: error.message })
138
+ };
139
+ throw new Error([`moved to the trash: ${deleted.join(', ') || 'none'}`, ...lines].join('\n'), {
140
+ cause: first instanceof HttpError ? new HttpError(first.message, first.status, body) : first
141
+ });
142
+ }
143
+ /**
144
+ * What deleting each form or table would take with it, nothing deleted, a few at
145
+ * a time (`eachToken`). A token that cannot be read is listed under `failures`
146
+ * beside the ones that could, so one wrong token does not hide the rest; only
147
+ * when none could be read does it fail, as its first failure would. Both keep
148
+ * the order given.
149
+ */
150
+ async function previewTrash(client, input, kind) {
151
+ const outcomes = await eachToken(input.rest, (token) => client.request(kind === 'form'
152
+ ? call('previewFormDeletion', { path: { form_token: token } })
153
+ : call('previewTableDeletion', { path: { table_token: token } })));
154
+ const previews = outcomes.flatMap((outcome) => ('value' in outcome ? [outcome.value] : []));
155
+ const failures = outcomes.flatMap((outcome) => ('error' in outcome ? [outcome] : []));
156
+ if (previews.length === 0)
157
+ throw failures[0].error;
158
+ if (failures.length === 0)
159
+ return { previews };
160
+ return {
161
+ previews,
162
+ failures: failures.map(({ token, error }) => error instanceof HttpError
163
+ ? { token, status: error.status, message: error.message }
164
+ : { token, message: error.message })
165
+ };
69
166
  }
70
167
  /**
71
168
  * Drops the keys an optional flag left undefined. JSON.stringify would drop
@@ -92,6 +189,12 @@ export function one(value) {
92
189
  return Array.isArray(value) ? value : [value];
93
190
  }
94
191
  export const YES_OPTION = { name: '--yes', type: 'boolean', description: 'Confirm the deletion' };
192
+ /** `form delete` and `table delete`'s look before they delete. */
193
+ export const PREVIEW_OPTION = {
194
+ name: '--preview',
195
+ type: 'boolean',
196
+ description: 'Show what deleting each would take with it, and delete nothing'
197
+ };
95
198
  export const FOLDER_OPTION = {
96
199
  name: '--folder',
97
200
  type: 'string',
@@ -1,6 +1,6 @@
1
1
  import { FILTER_OPTION, FILTERS_OPTION, JSON_OPTION, PAGINATION_OPTIONS, SORT_OPTION } from '../options.js';
2
2
  import { bodyChoices, call } from '../spec.js';
3
- import { FOLDER_OPTION, LISTING, filters, keywords, overriding, paging, payload, sort } from './shared.js';
3
+ import { FOLDER_OPTION, LISTING, PREVIEW_OPTION, YES_OPTION, filters, keywords, overriding, paging, payload, sort, trash } from './shared.js';
4
4
  import { validateContainerPayload } from '../payload.js';
5
5
  /**
6
6
  * The field types a table column may be, which is a third of what a form takes.
@@ -79,6 +79,18 @@ export const TABLE = [
79
79
  }),
80
80
  examples: ['jinshuju table move Vn4xR8 --folder Nf7mDC', 'jinshuju table move Vn4xR8']
81
81
  },
82
+ {
83
+ path: ['table', 'delete'],
84
+ summary: 'Move tables to the trash',
85
+ description: 'Each table goes to the trash with its entries, and can be restored from there in the web app ' +
86
+ 'within 2 years. Up to 20 at a time, each deleted on its own: one refused leaves the others ' +
87
+ 'deleted, and the error says which went and which did not. --preview reads what deleting each ' +
88
+ 'would take with it instead, and deletes nothing.',
89
+ args: [{ name: 'table', required: true, variadic: true, description: 'Table token' }],
90
+ options: [YES_OPTION, PREVIEW_OPTION],
91
+ run: (input, client) => trash(client, input, 'table'),
92
+ examples: ['jinshuju table delete Vn4xR8 Qm5tW2 --preview', 'jinshuju table delete Vn4xR8 Qm5tW2 --yes']
93
+ },
82
94
  {
83
95
  path: ['table', 'edit'],
84
96
  summary: 'Edit a table',
@@ -4,7 +4,7 @@ import { type OperationId } from '../spec.js';
4
4
  * What the CLI uploads a form image as. A test holds the list to the spec's
5
5
  * `image_type`, which is where it would otherwise drift.
6
6
  */
7
- export declare const FORM_IMAGE_TYPES: readonly ["description", "header", "wallpaper", "opensearch_header", "wheel_fortune_prize"];
7
+ export declare const FORM_IMAGE_TYPES: readonly ["description", "header", "wallpaper", "opensearch_header", "wheel_fortune_prize", "weixin_share_icon"];
8
8
  export type FormImageType = (typeof FORM_IMAGE_TYPES)[number];
9
9
  /**
10
10
  * A file on disk, as multipart. The three endpoints that take one authenticate
@@ -29,8 +29,8 @@ interface Upload {
29
29
  /** A file uploaded with a progress line while it goes, answered by its id. */
30
30
  export declare function uploadedId(client: HttpClient, { id, path, file, extra, key }: Upload): Promise<string>;
31
31
  /**
32
- * An image that a form's theme, one of its public queries or a prize of its lucky wheel
33
- * refers to by id, uploaded with `imageType` saying which.
32
+ * An image that a form's theme, one of its public queries, a prize of its lucky wheel
33
+ * or its WeChat share card refers to by id, uploaded with `imageType` saying which.
34
34
  */
35
35
  export declare function uploadFormImage(client: HttpClient, file: string, imageType: FormImageType): Promise<string>;
36
36
  export {};
@@ -30,7 +30,8 @@ export const FORM_IMAGE_TYPES = [
30
30
  'header',
31
31
  'wallpaper',
32
32
  'opensearch_header',
33
- 'wheel_fortune_prize'
33
+ 'wheel_fortune_prize',
34
+ 'weixin_share_icon'
34
35
  ];
35
36
  /**
36
37
  * A file on disk, as multipart. The three endpoints that take one authenticate
@@ -82,8 +83,8 @@ export async function uploadedId(client, { id, path = {}, file, extra, key }) {
82
83
  }
83
84
  }
84
85
  /**
85
- * An image that a form's theme, one of its public queries or a prize of its lucky wheel
86
- * refers to by id, uploaded with `imageType` saying which.
86
+ * An image that a form's theme, one of its public queries, a prize of its lucky wheel
87
+ * or its WeChat share card refers to by id, uploaded with `imageType` saying which.
87
88
  */
88
89
  export function uploadFormImage(client, file, imageType) {
89
90
  return uploadedId(client, { id: 'uploadFormImage', file, extra: { image_type: imageType }, key: 'attachment_id' });
@@ -3,7 +3,7 @@ import type { Operation, Schema } from '../spec.js';
3
3
  export declare const BASE_PATH = "/api/v1";
4
4
  /** The day spec/openapi.yaml was fetched from the API, when scripts/fetch-spec.mjs recorded it. */
5
5
  export declare const SPEC_DATE: string | undefined;
6
- export type OperationId = 'aggregateEntries' | 'aggregateFormViewEntries' | 'aggregateTableEntries' | 'aggregateTableViewEntries' | 'aggregateTradeTransactions' | 'checkFormFieldData' | 'checkTableFieldData' | 'copyForm' | 'countEntries' | 'countEntriesAcrossForms' | 'countFormViewEntries' | 'countTableEntries' | 'countTableViewEntries' | 'createCheckinCampaign' | 'createEmailTask' | 'createEntriesBatch' | 'createEntry' | 'createEntryComment' | 'createEntryImport' | 'createEntryLegacy' | 'createFillFormEntry' | 'createFillViewEntry' | 'createFolder' | 'createForm' | 'createFormView' | 'createFormWebhook' | 'createMemoryNote' | 'createMessageChannel' | 'createNotificationRule' | 'createOpensearchQuery' | 'createRoutine' | 'createSmsSignature' | 'createSmsTask' | 'createSmsTemplate' | 'createTable' | 'createTableEntry' | 'createTableEntryComment' | 'createTableView' | 'createTemplateUsage' | 'createWeixinOauthSession' | 'deleteCheckinCampaign' | 'deleteEntry' | 'deleteEntryComment' | 'deleteForm' | 'deleteFormView' | 'deleteFormWebhook' | 'deleteMemoryNotes' | 'deleteMessageChannel' | 'deleteNotificationRule' | 'deleteRoutine' | 'deleteSmsSignature' | 'deleteSmsTemplate' | 'deleteTable' | 'deleteTableEntry' | 'deleteTableEntryComment' | 'deleteTableView' | 'estimateEmailTask' | 'estimateEmailTaskResend' | 'estimateMessage' | 'estimateSmsTask' | 'estimateSmsTaskChange' | 'estimateSmsTaskResend' | 'exportRemainingVouchers' | 'getBillingAccount' | 'getCheckinCampaign' | 'getCurrentUser' | 'getEmailTask' | 'getEntry' | 'getEntryImport' | 'getEntryStateFlow' | 'getEntryStats' | 'getEvaluationSetting' | 'getExamSetting' | 'getFieldType' | 'getFillFormPage' | 'getFillViewPage' | 'getFolder' | 'getForm' | 'getFormSetting' | 'getFormView' | 'getManuallyCloseRule' | 'getMemory' | 'getMessage' | 'getMessageChannel' | 'getNotificationRule' | 'getOpensearchQuery' | 'getPublishedArtifact' | 'getQuickpaySetting' | 'getRoutine' | 'getSmsTask' | 'getTable' | 'getTableEntry' | 'getTableView' | 'getTradeMerchant' | 'getWheelFortune' | 'listArtifacts' | 'listBillingAccountInvoices' | 'listBillingAccountPaidFeatures' | 'listBillingAccountPaymentHistories' | 'listBillingAccountUsers' | 'listCheckinCampaigns' | 'listContacts' | 'listEmailTaskActivities' | 'listEmailTasks' | 'listEntries' | 'listEntryComments' | 'listExtendedAttributes' | 'listFieldRules' | 'listFieldTypes' | 'listFolders' | 'listFormConditionTriggerableFields' | 'listFormCooperators' | 'listFormViewEntries' | 'listFormViews' | 'listForms' | 'listMessageChannels' | 'listMessages' | 'listMyFilledForms' | 'listMySubmittedEntries' | 'listNotificationRuleNotifications' | 'listNotificationRules' | 'listOpensearchQueries' | 'listOpensearchQuerySuggestions' | 'listRoutineRuns' | 'listRoutines' | 'listSmsAuditStatuses' | 'listSmsSignatures' | 'listSmsTaskActivities' | 'listSmsTasks' | 'listSmsTemplates' | 'listSmtpAccounts' | 'listTableConditionTriggerableFields' | 'listTableEntries' | 'listTableEntryComments' | 'listTableViewEntries' | 'listTableViews' | 'listTables' | 'listTradePayouts' | 'listTradeRefunds' | 'listTradeTransactions' | 'moveFormToFolder' | 'moveTableToFolder' | 'patchEntriesBatch' | 'pauseRoutine' | 'prepareEntryAttachmentUpload' | 'prepareFormImageUpload' | 'prepareGoodsDeliverableAttachmentUpload' | 'prepareImportFileUpload' | 'previewFormFieldTypeChange' | 'previewTableFieldTypeChange' | 'replaceEntry' | 'replaceTableEntry' | 'resendEmailTask' | 'resendSmsTask' | 'resumeRoutine' | 'runRoutine' | 'searchEntriesAcrossForms' | 'searchMySubmittedEntries' | 'sendMessage' | 'sendSmsTask' | 'summarizeEntries' | 'summarizeFormViewEntries' | 'summarizeTableEntries' | 'summarizeTableViewEntries' | 'updateAccessPolicy' | 'updateCheckinCampaign' | 'updateEntry' | 'updateEntryComment' | 'updateEntryStateFlow' | 'updateEntryViaPost' | 'updateEvaluationSetting' | 'updateExamSetting' | 'updateForm' | 'updateFormSetting' | 'updateFormTheme' | 'updateFormView' | 'updateManuallyCloseRule' | 'updateMemoryNote' | 'updateNotificationRule' | 'updateOpensearchQuery' | 'updatePublishedArtifact' | 'updateQuickpaySetting' | 'updateRoutine' | 'updateSmsSignature' | 'updateSmsTask' | 'updateSmsTemplate' | 'updateTable' | 'updateTableEntry' | 'updateTableEntryComment' | 'updateTableEntryViaPost' | 'updateTableView' | 'updateWheelFortune' | 'uploadEntryAttachment' | 'uploadFormImage' | 'uploadGoodsDeliverableAttachment' | 'uploadImportFile' | 'uploadUserLicenseAttachment' | 'verifyRedirectParams';
6
+ export type OperationId = 'aggregateEntries' | 'aggregateFormViewEntries' | 'aggregateTableEntries' | 'aggregateTableViewEntries' | 'aggregateTradeTransactions' | 'checkFormFieldData' | 'checkTableFieldData' | 'copyForm' | 'countEntries' | 'countEntriesAcrossForms' | 'countFormViewEntries' | 'countTableEntries' | 'countTableViewEntries' | 'createCheckinCampaign' | 'createEmailTask' | 'createEntriesBatch' | 'createEntry' | 'createEntryComment' | 'createEntryImport' | 'createEntryLegacy' | 'createFillFormEntry' | 'createFillViewEntry' | 'createFolder' | 'createForm' | 'createFormCooperators' | 'createFormView' | 'createFormWebhook' | 'createMemoryNote' | 'createMessageChannel' | 'createNotificationRule' | 'createOpenResult' | 'createOpensearchQuery' | 'createRoutine' | 'createSmsSignature' | 'createSmsTask' | 'createSmsTemplate' | 'createTable' | 'createTableEntry' | 'createTableEntryComment' | 'createTableView' | 'createTemplateUsage' | 'createWeixinOauthSession' | 'deleteCheckinCampaign' | 'deleteEntry' | 'deleteEntryComment' | 'deleteForm' | 'deleteFormView' | 'deleteFormWebhook' | 'deleteMemoryNotes' | 'deleteMessageChannel' | 'deleteNotificationRule' | 'deleteOpenResult' | 'deleteRoutine' | 'deleteSmsSignature' | 'deleteSmsTemplate' | 'deleteTable' | 'deleteTableEntry' | 'deleteTableEntryComment' | 'deleteTableView' | 'estimateEmailTask' | 'estimateEmailTaskResend' | 'estimateMessage' | 'estimateSmsTask' | 'estimateSmsTaskChange' | 'estimateSmsTaskResend' | 'exportRemainingVouchers' | 'getBillingAccount' | 'getCheckinCampaign' | 'getCurrentUser' | 'getEmailTask' | 'getEntry' | 'getEntryImport' | 'getEntryStateFlow' | 'getEntryStats' | 'getEvaluationSetting' | 'getExamSetting' | 'getFieldType' | 'getFillFormPage' | 'getFillViewPage' | 'getFolder' | 'getForm' | 'getFormSetting' | 'getFormView' | 'getManuallyCloseRule' | 'getMemory' | 'getMessage' | 'getMessageChannel' | 'getNotificationRule' | 'getOpenResult' | 'getOpensearchQuery' | 'getPublishedArtifact' | 'getQuickpaySetting' | 'getRoutine' | 'getSmsTask' | 'getTable' | 'getTableEntry' | 'getTableView' | 'getTradeMerchant' | 'getUserFormSetting' | 'getWheelFortune' | 'listArtifactDataSources' | 'listArtifacts' | 'listBillingAccountInvoices' | 'listBillingAccountPaidFeatures' | 'listBillingAccountPaymentHistories' | 'listBillingAccountUsers' | 'listCheckinCampaigns' | 'listContacts' | 'listEmailTaskActivities' | 'listEmailTasks' | 'listEntries' | 'listEntryComments' | 'listExtendedAttributes' | 'listFieldRules' | 'listFieldTypes' | 'listFolders' | 'listFormConditionTriggerableFields' | 'listFormCooperators' | 'listFormPublishedArtifacts' | 'listFormViewEntries' | 'listFormViews' | 'listForms' | 'listMessageChannels' | 'listMessages' | 'listMyFilledForms' | 'listMySubmittedEntries' | 'listNotificationRuleNotifications' | 'listNotificationRules' | 'listOpenResults' | 'listOpensearchQueries' | 'listOpensearchQuerySuggestions' | 'listRedirectRules' | 'listRoutineRuns' | 'listRoutines' | 'listSmsAuditStatuses' | 'listSmsSignatures' | 'listSmsTaskActivities' | 'listSmsTasks' | 'listSmsTemplates' | 'listSmtpAccounts' | 'listTableConditionTriggerableFields' | 'listTableEntries' | 'listTableEntryComments' | 'listTablePublishedArtifacts' | 'listTableViewEntries' | 'listTableViews' | 'listTables' | 'listTradePayouts' | 'listTradeRefunds' | 'listTradeTransactions' | 'moveFormToFolder' | 'moveTableToFolder' | 'patchEntriesBatch' | 'pauseRoutine' | 'prepareEntryAttachmentUpload' | 'prepareFormImageUpload' | 'prepareGoodsDeliverableAttachmentUpload' | 'prepareImportFileUpload' | 'previewFormDeletion' | 'previewFormFieldTypeChange' | 'previewTableDeletion' | 'previewTableFieldTypeChange' | 'replaceEntry' | 'replaceTableEntry' | 'resendEmailTask' | 'resendSmsTask' | 'restoreFormPublishedArtifactDataGrant' | 'restoreTablePublishedArtifactDataGrant' | 'resumeRoutine' | 'revokeFormPublishedArtifactDataGrant' | 'revokeTablePublishedArtifactDataGrant' | 'runRoutine' | 'searchEntriesAcrossForms' | 'searchMySubmittedEntries' | 'sendMessage' | 'sendSmsTask' | 'summarizeEntries' | 'summarizeFormViewEntries' | 'summarizeTableEntries' | 'summarizeTableViewEntries' | 'updateAccessPolicy' | 'updateCheckinCampaign' | 'updateEntry' | 'updateEntryComment' | 'updateEntryStateFlow' | 'updateEntryViaPost' | 'updateEvaluationSetting' | 'updateExamSetting' | 'updateForm' | 'updateFormSetting' | 'updateFormTheme' | 'updateFormView' | 'updateManuallyCloseRule' | 'updateMemoryNote' | 'updateNotificationRule' | 'updateOpenResult' | 'updateOpensearchQuery' | 'updatePublishedArtifact' | 'updateQuickpaySetting' | 'updateRoutine' | 'updateSmsSignature' | 'updateSmsTask' | 'updateSmsTemplate' | 'updateTable' | 'updateTableEntry' | 'updateTableEntryComment' | 'updateTableEntryViaPost' | 'updateTableView' | 'updateUserFormSetting' | 'updateWheelFortune' | 'uploadEntryAttachment' | 'uploadFormImage' | 'uploadGoodsDeliverableAttachment' | 'uploadImportFile' | 'uploadUserLicenseAttachment' | 'verifyRedirectParams';
7
7
  export declare const OPERATIONS: {
8
8
  readonly [id in OperationId]: Operation;
9
9
  };