@oasis-path/gamma-sdk 1.0.4 → 1.0.6

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/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { GammaFilesClientConfig, UploadFileOptions, UploadFileResponse, ListFilesResponse, FileMetadataResponse, DeleteFileResponse, PresignedUrlOptions, PresignedUrlResponse } from './types';
1
+ import { GammaFilesClientConfig, UploadFileOptions, UploadFileResponse, ListFilesResponse, FileMetadataResponse, DeleteFileResponse, PresignedUrlOptions, PresignedUrlResponse, ViewFileByTokenResult } from './types';
2
2
  export declare class GammaFilesClient {
3
3
  private baseUrl;
4
4
  private apiKey;
@@ -9,6 +9,6 @@ export declare class GammaFilesClient {
9
9
  deleteFile(fileId: string): Promise<DeleteFileResponse>;
10
10
  getFileMetadata(fileId: string): Promise<FileMetadataResponse>;
11
11
  generatePresignedUrl(options: PresignedUrlOptions): Promise<PresignedUrlResponse>;
12
- viewFileByToken(token: string): Promise<ArrayBuffer>;
12
+ viewFileByToken(fileId: string, token: string): Promise<ViewFileByTokenResult>;
13
13
  private request;
14
14
  }
package/dist/client.js CHANGED
@@ -32,8 +32,8 @@ class GammaFilesClient {
32
32
  async generatePresignedUrl(options) {
33
33
  return (0, generatePresignedUrl_1.generatePresignedUrl)(options, this.request.bind(this));
34
34
  }
35
- async viewFileByToken(token) {
36
- return (0, viewFileByToken_1.viewFileByToken)(token, this.request.bind(this));
35
+ async viewFileByToken(fileId, token) {
36
+ return (0, viewFileByToken_1.viewFileByToken)(fileId, token, this.request.bind(this));
37
37
  }
38
38
  async request(method, path, options) {
39
39
  return (0, request_1.makeRequest)(method, path, this.baseUrl, this.apiKey, options);
@@ -3,8 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generatePresignedUrl = generatePresignedUrl;
4
4
  async function generatePresignedUrl(options, request) {
5
5
  const url = '/api/files/presigned-url';
6
+ const payload = {
7
+ ...options,
8
+ maxUsageCount: options.maxUsageCount ?? 1
9
+ };
6
10
  return request('POST', url, {
7
- body: JSON.stringify(options),
11
+ body: JSON.stringify(payload),
8
12
  headers: {
9
13
  'Content-Type': 'application/json',
10
14
  },
@@ -3,4 +3,5 @@ export declare function makeRequest<T>(method: string, path: string, baseUrl: st
3
3
  headers?: Record<string, string>;
4
4
  binary?: boolean;
5
5
  skipAuth?: boolean;
6
+ includeHeaders?: boolean;
6
7
  }): Promise<T>;
@@ -78,7 +78,24 @@ async function makeRequest(method, path, baseUrl, apiKey, options = {}) {
78
78
  return;
79
79
  }
80
80
  if (options.binary) {
81
- resolve(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
81
+ const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
82
+ if (options.includeHeaders) {
83
+ const result = {
84
+ data: arrayBuffer,
85
+ headers: {
86
+ contentType: res.headers['content-type'] || '',
87
+ contentLength: parseInt(res.headers['content-length'] || '0', 10),
88
+ contentDisposition: res.headers['content-disposition'] || '',
89
+ etag: res.headers['etag'],
90
+ cacheControl: res.headers['cache-control'],
91
+ cfCacheTag: res.headers['cf-cache-tag'],
92
+ }
93
+ };
94
+ resolve(result);
95
+ }
96
+ else {
97
+ resolve(arrayBuffer);
98
+ }
82
99
  }
83
100
  else {
84
101
  const data = JSON.parse(responseText);
@@ -5,35 +5,57 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.uploadFile = uploadFile;
7
7
  const form_data_1 = __importDefault(require("form-data"));
8
+ const stream_1 = require("stream");
8
9
  async function uploadFile(baseUrl, apiKey, options, request) {
9
10
  const { file, filename, mimeType, folderId } = options;
10
11
  const form = new form_data_1.default();
11
- let fileBuffer;
12
12
  let contentType = mimeType || 'application/octet-stream';
13
- if (Buffer.isBuffer(file)) {
14
- fileBuffer = file;
13
+ // Handle different file input types
14
+ if (file instanceof stream_1.Readable || file.pipe) {
15
+ // Stream support for Node.js - efficient for large files
16
+ form.append('file', file, {
17
+ filename,
18
+ contentType,
19
+ });
20
+ }
21
+ else if (Buffer.isBuffer(file)) {
22
+ // Direct buffer support
23
+ form.append('file', file, {
24
+ filename,
25
+ contentType,
26
+ });
15
27
  }
16
28
  else if (typeof file === 'string') {
17
- // Handle base64 string
18
- fileBuffer = Buffer.from(file, 'base64');
29
+ // Handle base64 string - convert to buffer
30
+ const fileBuffer = Buffer.from(file, 'base64');
31
+ form.append('file', fileBuffer, {
32
+ filename,
33
+ contentType,
34
+ });
19
35
  }
20
36
  else if (typeof Blob !== 'undefined' && file instanceof Blob) {
37
+ // Browser Blob support - must convert to buffer
21
38
  const arrayBuffer = await file.arrayBuffer();
22
- fileBuffer = Buffer.from(arrayBuffer);
39
+ const fileBuffer = Buffer.from(arrayBuffer);
23
40
  contentType = mimeType || file.type || 'application/octet-stream';
41
+ form.append('file', fileBuffer, {
42
+ filename,
43
+ contentType,
44
+ });
24
45
  }
25
46
  else if (typeof File !== 'undefined' && file instanceof File) {
47
+ // Browser File support - must convert to buffer
26
48
  const arrayBuffer = await file.arrayBuffer();
27
- fileBuffer = Buffer.from(arrayBuffer);
49
+ const fileBuffer = Buffer.from(arrayBuffer);
28
50
  contentType = mimeType || file.type || 'application/octet-stream';
51
+ form.append('file', fileBuffer, {
52
+ filename,
53
+ contentType,
54
+ });
29
55
  }
30
56
  else {
31
- throw new Error('Unsupported file type');
57
+ throw new Error('Unsupported file type. Supported types: Buffer, Stream, Blob, File, or base64 string');
32
58
  }
33
- form.append('file', fileBuffer, {
34
- filename,
35
- contentType,
36
- });
37
59
  const url = folderId
38
60
  ? `/api/files/upload/${folderId}`
39
61
  : '/api/files/upload';
@@ -1 +1,2 @@
1
- export declare function viewFileByToken(token: string, request: <T>(method: string, path: string, options?: any) => Promise<T>): Promise<ArrayBuffer>;
1
+ import { ViewFileByTokenResult } from '../types';
2
+ export declare function viewFileByToken(fileId: string, token: string, request: <T>(method: string, path: string, options?: any) => Promise<T>): Promise<ViewFileByTokenResult>;
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.viewFileByToken = viewFileByToken;
4
- async function viewFileByToken(token, request) {
5
- const url = `/api/files/view/${token}`;
4
+ async function viewFileByToken(fileId, token, request) {
5
+ const url = `/api/files/view/${fileId}?token=${encodeURIComponent(token)}`;
6
6
  return request('GET', url, {
7
7
  binary: true,
8
- skipAuth: true
8
+ skipAuth: true,
9
+ includeHeaders: true
9
10
  });
10
11
  }
package/dist/types.d.ts CHANGED
@@ -13,7 +13,7 @@ export interface FileMetadata {
13
13
  createdAt: string;
14
14
  }
15
15
  export interface UploadFileOptions {
16
- file: Buffer | Blob | File | string;
16
+ file: Buffer | Blob | File | string | NodeJS.ReadableStream;
17
17
  filename: string;
18
18
  mimeType?: string;
19
19
  folderId?: string;
@@ -37,6 +37,7 @@ export interface DeleteFileResponse {
37
37
  export interface PresignedUrlOptions {
38
38
  fileId: string;
39
39
  expiresIn?: number;
40
+ maxUsageCount?: number;
40
41
  }
41
42
  export interface PresignedUrlResponse {
42
43
  success: true;
@@ -48,6 +49,17 @@ export interface DownloadFileResult {
48
49
  file: FileMetadata;
49
50
  data: ArrayBuffer;
50
51
  }
52
+ export interface ViewFileByTokenResult {
53
+ data: ArrayBuffer;
54
+ headers: {
55
+ contentType: string;
56
+ contentLength: number;
57
+ contentDisposition: string;
58
+ etag?: string;
59
+ cacheControl?: string;
60
+ cfCacheTag?: string;
61
+ };
62
+ }
51
63
  export interface ApiErrorResponse {
52
64
  success: false;
53
65
  error: string;
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "@oasis-path/gamma-sdk",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "TypeScript SDK for Gamma Files API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
- "publishConfig": {
8
- "access": "public"
7
+ "publishConfig": { "access": "public" },
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "watch": "tsc --watch",
11
+ "prepublishOnly": "pnpm run build"
9
12
  },
10
13
  "keywords": [
11
14
  "gamma",
@@ -26,9 +29,5 @@
26
29
  },
27
30
  "files": [
28
31
  "dist"
29
- ],
30
- "scripts": {
31
- "build": "tsc",
32
- "watch": "tsc --watch"
33
- }
34
- }
32
+ ]
33
+ }
package/README.md DELETED
@@ -1,285 +0,0 @@
1
- # Gamma Files SDK
2
-
3
- TypeScript/JavaScript SDK for interacting with the Gamma Files API.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- pnpm install @gamma/files-sdk
9
- ```
10
-
11
- Or if you're developing locally:
12
-
13
- ```bash
14
- cd sdk
15
- pnpm install
16
- pnpm run build
17
- ```
18
-
19
- Then in your project:
20
-
21
- ```bash
22
- pnpm install ../sdk
23
- ```
24
-
25
- ## Configuration
26
-
27
- Create a client instance with your API key and base URL:
28
-
29
- ```typescript
30
- import { GammaFilesClient } from '@gamma/files-sdk';
31
-
32
- const client = new GammaFilesClient({
33
- baseUrl: 'http://localhost:3000',
34
- apiKey: 'your-api-key-here'
35
- });
36
- ```
37
-
38
- ## Usage Examples
39
-
40
- ### Upload a File
41
-
42
- ```typescript
43
- import * as fs from 'fs';
44
-
45
- // Upload from Node.js Buffer
46
- const fileBuffer = fs.readFileSync('./document.pdf');
47
- const result = await client.uploadFile({
48
- file: fileBuffer,
49
- filename: 'document.pdf',
50
- mimeType: 'application/pdf',
51
- folderId: 'folder-id-here' // optional, uploads to root if not specified
52
- });
53
-
54
- console.log('Uploaded file:', result.file);
55
- ```
56
-
57
- In browser environment:
58
-
59
- ```typescript
60
- // Upload from File input
61
- const fileInput = document.querySelector('input[type="file"]');
62
- const file = fileInput.files[0];
63
-
64
- const result = await client.uploadFile({
65
- file: file,
66
- filename: file.name,
67
- mimeType: file.type,
68
- folderId: 'folder-id-here' // optional
69
- });
70
- ```
71
-
72
- ### Download a File
73
-
74
- ```typescript
75
- const fileData = await client.downloadFile('file-id-here');
76
-
77
- // In Node.js, save to disk
78
- const buffer = Buffer.from(fileData);
79
- fs.writeFileSync('./downloaded-file.pdf', buffer);
80
-
81
- // In browser, create a download link
82
- const blob = new Blob([fileData]);
83
- const url = URL.createObjectURL(blob);
84
- const a = document.createElement('a');
85
- a.href = url;
86
- a.download = 'file.pdf';
87
- a.click();
88
- ```
89
-
90
- ### List Files in a Folder
91
-
92
- ```typescript
93
- const result = await client.listFiles('folder-id-here');
94
-
95
- console.log('Files:', result.files);
96
- result.files.forEach(file => {
97
- console.log(`- ${file.originalName} (${file.size} bytes)`);
98
- });
99
- ```
100
-
101
- ### Get File Metadata
102
-
103
- ```typescript
104
- const result = await client.getFileMetadata('file-id-here');
105
-
106
- console.log('File metadata:', result.file);
107
- console.log('Name:', result.file.originalName);
108
- console.log('Size:', result.file.size);
109
- console.log('Type:', result.file.mimeType);
110
- console.log('Uploaded:', result.file.createdAt);
111
- ```
112
-
113
- ### Delete a File
114
-
115
- ```typescript
116
- const result = await client.deleteFile('file-id-here');
117
- console.log(result.message); // "File deleted successfully"
118
- ```
119
-
120
- ### Generate Presigned URL
121
-
122
- Generate a temporary URL for file access without requiring API key authentication:
123
-
124
- ```typescript
125
- const result = await client.generatePresignedUrl({
126
- fileId: 'file-id-here',
127
- expiresIn: 3600 // optional, defaults to 3600 seconds (1 hour)
128
- });
129
-
130
- console.log('Presigned URL:', result.url);
131
- console.log('Token:', result.token);
132
- console.log('Expires at:', result.expiresAt);
133
-
134
- // Share this URL with anyone - no API key needed
135
- ```
136
-
137
- ### View File by Token
138
-
139
- Access a file using a presigned token (no API key required):
140
-
141
- ```typescript
142
- const fileData = await client.viewFileByToken('presigned-token-here');
143
-
144
- // Handle the file data as needed
145
- const buffer = Buffer.from(fileData);
146
- fs.writeFileSync('./viewed-file.pdf', buffer);
147
- ```
148
-
149
- ## API Reference
150
-
151
- ### `GammaFilesClient`
152
-
153
- #### Constructor
154
-
155
- ```typescript
156
- new GammaFilesClient(config: GammaFilesClientConfig)
157
- ```
158
-
159
- **Parameters:**
160
- - `config.baseUrl` - Base URL of the Gamma API
161
- - `config.apiKey` - Your API key (must have appropriate permissions)
162
-
163
- #### Methods
164
-
165
- ##### `uploadFile(options: UploadFileOptions): Promise<UploadFileResponse>`
166
-
167
- Upload a file to the server.
168
-
169
- **Parameters:**
170
- - `options.file` - File data (Buffer, Blob, or File object)
171
- - `options.filename` - Name of the file
172
- - `options.mimeType` - MIME type (optional, will be detected if not provided)
173
- - `options.folderId` - Target folder ID (optional, uploads to root folder if not specified)
174
-
175
- **Returns:** Upload response with file metadata
176
-
177
- **API Key Permissions Required:** `write` or `admin`
178
-
179
- ##### `downloadFile(fileId: string): Promise<ArrayBuffer>`
180
-
181
- Download a file by ID.
182
-
183
- **Parameters:**
184
- - `fileId` - ID of the file to download
185
-
186
- **Returns:** File data as ArrayBuffer
187
-
188
- **API Key Permissions Required:** `read`, `write`, or `admin`
189
-
190
- ##### `listFiles(folderId: string): Promise<ListFilesResponse>`
191
-
192
- List all files in a folder.
193
-
194
- **Parameters:**
195
- - `folderId` - ID of the folder
196
-
197
- **Returns:** List of files with metadata
198
-
199
- **API Key Permissions Required:** `read`, `write`, or `admin`
200
-
201
- ##### `deleteFile(fileId: string): Promise<DeleteFileResponse>`
202
-
203
- Delete a file by ID.
204
-
205
- **Parameters:**
206
- - `fileId` - ID of the file to delete
207
-
208
- **Returns:** Deletion confirmation message
209
-
210
- **API Key Permissions Required:** `write` or `admin`
211
-
212
- ##### `getFileMetadata(fileId: string): Promise<FileMetadataResponse>`
213
-
214
- Get metadata for a specific file.
215
-
216
- **Parameters:**
217
- - `fileId` - ID of the file
218
-
219
- **Returns:** File metadata
220
-
221
- **API Key Permissions Required:** `read`, `write`, or `admin`
222
-
223
- ##### `generatePresignedUrl(options: PresignedUrlOptions): Promise<PresignedUrlResponse>`
224
-
225
- Generate a presigned URL for temporary file access.
226
-
227
- **Parameters:**
228
- - `options.fileId` - ID of the file
229
- - `options.expiresIn` - Expiration time in seconds (min: 60, max: 86400, default: 3600)
230
-
231
- **Returns:** Presigned URL information including token, full URL, and expiration time
232
-
233
- **API Key Permissions Required:** `read`, `write`, or `admin`
234
-
235
- ##### `viewFileByToken(token: string): Promise<ArrayBuffer>`
236
-
237
- Access a file using a presigned token (no API key required).
238
-
239
- **Parameters:**
240
- - `token` - Presigned token from `generatePresignedUrl`
241
-
242
- **Returns:** File data as ArrayBuffer
243
-
244
- **API Key Permissions Required:** None (uses token authentication)
245
-
246
- ## Types
247
-
248
- All TypeScript types are exported from the package:
249
-
250
- ```typescript
251
- import {
252
- GammaFilesClient,
253
- GammaFilesClientConfig,
254
- FileMetadata,
255
- UploadFileOptions,
256
- UploadFileResponse,
257
- ListFilesResponse,
258
- FileMetadataResponse,
259
- DeleteFileResponse,
260
- PresignedUrlOptions,
261
- PresignedUrlResponse,
262
- DownloadFileResult,
263
- ApiErrorResponse
264
- } from '@gamma/files-sdk';
265
- ```
266
-
267
- ## Error Handling
268
-
269
- All methods throw errors when requests fail:
270
-
271
- ```typescript
272
- try {
273
- const result = await client.uploadFile({
274
- file: buffer,
275
- filename: 'test.pdf'
276
- });
277
- console.log('Success:', result);
278
- } catch (error) {
279
- console.error('Upload failed:', error.message);
280
- }
281
- ```
282
-
283
- ## License
284
-
285
- MIT