@yoonion/mimi-seed-mcp 0.21.7 → 0.22.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/README.md CHANGED
@@ -128,7 +128,7 @@ export ANTHROPIC_API_KEY=sk-ant-...
128
128
  ---
129
129
 
130
130
  <!-- generated:readme-tools-heading:start — edit scripts/docs-spec.mjs, then npm run plugin:sync -->
131
- ## 제공 도구 (150+ 개 · 23개 영역)
131
+ ## 제공 도구 (150+ 개 · 24개 영역)
132
132
  <!-- generated:readme-tools-heading:end -->
133
133
 
134
134
  <!-- generated:readme-tools-table:start — edit scripts/docs-spec.mjs, then npm run plugin:sync -->
@@ -147,6 +147,7 @@ export ANTHROPIC_API_KEY=sk-ant-...
147
147
  | Facebook | 6 | `facebook_post_photo` / `facebook_post_multi_photo` / `facebook_list_pages` |
148
148
  | Google Cloud IAM | 5 | `iam_create_service_account` / `iam_create_key` / `iam_add_iam_policy_binding` |
149
149
  | BigQuery | 5 | `bigquery_run_query` / `bigquery_list_datasets` / `bigquery_get_table_schema` |
150
+ | Google Drive | 8 | `drive_upload_file` / `drive_update_file_content` / `drive_create_folder` / `drive_list_files` |
150
151
  | GCP Billing | 4 | `gcp_get_billing_info` / `gcp_list_billing_projects` / `gcp_list_budgets` / `gcp_create_budget` |
151
152
  | Threads | 7 | `threads_post` / `threads_post_video` / `threads_post_carousel` / `threads_refresh_token` |
152
153
  | TikTok Business | 7 | `tiktok_business_plan_video_post` / `tiktok_business_publish_video` / `tiktok_business_get_publish_status` |
@@ -73,6 +73,7 @@ row for the job; batching two rows in one `select:` call is fine.
73
73
  | Remote Config usage + experiments | `select:firebase_get_remote_config_overview,gcp_get_billing_info` |
74
74
  | Analytics wiring (Firebase ↔ GA4 ↔ BigQuery) | `select:firebase_link_analytics,firebase_get_analytics_details,ga4_list_account_summaries,ga4_list_properties,ga4_create_property,ga4_list_data_streams,ga4_create_data_stream,ga4_plan_bigquery_link,ga4_create_bigquery_link,ga4_run_report` |
75
75
  | BigQuery | `select:bigquery_auth_status,bigquery_list_datasets,bigquery_list_tables,bigquery_get_table_schema,bigquery_run_query` |
76
+ | Google Drive (영상·산출물 업로드·교체·정리) | `select:drive_auth_status,drive_list_files,drive_create_folder,drive_upload_file,drive_update_file_content,drive_get_file,drive_update_file_metadata,drive_trash_file` |
76
77
  | GCP billing (Blaze 여부 · 비용 범위 · 예산) | `select:gcp_get_billing_info,gcp_list_billing_projects,gcp_list_budgets,gcp_create_budget` |
77
78
  | Real revenue (스토어 정산 원장 — sandbox·테스터가 섞이지 않는 유일한 창구) | `select:appstore_get_sales_report,appstore_get_finance_report,playstore_list_financial_reports,playstore_get_financial_report` |
78
79
  | App Store weekly growth insight | `select:appstore_get_weekly_insight,appstore_get_sales_report` |
@@ -0,0 +1,26 @@
1
+ import type { JWT } from 'google-auth-library';
2
+ import type { ServiceAccountKey } from './bigquery-auth.js';
3
+ export declare const DRIVE_SA_PATH: string;
4
+ export declare const DRIVE_SA_ENV = "MIMI_SEED_DRIVE_SA_JSON";
5
+ /** 서비스 계정은 공유받은 범위 안에서만 보이므로 전체 drive 스코프를 쓴다. */
6
+ export declare const DRIVE_SA_SCOPES: string[];
7
+ export type DriveAuthSource = 'service-account-env' | 'service-account' | 'user-oauth';
8
+ /** JSON 문자열 → 서비스 계정 키. 형식이 아니면 throw (메시지에 키 본문을 싣지 않는다). */
9
+ export declare function parseDriveServiceAccountJson(json: string): ServiceAccountKey;
10
+ /** 검증 후 ~/.mimi-seed/drive-service-account.json 에 0600 원자적 저장. */
11
+ export declare function saveDriveServiceAccountJson(json: string): ServiceAccountKey;
12
+ /** 저장된 Drive 서비스 계정 키 삭제. 없으면 false. */
13
+ export declare function deleteDriveServiceAccountJson(): boolean;
14
+ export interface DriveServiceAccount {
15
+ key: ServiceAccountKey;
16
+ source: Exclude<DriveAuthSource, 'user-oauth'>;
17
+ }
18
+ /**
19
+ * 설정된 Drive 서비스 계정. 환경 변수가 있으면 그것이 이긴다.
20
+ * 환경 변수가 있는데 형식이 틀리면 조용히 파일로 넘어가지 않고 throw — 잘못된 키를 쓰는 줄
21
+ * 모른 채 다른 계정으로 올라가는 일을 막는다.
22
+ */
23
+ export declare function getDriveServiceAccount(env?: NodeJS.ProcessEnv): DriveServiceAccount | null;
24
+ /** 서비스 계정 키 → Drive 스코프 JWT 클라이언트. */
25
+ export declare function driveJwt(key: ServiceAccountKey): JWT;
26
+ export declare const DRIVE_AUTH_HINT: string;
@@ -0,0 +1,91 @@
1
+ import { newJWT } from '../lib/google-auth-lite.js';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { writeCredentialFile } from '#core/atomic-write.js';
6
+ /**
7
+ * Google Drive 인증 — 서비스 계정 우선, 없으면 사용자 OAuth(drive.file).
8
+ *
9
+ * 왜 서비스 계정이 우선인가:
10
+ * - OAuth 경로는 비민감 스코프 drive.file 만 쓴다. 이 앱이 만든 파일만 다룰 수 있어서
11
+ * 사용자가 이미 가진 폴더(예: 팀 공유 폴더)에는 올릴 수 없다.
12
+ * - 서비스 계정은 공유받은 폴더·공유 드라이브 안에서 전체 Drive 스코프로 동작하고,
13
+ * 브라우저 로그인이 없어 CI·클라우드 컨테이너에서도 쓸 수 있다.
14
+ *
15
+ * 키 위치(우선순위):
16
+ * 1. 환경 변수 MIMI_SEED_DRIVE_SA_JSON — 키 JSON 본문. 파일을 둘 수 없는 CI·클라우드용.
17
+ * 2. ~/.mimi-seed/drive-service-account.json — mimi-seed-drive-auth 가 검증 후 저장.
18
+ *
19
+ * 키 본문은 절대 로그·도구 출력·에러 메시지에 싣지 않는다.
20
+ */
21
+ const CONFIG_DIR = path.join(os.homedir(), '.mimi-seed');
22
+ export const DRIVE_SA_PATH = path.join(CONFIG_DIR, 'drive-service-account.json');
23
+ export const DRIVE_SA_ENV = 'MIMI_SEED_DRIVE_SA_JSON';
24
+ /** 서비스 계정은 공유받은 범위 안에서만 보이므로 전체 drive 스코프를 쓴다. */
25
+ export const DRIVE_SA_SCOPES = ['https://www.googleapis.com/auth/drive'];
26
+ /** JSON 문자열 → 서비스 계정 키. 형식이 아니면 throw (메시지에 키 본문을 싣지 않는다). */
27
+ export function parseDriveServiceAccountJson(json) {
28
+ let parsed;
29
+ try {
30
+ parsed = JSON.parse(json);
31
+ }
32
+ catch {
33
+ throw new Error('JSON 파싱 실패 — 올바른 서비스 계정 키 파일이 아닙니다.');
34
+ }
35
+ if (parsed.type !== 'service_account' || !parsed.client_email || !parsed.private_key) {
36
+ throw new Error('서비스 계정 키 형식이 아닙니다 (type="service_account", client_email, private_key 필요).');
37
+ }
38
+ return parsed;
39
+ }
40
+ /** 검증 후 ~/.mimi-seed/drive-service-account.json 에 0600 원자적 저장. */
41
+ export function saveDriveServiceAccountJson(json) {
42
+ const parsed = parseDriveServiceAccountJson(json);
43
+ writeCredentialFile(DRIVE_SA_PATH, json);
44
+ return parsed;
45
+ }
46
+ /** 저장된 Drive 서비스 계정 키 삭제. 없으면 false. */
47
+ export function deleteDriveServiceAccountJson() {
48
+ if (!fs.existsSync(DRIVE_SA_PATH))
49
+ return false;
50
+ fs.unlinkSync(DRIVE_SA_PATH);
51
+ return true;
52
+ }
53
+ /**
54
+ * 설정된 Drive 서비스 계정. 환경 변수가 있으면 그것이 이긴다.
55
+ * 환경 변수가 있는데 형식이 틀리면 조용히 파일로 넘어가지 않고 throw — 잘못된 키를 쓰는 줄
56
+ * 모른 채 다른 계정으로 올라가는 일을 막는다.
57
+ */
58
+ export function getDriveServiceAccount(env = process.env) {
59
+ const fromEnv = env[DRIVE_SA_ENV];
60
+ if (fromEnv && fromEnv.trim()) {
61
+ try {
62
+ return { key: parseDriveServiceAccountJson(fromEnv), source: 'service-account-env' };
63
+ }
64
+ catch (e) {
65
+ throw new Error(`${DRIVE_SA_ENV}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
66
+ }
67
+ }
68
+ if (!fs.existsSync(DRIVE_SA_PATH))
69
+ return null;
70
+ try {
71
+ return { key: parseDriveServiceAccountJson(fs.readFileSync(DRIVE_SA_PATH, 'utf-8')), source: 'service-account' };
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ }
77
+ /** 서비스 계정 키 → Drive 스코프 JWT 클라이언트. */
78
+ export function driveJwt(key) {
79
+ return newJWT({ email: key.client_email, key: key.private_key, scopes: DRIVE_SA_SCOPES });
80
+ }
81
+ export const DRIVE_AUTH_HINT = [
82
+ '❌ Google Drive 인증이 설정되지 않았어.',
83
+ '',
84
+ '방법 1 — Drive 서비스 계정 (권장: 기존 폴더·공유 드라이브, CI·클라우드):',
85
+ ' npx -y @yoonion/mimi-seed-mcp mimi-seed-drive-auth',
86
+ ` (파일을 둘 수 없는 환경이면 키 JSON 본문을 환경 변수 ${DRIVE_SA_ENV} 에 넣는다)`,
87
+ ' 그 다음 대상 폴더(또는 공유 드라이브)를 서비스 계정 이메일과 공유해.',
88
+ '',
89
+ '방법 2 — Google 계정 OAuth (mimi-seed 가 만든 파일·폴더만 다룸):',
90
+ ' npx -y @yoonion/mimi-seed-mcp mimi-seed-auth --domains drive',
91
+ ].join('\n');
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ import readline from 'node:readline';
3
+ import fs from 'node:fs';
4
+ import { DRIVE_SA_ENV, DRIVE_SA_PATH, driveJwt, getDriveServiceAccount, saveDriveServiceAccountJson, } from './drive-auth.js';
5
+ import * as drive from '../drive/tools.js';
6
+ import { resolveLang } from '#core/lang.js';
7
+ // ko 가 원본이고 en 은 `typeof ko` 를 만족해야 한다 — 키를 빠뜨리면 컴파일이 깨진다.
8
+ const ko = {
9
+ title: ' 🤖 Mimi Seed — Google Drive 서비스 계정 연결',
10
+ why1: ' 서비스 계정은 공유받은 기존 폴더와 공유 드라이브에 파일을 올리고 관리할 수 있어.',
11
+ why2: ' (Google 로그인 OAuth 의 drive.file 권한은 mimi-seed 가 만든 파일·폴더만 다룬다)',
12
+ envWins: (env) => ` ℹ️ 환경 변수 ${env} 이 설정돼 있어 — 저장한 파일보다 환경 변수가 우선한다.`,
13
+ already: (email) => ` ✅ 이미 연결됨 (${email})`,
14
+ reconnect: ' 다시 설정할래? (y/N): ',
15
+ needTitle: ' Drive API 를 쓸 수 있는 서비스 계정 키 JSON 이 필요해:',
16
+ step1: ' 1. GCP Console → APIs & Services → Google Drive API 사용 설정',
17
+ step2: ' 2. IAM & Admin → Service Accounts → 서비스 계정 선택(또는 생성) → Keys → Add Key → JSON',
18
+ step3: ' 3. 올릴 대상 폴더(또는 공유 드라이브)를 서비스 계정 이메일과 "편집자"로 공유',
19
+ step3b: ' 서비스 계정에는 자기 저장 용량이 없으니, 공유 드라이브나 공유받은 폴더에 올린다.',
20
+ step4: ' 4. 다운로드한 JSON 파일 경로를 입력해',
21
+ askPath: ' 서비스 계정 JSON 파일 경로: ',
22
+ noFile: (p) => ` ❌ 파일 없음: ${p}`,
23
+ saved: (email, file) => ` ✅ 저장 완료! (${email})\n ${file}`,
24
+ askFolder: ' 접근을 확인할 Drive 폴더 ID (엔터 시 건너뜀): ',
25
+ probing: (id) => ` 🔎 폴더 ${id} 확인 중...`,
26
+ probeOk: (name, n) => ` ✅ 접근 OK — "${name}" (항목 ${n}개 표시)`,
27
+ probeFail: (msg) => ` ⚠️ 접근 실패: ${msg}`,
28
+ nextTitle: ' 이제 Claude Code 또는 Codex에서:',
29
+ nextExample: ' "이 영상을 Drive 의 영상 폴더에 올려줘"',
30
+ usage: ' 사용법: mimi-seed-drive-auth [--file <서비스계정.json>] [--folder <폴더ID>]',
31
+ };
32
+ const en = {
33
+ title: ' 🤖 Mimi Seed — Connect a Google Drive service account',
34
+ why1: ' A service account can upload to and manage existing folders and shared drives shared with it.',
35
+ why2: ' (The Google sign-in OAuth drive.file grant only covers files and folders mimi-seed created)',
36
+ envWins: (env) => ` ℹ️ ${env} is set — the environment variable wins over the saved file.`,
37
+ already: (email) => ` ✅ Already connected (${email})`,
38
+ reconnect: ' Set it up again? (y/N): ',
39
+ needTitle: ' A service-account key JSON with Drive API access is required:',
40
+ step1: ' 1. GCP Console → APIs & Services → enable the Google Drive API',
41
+ step2: ' 2. IAM & Admin → Service Accounts → pick (or create) one → Keys → Add Key → JSON',
42
+ step3: ' 3. Share the target folder (or shared drive) with the service-account email as Editor',
43
+ step3b: ' Service accounts have no storage quota of their own — upload into a shared drive or a shared folder.',
44
+ step4: ' 4. Enter the path to the downloaded JSON file',
45
+ askPath: ' Path to the service-account JSON file: ',
46
+ noFile: (p) => ` ❌ File not found: ${p}`,
47
+ saved: (email, file) => ` ✅ Saved! (${email})\n ${file}`,
48
+ askFolder: ' Drive folder ID to check access (Enter to skip): ',
49
+ probing: (id) => ` 🔎 Checking folder ${id}...`,
50
+ probeOk: (name, n) => ` ✅ Access OK — "${name}" (${n} item(s) listed)`,
51
+ probeFail: (msg) => ` ⚠️ Access failed: ${msg}`,
52
+ nextTitle: ' Now, in Claude Code or Codex:',
53
+ nextExample: ' "Upload this video to the videos folder on Drive"',
54
+ usage: ' Usage: mimi-seed-drive-auth [--file <service-account.json>] [--folder <folderId>]',
55
+ };
56
+ const M = resolveLang() === 'en' ? en : ko;
57
+ function flag(args, name) {
58
+ const eq = args.find((a) => a.startsWith(`--${name}=`));
59
+ if (eq)
60
+ return eq.slice(name.length + 3);
61
+ const i = args.indexOf(`--${name}`);
62
+ return i >= 0 ? args[i + 1] : undefined;
63
+ }
64
+ async function probe(folderId) {
65
+ const sa = getDriveServiceAccount();
66
+ if (!sa)
67
+ return;
68
+ console.log(M.probing(folderId));
69
+ const client = driveJwt(sa.key);
70
+ try {
71
+ const folder = await drive.getFile(client, folderId);
72
+ const { files } = await drive.listFiles(client, { folderId, pageSize: 10 });
73
+ console.log(M.probeOk(folder.name, files.length));
74
+ }
75
+ catch (e) {
76
+ console.log(M.probeFail(drive.driveError(e, sa.source, sa.key.client_email).message));
77
+ }
78
+ }
79
+ async function main() {
80
+ const args = process.argv.slice(2);
81
+ if (args.includes('--help') || args.includes('-h')) {
82
+ console.log(M.usage);
83
+ return;
84
+ }
85
+ const fileArg = flag(args, 'file');
86
+ const folderArg = flag(args, 'folder');
87
+ console.log('');
88
+ console.log(M.title);
89
+ console.log('');
90
+ console.log(M.why1);
91
+ console.log(M.why2);
92
+ console.log('');
93
+ if (process.env[DRIVE_SA_ENV]?.trim())
94
+ console.log(M.envWins(DRIVE_SA_ENV));
95
+ // 비대화형: --file 로 바로 저장 (CI·스크립트).
96
+ if (fileArg) {
97
+ if (!fs.existsSync(fileArg)) {
98
+ console.log(M.noFile(fileArg));
99
+ process.exit(1);
100
+ }
101
+ const parsed = saveDriveServiceAccountJson(fs.readFileSync(fileArg, 'utf-8'));
102
+ console.log(M.saved(parsed.client_email, DRIVE_SA_PATH));
103
+ if (folderArg)
104
+ await probe(folderArg);
105
+ return;
106
+ }
107
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
108
+ const ask = (q) => new Promise((r) => rl.question(q, r));
109
+ try {
110
+ let existing = null;
111
+ try {
112
+ existing = getDriveServiceAccount();
113
+ }
114
+ catch {
115
+ existing = null;
116
+ }
117
+ if (existing) {
118
+ console.log(M.already(existing.key.client_email));
119
+ if ((await ask(M.reconnect)).toLowerCase() !== 'y') {
120
+ if (folderArg)
121
+ await probe(folderArg);
122
+ return;
123
+ }
124
+ }
125
+ console.log(M.needTitle);
126
+ console.log(M.step1);
127
+ console.log(M.step2);
128
+ console.log(M.step3);
129
+ console.log(M.step3b);
130
+ console.log(M.step4);
131
+ console.log('');
132
+ const jsonPath = (await ask(M.askPath)).trim().replace(/^["']|["']$/g, '');
133
+ if (!fs.existsSync(jsonPath)) {
134
+ console.log(M.noFile(jsonPath));
135
+ process.exitCode = 1;
136
+ return;
137
+ }
138
+ const parsed = saveDriveServiceAccountJson(fs.readFileSync(jsonPath, 'utf-8'));
139
+ console.log('');
140
+ console.log(M.saved(parsed.client_email, DRIVE_SA_PATH));
141
+ console.log('');
142
+ const folderId = folderArg ?? (await ask(M.askFolder)).trim();
143
+ if (folderId)
144
+ await probe(folderId);
145
+ console.log('');
146
+ console.log(M.nextTitle);
147
+ console.log(M.nextExample);
148
+ console.log('');
149
+ }
150
+ finally {
151
+ rl.close();
152
+ }
153
+ }
154
+ main().catch((e) => {
155
+ console.error(`\n ❌ ${e instanceof Error ? e.message : String(e)}\n`);
156
+ process.exit(1);
157
+ });
@@ -69,11 +69,18 @@ export declare const AUTH_DOMAINS: {
69
69
  readonly scopes: readonly ["https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly"];
70
70
  readonly summary: "youtube_get_channel·youtube_list_videos·youtube_get_analytics_report — 채널·영상·성과 읽기";
71
71
  };
72
+ readonly drive: {
73
+ readonly label: "Google Drive (drive.file)";
74
+ readonly scopes: readonly ["https://www.googleapis.com/auth/drive.file"];
75
+ readonly summary: "drive_* — mimi-seed 가 만든 파일·폴더 업로드·갱신·정리 (기존 폴더·공유 드라이브는 Drive 서비스 계정)";
76
+ };
72
77
  };
73
78
  export type AuthDomainId = keyof typeof AUTH_DOMAINS;
74
79
  /** z.enum 등 튜플이 필요한 자리에 쓰는 도메인 id 목록 (선언 순서 유지). */
75
80
  export declare const DOMAIN_IDS: [AuthDomainId, ...AuthDomainId[]];
76
81
  export declare const CLOUD_PLATFORM_SCOPE: "https://www.googleapis.com/auth/cloud-platform";
82
+ /** Drive OAuth 경로가 pre-flight 하는 스코프. 도메인 정의에서 파생한다(리터럴 중복 금지). */
83
+ export declare const DRIVE_FILE_SCOPE: "https://www.googleapis.com/auth/drive.file";
77
84
  /**
78
85
  * Play Developer Reporting API(Android vitals 통계) 전용 스코프. androidpublisher 와
79
86
  * 별개다 — SA JWT 와 OAuth playstore 도메인 양쪽에 함께 실어야 통계 도구가 동작한다.
@@ -80,10 +80,20 @@ export const AUTH_DOMAINS = {
80
80
  ],
81
81
  summary: 'youtube_get_channel·youtube_list_videos·youtube_get_analytics_report — 채널·영상·성과 읽기',
82
82
  },
83
+ drive: {
84
+ label: 'Google Drive (drive.file)',
85
+ // drive.file 은 비민감 스코프다 — 이 앱이 만들었거나 사용자가 이 앱으로 연 파일만 다룬다.
86
+ // 기존 폴더·공유 드라이브 전체를 다루려면 Drive 서비스 계정(mimi-seed-drive-auth)을 쓴다.
87
+ // 전체 drive 스코프는 제한(restricted) 스코프라 OAuth 앱 보안 심사가 필요해 여기 넣지 않는다.
88
+ scopes: ['https://www.googleapis.com/auth/drive.file'],
89
+ summary: 'drive_* — mimi-seed 가 만든 파일·폴더 업로드·갱신·정리 (기존 폴더·공유 드라이브는 Drive 서비스 계정)',
90
+ },
83
91
  };
84
92
  /** z.enum 등 튜플이 필요한 자리에 쓰는 도메인 id 목록 (선언 순서 유지). */
85
93
  export const DOMAIN_IDS = Object.keys(AUTH_DOMAINS);
86
94
  export const CLOUD_PLATFORM_SCOPE = AUTH_DOMAINS.gcp.scopes[0];
95
+ /** Drive OAuth 경로가 pre-flight 하는 스코프. 도메인 정의에서 파생한다(리터럴 중복 금지). */
96
+ export const DRIVE_FILE_SCOPE = AUTH_DOMAINS.drive.scopes[0];
87
97
  /**
88
98
  * Play Developer Reporting API(Android vitals 통계) 전용 스코프. androidpublisher 와
89
99
  * 별개다 — SA JWT 와 OAuth playstore 도메인 양쪽에 함께 실어야 통계 도구가 동작한다.
@@ -0,0 +1,122 @@
1
+ import type { JWT, OAuth2Client } from 'google-auth-library';
2
+ import type { DriveAuthSource } from '../auth/drive-auth.js';
3
+ /**
4
+ * Google Drive v3 래퍼 — 파일·폴더 조회, 업로드, 내용 갱신, 이름 변경·이동, 휴지통.
5
+ *
6
+ * 모든 호출에 supportsAllDrives 를 싣는다. 서비스 계정은 자기 저장 공간이 없어서 실제로는
7
+ * 공유 드라이브 안에서 일하는 경우가 대부분인데, 이 플래그가 빠지면 공유 드라이브 파일이
8
+ * "없는 파일"(404)로 보인다.
9
+ */
10
+ export type DriveClient = OAuth2Client | JWT;
11
+ export declare const FOLDER_MIME = "application/vnd.google-apps.folder";
12
+ /**
13
+ * Drive 파일·폴더 ID. 영숫자·밑줄·하이픈만 허용한다 — 이 값은 files.list 의 q 문자열 안에
14
+ * 그대로 들어가므로, 따옴표가 섞이면 질의가 다른 뜻이 된다. 'root' 는 내 드라이브 최상위 별칭.
15
+ */
16
+ export declare const DRIVE_ID_RE: RegExp;
17
+ /** files.list q 문자열 리터럴 이스케이프 (\ 와 ' ). */
18
+ export declare function escapeQueryValue(value: string): string;
19
+ export interface DriveFile {
20
+ id: string;
21
+ name: string;
22
+ mimeType: string;
23
+ isFolder: boolean;
24
+ size: number | null;
25
+ md5Checksum: string | null;
26
+ createdTime: string | null;
27
+ modifiedTime: string | null;
28
+ parents: string[];
29
+ driveId: string | null;
30
+ trashed: boolean;
31
+ webViewLink: string | null;
32
+ description: string | null;
33
+ }
34
+ /**
35
+ * Drive 에러를 "무엇을 고칠지"가 보이는 메시지로. 서비스 계정과 OAuth(drive.file) 는
36
+ * 같은 404 라도 원인이 달라 안내를 나눈다.
37
+ */
38
+ export declare function driveError(e: unknown, source?: DriveAuthSource, clientEmail?: string | null): Error;
39
+ export interface ListFilesInput {
40
+ folderId?: string;
41
+ nameContains?: string;
42
+ mimeType?: string;
43
+ includeTrashed?: boolean;
44
+ pageSize?: number;
45
+ pageToken?: string;
46
+ }
47
+ /** files.list 의 q 문자열 조립 (테스트가 이스케이프를 고정한다). */
48
+ export declare function buildListQuery(input: ListFilesInput): string;
49
+ export declare function listFiles(auth: DriveClient, input: ListFilesInput): Promise<{
50
+ files: DriveFile[];
51
+ nextPageToken: string | null;
52
+ }>;
53
+ export declare function getFile(auth: DriveClient, fileId: string): Promise<DriveFile>;
54
+ export interface CreateFolderInput {
55
+ name: string;
56
+ parentId?: string;
57
+ /** 같은 이름의 폴더가 부모 안에 이미 있으면 새로 만들지 않고 그것을 돌려준다 (기본 true). */
58
+ reuseExisting?: boolean;
59
+ }
60
+ export declare function createFolder(auth: DriveClient, input: CreateFolderInput): Promise<{
61
+ status: "exists";
62
+ folder: DriveFile;
63
+ } | {
64
+ status: "created";
65
+ folder: DriveFile;
66
+ }>;
67
+ /** 확장자 → MIME. 모르면 application/octet-stream (Drive 가 Google 문서로 변환하지 않는다). */
68
+ export declare function guessMimeType(filePath: string): string;
69
+ export interface LocalFile {
70
+ path: string;
71
+ size: number;
72
+ mimeType: string;
73
+ }
74
+ /** 업로드할 로컬 파일 점검 — 절대 경로, 일반 파일, 비어 있지 않음. */
75
+ export declare function inspectLocalFile(filePath: string, mimeType?: string): LocalFile;
76
+ /** 로컬 파일 MD5 — 업로드 결과의 md5Checksum 과 비교해 전송 무결성을 확인한다. */
77
+ export declare function md5OfFile(filePath: string): Promise<string>;
78
+ export interface UploadFileInput {
79
+ filePath: string;
80
+ parentId?: string;
81
+ name?: string;
82
+ mimeType?: string;
83
+ /** 같은 폴더에 같은 이름이 있을 때: error(기본) — 덮어쓰기 대신 drive_update_file_content 를 안내, create_new — 하나 더 만든다. */
84
+ onConflict?: 'error' | 'create_new';
85
+ }
86
+ export declare function uploadFile(auth: DriveClient, input: UploadFileInput): Promise<{
87
+ status: "uploaded";
88
+ file: DriveFile;
89
+ local: LocalFile;
90
+ verified: boolean | null;
91
+ }>;
92
+ export interface UpdateContentInput {
93
+ fileId: string;
94
+ filePath: string;
95
+ mimeType?: string;
96
+ }
97
+ /** 기존 파일의 내용을 로컬 파일로 교체 (같은 fileId·링크 유지, Drive 가 이전 버전을 보관). */
98
+ export declare function updateFileContent(auth: DriveClient, input: UpdateContentInput): Promise<{
99
+ status: "updated";
100
+ before: DriveFile;
101
+ after: DriveFile;
102
+ local: LocalFile;
103
+ verified: boolean | null;
104
+ }>;
105
+ export interface UpdateMetadataInput {
106
+ fileId: string;
107
+ name?: string;
108
+ description?: string;
109
+ moveToFolderId?: string;
110
+ }
111
+ /** 이름·설명 변경, 다른 폴더로 이동. 하나 이상 바꿔야 한다. */
112
+ export declare function updateFileMetadata(auth: DriveClient, input: UpdateMetadataInput): Promise<{
113
+ status: "updated";
114
+ before: DriveFile;
115
+ after: DriveFile;
116
+ }>;
117
+ /** 휴지통으로 이동 (30일 안에는 Drive 휴지통에서 되살릴 수 있다). */
118
+ export declare function trashFile(auth: DriveClient, fileId: string): Promise<{
119
+ status: "trashed";
120
+ before: DriveFile;
121
+ after: DriveFile;
122
+ }>;