easy-airtable-api 0.0.17 → 0.2.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/CHANGELOG.md +37 -0
- package/README.md +97 -1
- package/package.json +6 -3
- package/easy-airtable-api-0.0.17.tgz +0 -0
- package/lib/bases.d.ts +0 -18
- package/lib/bases.js +0 -40
- package/lib/cli.d.ts +0 -2
- package/lib/cli.js +0 -82
- package/lib/codegen/build.d.ts +0 -2
- package/lib/codegen/build.js +0 -25
- package/lib/codegen/emit-typescript.d.ts +0 -8
- package/lib/codegen/emit-typescript.js +0 -104
- package/lib/codegen/generate.d.ts +0 -2
- package/lib/codegen/generate.js +0 -23
- package/lib/codegen/identifiers.d.ts +0 -7
- package/lib/codegen/identifiers.js +0 -51
- package/lib/codegen/index.d.ts +0 -3
- package/lib/codegen/index.js +0 -2
- package/lib/codegen/load-schema.d.ts +0 -3
- package/lib/codegen/load-schema.js +0 -28
- package/lib/codegen/map-field.d.ts +0 -31
- package/lib/codegen/map-field.js +0 -278
- package/lib/codegen/normalize-schema.d.ts +0 -11
- package/lib/codegen/normalize-schema.js +0 -61
- package/lib/codegen/types.d.ts +0 -62
- package/lib/codegen/types.js +0 -1
- package/lib/codegen/utils.d.ts +0 -14
- package/lib/codegen/utils.js +0 -30
- package/lib/codegen/write-atomic.d.ts +0 -1
- package/lib/codegen/write-atomic.js +0 -11
- package/lib/index.d.ts +0 -8
- package/lib/index.js +0 -3
- package/lib/records.d.ts +0 -162
- package/lib/records.js +0 -300
- package/lib/requests.d.ts +0 -74
- package/lib/requests.js +0 -362
- package/lib/types/bases.d.ts +0 -31
- package/lib/types/bases.js +0 -1
- package/lib/types/fields.d.ts +0 -328
- package/lib/types/fields.js +0 -1
- package/lib/types/metadata.d.ts +0 -24
- package/lib/types/metadata.js +0 -1
- package/lib/types/records.d.ts +0 -122
- package/lib/types/records.js +0 -1
- package/lib/types/tables.d.ts +0 -99
- package/lib/types/tables.js +0 -1
- package/lib/utils.d.ts +0 -4
- package/lib/utils.js +0 -19
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Breaking changes
|
|
6
|
+
|
|
7
|
+
- Requires Node.js 20 or later.
|
|
8
|
+
- Every request that Airtable or the network fails for good throws `AirtableApiError`, connection failures included (`statusCode` unset, Node's error as `cause`). Errors gain `attempts` and `earlierAttemptMayHaveApplied`, and `retryable` now means resending is safe: a create that failed after a 5xx or a dropped connection reports `false`.
|
|
9
|
+
- Creates are no longer resent after a 5xx or a dropped connection. They are still retried after a 429 or when the connection never opened, and updates, deletes, and reads still retry.
|
|
10
|
+
- When a later chunk of a batch helper fails, it throws `AirtableBatchError` with `completed`, `pending`, and the original error as `cause`.
|
|
11
|
+
- `maxDelayMs` defaults to 30 seconds. A server-requested wait longer than `maxDelayMs` now fails immediately instead of sleeping.
|
|
12
|
+
- `requestInterval: 0` means no pause, and record pagination now pauses between pages (500 ms by default).
|
|
13
|
+
- Generated `UpdateFields` accept `null`, generated files import only the shared types they use, and colliding type names get stable suffixes.
|
|
14
|
+
- The CLI rejects unknown options and invalid values. The unused codegen `format` option is removed.
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- `retry.timeoutMs` to set the socket inactivity timeout.
|
|
19
|
+
- `AirtableBatchError`, exported from the package root.
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- Text with multi-byte characters was corrupted when a character spanned two response chunks.
|
|
24
|
+
- Requests hung forever when the connection dropped mid-response.
|
|
25
|
+
- 429 retries now wait out Airtable's 30-second lockout.
|
|
26
|
+
- Every 5xx is retried. Error responses that aren't JSON keep their status code, and a 204 resolves to `undefined`.
|
|
27
|
+
- Network errors are recognized by Node's error code, so timeouts and DNS failures are retried.
|
|
28
|
+
- `apiURL` honors its protocol, port, and IPv6 hosts.
|
|
29
|
+
- `deleteRecord` retried after a 5xx or a dropped connection treats a 404 as success, since the earlier attempt deleted the record.
|
|
30
|
+
- Record, base, and table IDs are URL-encoded; empty IDs and `.` or `..` are rejected.
|
|
31
|
+
- Codegen types sync source fields correctly, and table names can no longer inject code through the generated comments.
|
|
32
|
+
|
|
33
|
+
## 0.1.0
|
|
34
|
+
|
|
35
|
+
- Exported a broader canonical public field/value type surface, including shared types used by generated code such as `AICell`, `BarcodeCell`, `BarcodeWrite`, `ButtonCell`, and `CollaboratorWrite`.
|
|
36
|
+
- Improved code generation to normalize legacy Airtable metadata variants, normalize Unicode identifiers, and emit collision-safe table/field constants and interface properties.
|
|
37
|
+
- Fixed generated typing for `aiText`, lookup/rollup nested collection results, duplicate field names, and response-mode guardrails for field-name-keyed generated record types.
|
|
38
|
+
- Expanded codegen fixture coverage and compile/type-level tests for aliases, Unicode, collisions, generated output safety, and response-mode compatibility.
|
|
39
|
+
|
|
3
40
|
## 0.0.17
|
|
4
41
|
|
|
5
42
|
- Reworked Airtable type generation around the new `easy-airtable-api/codegen` workflow.
|
package/README.md
CHANGED
|
@@ -25,6 +25,8 @@ npm install easy-airtable-api
|
|
|
25
25
|
bun add easy-airtable-api
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
+
Requires Node.js 20 or later.
|
|
29
|
+
|
|
28
30
|
## Recommended project setup
|
|
29
31
|
|
|
30
32
|
A good setup is to generate Airtable types once and commit the generated file.
|
|
@@ -189,6 +191,46 @@ await generateAirtableTypes({
|
|
|
189
191
|
});
|
|
190
192
|
```
|
|
191
193
|
|
|
194
|
+
### Clearing fields
|
|
195
|
+
|
|
196
|
+
Generated `UpdateFields` types accept `null` for every writable field, because Airtable clears a field when an update sends `null`. We checked this against Airtable for every writable field type; a rich text field keeps a single empty line (`"\n"`). `CreateFields` types don't accept `null`: leave a field out of a create instead.
|
|
197
|
+
|
|
198
|
+
### Generated type assumptions
|
|
199
|
+
|
|
200
|
+
Generated read types target Airtable's default JSON response mode:
|
|
201
|
+
|
|
202
|
+
- `cellFormat: 'json'`
|
|
203
|
+
- `returnFieldsByFieldId: false`
|
|
204
|
+
|
|
205
|
+
If you switch to `cellFormat: 'string'` or `returnFieldsByFieldId: true`, the response shape is no longer compatible with field-name-keyed generated interfaces. The read helpers now include type-level guardrails for this path, and incompatible calls fall back to untyped field maps unless you stay on the default JSON mode.
|
|
206
|
+
|
|
207
|
+
### Shared field/value types
|
|
208
|
+
|
|
209
|
+
Generated files import shared canonical field/value types from the package root instead of emitting duplicate local interfaces. You can import the same types in application code:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
import type {
|
|
213
|
+
AICell,
|
|
214
|
+
Attachment,
|
|
215
|
+
AttachmentWrite,
|
|
216
|
+
BarcodeCell,
|
|
217
|
+
BarcodeWrite,
|
|
218
|
+
ButtonCell,
|
|
219
|
+
Collaborator,
|
|
220
|
+
CollaboratorWrite,
|
|
221
|
+
} from 'easy-airtable-api';
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Examples:
|
|
225
|
+
|
|
226
|
+
- `aiText` read values use `AICell`
|
|
227
|
+
- attachment reads use `Attachment[]`, writes use `AttachmentWrite[]`
|
|
228
|
+
- collaborator reads use `Collaborator` / `Collaborator[]`, writes use `CollaboratorWrite` / `CollaboratorWrite[]`
|
|
229
|
+
- barcode reads use `BarcodeCell`, writes use `BarcodeWrite`
|
|
230
|
+
- button fields are readonly and use `ButtonCell`
|
|
231
|
+
|
|
232
|
+
These shared types make generated output and application code agree on one canonical public surface. They do not, by themselves, guarantee that every structured write shape has been exhaustively live-verified against Airtable in every edge case.
|
|
233
|
+
|
|
192
234
|
## Metadata/base APIs
|
|
193
235
|
|
|
194
236
|
### List accessible bases
|
|
@@ -281,17 +323,39 @@ const records = await getRecords({
|
|
|
281
323
|
retry: {
|
|
282
324
|
maxRetries: 2,
|
|
283
325
|
baseDelayMs: 250,
|
|
284
|
-
maxDelayMs:
|
|
326
|
+
maxDelayMs: 30000,
|
|
285
327
|
retryOn429: true,
|
|
286
328
|
retryOn5xx: true,
|
|
287
329
|
retryOnNetworkErrors: true,
|
|
288
330
|
useJitter: false,
|
|
331
|
+
timeoutMs: 60000,
|
|
289
332
|
},
|
|
290
333
|
});
|
|
291
334
|
```
|
|
292
335
|
|
|
293
336
|
The same `retry` option is supported by metadata helpers such as `listBases()` / `getBaseSchema()` and by `airtableRequestRaw()`.
|
|
294
337
|
|
|
338
|
+
How long the library waits between attempts:
|
|
339
|
+
|
|
340
|
+
- Normal retries back off exponentially from `baseDelayMs`, capped at `maxDelayMs` (30 seconds by default).
|
|
341
|
+
- After a `429`, Airtable rejects every request for 30 seconds, so the library waits at least that long before retrying. If the response has a `Retry-After` header, the library waits at least that long instead.
|
|
342
|
+
- If the wait the server asks for is longer than `maxDelayMs`, the library doesn't retry and throws the error right away. When the server sent a `Retry-After` header, the error's `retryAfterMs` holds it; a `429` without one leaves `retryAfterMs` unset, and Airtable's lockout is 30 seconds. With a `maxDelayMs` below 30 seconds, rate-limited requests therefore fail immediately.
|
|
343
|
+
|
|
344
|
+
Network errors are retried when Node reports a connection failure: `ECONNRESET`, `ECONNREFUSED`, `ETIMEDOUT`, `EPIPE`, `ENETUNREACH`, `EHOSTUNREACH`, `EAI_AGAIN`, or `ENOTFOUND`. An attempt that receives no data for `timeoutMs` (five minutes by default) fails with `ETIMEDOUT` and is retried the same way.
|
|
345
|
+
|
|
346
|
+
Requests that create something, such as `createRecord()`, `createRecords()`, `createBase()`, and `POST` requests sent with `airtableRequestRaw()`, are retried only when Airtable can't have applied them: after a `429` rate limit, or when the connection never opened (`ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`, `EHOSTUNREACH`). Airtable may already have created the records when it returns a `5xx` or the connection drops after sending, so the library does not send those requests again. Instead it throws the error, and you can check whether the records exist before trying again. Reads, updates, upserts, and deletes are retried as configured, including `getRecords()`, which uses `POST` to list records. When `deleteRecord()` is retried after a `5xx` or a dropped connection and the retry finds the record gone, the earlier attempt deleted it, so it reports the record as deleted. `deleteRecords()` doesn't do this, because a `404` for a batch doesn't say which record was missing; its error has `earlierAttemptMayHaveApplied: true` so you can check the records yourself.
|
|
347
|
+
|
|
348
|
+
### Errors
|
|
349
|
+
|
|
350
|
+
A request that Airtable or the network fails throws an `AirtableApiError`, whether Airtable answered with an error or the connection failed:
|
|
351
|
+
|
|
352
|
+
- `statusCode` and `airtableType` describe Airtable's answer. They are unset for a connection failure, whose Node error, with its `code`, is `cause`.
|
|
353
|
+
- `retryable` says whether resending the same request is safe and could succeed. It is `false` for a create that failed after Airtable may already have applied it.
|
|
354
|
+
- `attempts` is how many attempts were sent, and `earlierAttemptMayHaveApplied` says whether an earlier attempt failed in a way that may have applied the request.
|
|
355
|
+
- `retryAfterMs` holds the server's `Retry-After`, when it sent one.
|
|
356
|
+
|
|
357
|
+
A response whose body isn't valid JSON throws a plain `Error` instead. Input that Node rejects before sending anything, such as an API key containing a line break or an invalid `apiURL`, throws a `TypeError`.
|
|
358
|
+
|
|
295
359
|
## Runtime examples
|
|
296
360
|
|
|
297
361
|
### Get a single record
|
|
@@ -444,12 +508,38 @@ await deleteRecords({
|
|
|
444
508
|
});
|
|
445
509
|
```
|
|
446
510
|
|
|
511
|
+
### When a batch fails partway
|
|
512
|
+
|
|
513
|
+
`createRecords`, `updateRecords`, `replaceRecords`, `updateRecordsUpsert`, and `deleteRecords` send records in chunks of 10. If a chunk fails after earlier chunks succeeded, Airtable has already applied those earlier chunks. The helper then throws an `AirtableBatchError` that tells you what happened:
|
|
514
|
+
|
|
515
|
+
- `completed` holds what Airtable confirmed, in the helper's usual result shape.
|
|
516
|
+
- `pending` holds the inputs Airtable did not confirm, starting with the chunk that failed. After a `5xx` or a dropped connection, Airtable may still have applied that chunk, so check before you resend it.
|
|
517
|
+
- `cause` holds the original error. When it is an `AirtableApiError`, its `statusCode`, `retryable`, and `retryAfterMs` are there.
|
|
518
|
+
|
|
519
|
+
```ts
|
|
520
|
+
import { AirtableBatchError, createRecords } from 'easy-airtable-api';
|
|
521
|
+
|
|
522
|
+
try {
|
|
523
|
+
await createRecords({ apiKey, baseId, tableId, records });
|
|
524
|
+
} catch (error) {
|
|
525
|
+
if (error instanceof AirtableBatchError) {
|
|
526
|
+
console.log('Created before the failure:', error.completed);
|
|
527
|
+
console.log('Not confirmed:', error.pending.length, 'records');
|
|
528
|
+
console.log('Cause:', error.cause);
|
|
529
|
+
}
|
|
530
|
+
throw error;
|
|
531
|
+
}
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
When the first chunk fails, no earlier chunk succeeded, so the helper throws the original error instead. The same caution applies: after a `5xx` or a dropped connection, that chunk may still have been applied.
|
|
535
|
+
|
|
447
536
|
## Exports
|
|
448
537
|
|
|
449
538
|
Runtime package:
|
|
450
539
|
|
|
451
540
|
```ts
|
|
452
541
|
import {
|
|
542
|
+
AirtableBatchError,
|
|
453
543
|
airtableRequestRaw,
|
|
454
544
|
createBase,
|
|
455
545
|
createRecord,
|
|
@@ -479,6 +569,12 @@ import {
|
|
|
479
569
|
} from 'easy-airtable-api/codegen';
|
|
480
570
|
```
|
|
481
571
|
|
|
572
|
+
## Testing
|
|
573
|
+
|
|
574
|
+
Codegen coverage lives in focused fixtures under `tests/fixtures/` and runs as part of the normal Vitest suite.
|
|
575
|
+
|
|
576
|
+
The fixture matrix also includes compile checks for generated output and type-level guardrail tests for response modes that are incompatible with field-name-keyed generated types.
|
|
577
|
+
|
|
482
578
|
## Changelog
|
|
483
579
|
|
|
484
580
|
See [CHANGELOG.md](./CHANGELOG.md).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "easy-airtable-api",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Lightweight TypeScript-first Airtable client with metadata-based type generation.",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"lint": "eslint 'src/**/*.{ts,tsx}'",
|
|
27
27
|
"test": "npm run test:all",
|
|
28
28
|
"test:codegen": "vitest run tests/codegen.test.ts",
|
|
29
|
-
"test:integration": "RUN_AIRTABLE_INTEGRATION_TESTS=true vitest run tests/get-record.test.ts tests/get-records.test.ts tests/create-records.test.ts tests/update-records.test.ts tests/delete-records.test.ts",
|
|
29
|
+
"test:integration": "RUN_AIRTABLE_INTEGRATION_TESTS=true vitest run tests/get-record.test.ts tests/get-records.test.ts tests/create-records.test.ts tests/update-records.test.ts tests/delete-records.test.ts tests/create-base.integration.test.ts tests/get-base-schema.integration.test.ts",
|
|
30
30
|
"test:all": "vitest run"
|
|
31
31
|
},
|
|
32
32
|
"keywords": [
|
|
@@ -39,6 +39,9 @@
|
|
|
39
39
|
"homepage": "https://marcellocurto.com/code/easy-airtable-api",
|
|
40
40
|
"author": "Marcello Curto",
|
|
41
41
|
"license": "MIT",
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=20"
|
|
44
|
+
},
|
|
42
45
|
"prettier": {
|
|
43
46
|
"trailingComma": "es5",
|
|
44
47
|
"tabWidth": 2,
|
|
@@ -67,4 +70,4 @@
|
|
|
67
70
|
"typescript": "^5.4.3",
|
|
68
71
|
"vitest": "^1.4.0"
|
|
69
72
|
}
|
|
70
|
-
}
|
|
73
|
+
}
|
|
Binary file
|
package/lib/bases.d.ts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import type { AirtableRetryOptions } from './requests.js';
|
|
2
|
-
import type { CreateBaseRequestBody, CreateBaseResponse, ListBasesResponse } from './types/bases.js';
|
|
3
|
-
import type { AirtableBaseSchema } from './types/metadata.js';
|
|
4
|
-
export declare function listBases({ apiKey, offset, retry, }: {
|
|
5
|
-
apiKey: string;
|
|
6
|
-
offset?: string;
|
|
7
|
-
retry?: AirtableRetryOptions;
|
|
8
|
-
}): Promise<ListBasesResponse>;
|
|
9
|
-
export declare function createBase({ apiKey, body, retry, }: {
|
|
10
|
-
apiKey: string;
|
|
11
|
-
body: CreateBaseRequestBody;
|
|
12
|
-
retry?: AirtableRetryOptions;
|
|
13
|
-
}): Promise<CreateBaseResponse>;
|
|
14
|
-
export declare function getBaseSchema({ apiKey, baseId, retry, }: {
|
|
15
|
-
apiKey: string;
|
|
16
|
-
baseId: string;
|
|
17
|
-
retry?: AirtableRetryOptions;
|
|
18
|
-
}): Promise<AirtableBaseSchema>;
|
package/lib/bases.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import { airtableApiRequest } from './requests.js';
|
|
2
|
-
export async function listBases({ apiKey, offset, retry, }) {
|
|
3
|
-
return airtableApiRequest({
|
|
4
|
-
apiKey,
|
|
5
|
-
method: 'GET',
|
|
6
|
-
path: '/meta/bases',
|
|
7
|
-
query: { offset },
|
|
8
|
-
retry,
|
|
9
|
-
});
|
|
10
|
-
}
|
|
11
|
-
export async function createBase({ apiKey, body, retry, }) {
|
|
12
|
-
return airtableApiRequest({
|
|
13
|
-
apiKey,
|
|
14
|
-
method: 'POST',
|
|
15
|
-
path: '/meta/bases',
|
|
16
|
-
body,
|
|
17
|
-
retry,
|
|
18
|
-
requestContext: {
|
|
19
|
-
method: 'POST',
|
|
20
|
-
path: '/meta/bases',
|
|
21
|
-
},
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
export async function getBaseSchema({ apiKey, baseId, retry, }) {
|
|
25
|
-
if (!baseId) {
|
|
26
|
-
throw new Error('Base ID is not set. Please provide a valid Airtable base ID.');
|
|
27
|
-
}
|
|
28
|
-
const path = `/meta/bases/${encodeURIComponent(baseId)}/tables`;
|
|
29
|
-
return airtableApiRequest({
|
|
30
|
-
apiKey,
|
|
31
|
-
method: 'GET',
|
|
32
|
-
path,
|
|
33
|
-
retry,
|
|
34
|
-
requestContext: {
|
|
35
|
-
method: 'GET',
|
|
36
|
-
baseId,
|
|
37
|
-
path,
|
|
38
|
-
},
|
|
39
|
-
});
|
|
40
|
-
}
|
package/lib/cli.d.ts
DELETED
package/lib/cli.js
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { generateAirtableTypes } from './codegen/generate.js';
|
|
3
|
-
function readFlag(args, flag) {
|
|
4
|
-
const index = args.indexOf(flag);
|
|
5
|
-
if (index === -1)
|
|
6
|
-
return undefined;
|
|
7
|
-
return args[index + 1];
|
|
8
|
-
}
|
|
9
|
-
function readMultiFlag(args, flag) {
|
|
10
|
-
const values = [];
|
|
11
|
-
args.forEach((argument, index) => {
|
|
12
|
-
if (argument === flag && args[index + 1]) {
|
|
13
|
-
values.push(args[index + 1]);
|
|
14
|
-
}
|
|
15
|
-
});
|
|
16
|
-
return values;
|
|
17
|
-
}
|
|
18
|
-
function hasFlag(args, flag) {
|
|
19
|
-
return args.includes(flag);
|
|
20
|
-
}
|
|
21
|
-
function printHelp() {
|
|
22
|
-
console.log(`easy-airtable-api generate [options]
|
|
23
|
-
|
|
24
|
-
Options:
|
|
25
|
-
--baseId <id>
|
|
26
|
-
--accessToken <token>
|
|
27
|
-
--apiKey <token>
|
|
28
|
-
--schemaPath <path>
|
|
29
|
-
--output <path>
|
|
30
|
-
--table <nameOrId> Repeatable
|
|
31
|
-
--enumMode <mode> literal | hybrid | broad
|
|
32
|
-
--schemaMode <mode> read | write | full
|
|
33
|
-
--createRequiredMode <mode> allOptional | primaryField
|
|
34
|
-
--unknownFieldBehavior <mode> unknown | error
|
|
35
|
-
--noTableIds
|
|
36
|
-
--noFieldIds
|
|
37
|
-
--help
|
|
38
|
-
`);
|
|
39
|
-
}
|
|
40
|
-
async function main() {
|
|
41
|
-
const args = process.argv.slice(2);
|
|
42
|
-
const command = args[0];
|
|
43
|
-
if (!command || command === '--help' || command === '-h') {
|
|
44
|
-
printHelp();
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
if (command !== 'generate') {
|
|
48
|
-
throw new Error(`Unknown command: ${command}`);
|
|
49
|
-
}
|
|
50
|
-
const tables = readMultiFlag(args, '--table');
|
|
51
|
-
const schemaPath = readFlag(args, '--schemaPath');
|
|
52
|
-
const baseId = readFlag(args, '--baseId');
|
|
53
|
-
const accessToken = readFlag(args, '--accessToken');
|
|
54
|
-
const apiKey = readFlag(args, '--apiKey');
|
|
55
|
-
const source = schemaPath
|
|
56
|
-
? { schemaPath }
|
|
57
|
-
: {
|
|
58
|
-
baseId: baseId ?? '',
|
|
59
|
-
accessToken,
|
|
60
|
-
apiKey,
|
|
61
|
-
};
|
|
62
|
-
const result = await generateAirtableTypes({
|
|
63
|
-
source,
|
|
64
|
-
output: readFlag(args, '--output'),
|
|
65
|
-
tableNameOrId: tables.length ? tables : undefined,
|
|
66
|
-
enumMode: readFlag(args, '--enumMode'),
|
|
67
|
-
schemaMode: readFlag(args, '--schemaMode'),
|
|
68
|
-
createRequiredMode: readFlag(args, '--createRequiredMode'),
|
|
69
|
-
unknownFieldBehavior: readFlag(args, '--unknownFieldBehavior'),
|
|
70
|
-
includeTableIds: !hasFlag(args, '--noTableIds'),
|
|
71
|
-
includeFieldIds: !hasFlag(args, '--noFieldIds'),
|
|
72
|
-
});
|
|
73
|
-
console.log(`Generated ${result.tablesGenerated} table(s) at ${result.outputPath}`);
|
|
74
|
-
if (result.warnings.length) {
|
|
75
|
-
console.warn(`Warnings:\n- ${result.warnings.join('\n- ')}`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
main().catch((error) => {
|
|
79
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
80
|
-
console.error(message);
|
|
81
|
-
process.exit(1);
|
|
82
|
-
});
|
package/lib/codegen/build.d.ts
DELETED
package/lib/codegen/build.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { emitTypeScript } from './emit-typescript.js';
|
|
2
|
-
import { loadSchema } from './load-schema.js';
|
|
3
|
-
import { normalizeSchema } from './normalize-schema.js';
|
|
4
|
-
export async function buildAirtableTypes(options) {
|
|
5
|
-
const { source, tableNameOrId, enumMode = 'hybrid', createRequiredMode = 'allOptional', unknownFieldBehavior = 'unknown', includeTableIds = true, includeFieldIds = true, schemaMode = 'full', } = options;
|
|
6
|
-
const schema = await loadSchema(source);
|
|
7
|
-
const { normalizedBase, warnings } = normalizeSchema({
|
|
8
|
-
schema,
|
|
9
|
-
tableNameOrId,
|
|
10
|
-
enumMode,
|
|
11
|
-
unknownFieldBehavior,
|
|
12
|
-
});
|
|
13
|
-
const content = emitTypeScript({
|
|
14
|
-
normalizedBase,
|
|
15
|
-
includeTableIds,
|
|
16
|
-
includeFieldIds,
|
|
17
|
-
schemaMode,
|
|
18
|
-
createRequiredMode,
|
|
19
|
-
});
|
|
20
|
-
return {
|
|
21
|
-
content,
|
|
22
|
-
tablesGenerated: normalizedBase.tables.length,
|
|
23
|
-
warnings,
|
|
24
|
-
};
|
|
25
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import type { CreateRequiredMode, NormalizedBase, SchemaMode } from './types.js';
|
|
2
|
-
export declare function emitTypeScript({ normalizedBase, includeTableIds, includeFieldIds, schemaMode, createRequiredMode, }: {
|
|
3
|
-
normalizedBase: NormalizedBase;
|
|
4
|
-
includeTableIds: boolean;
|
|
5
|
-
includeFieldIds: boolean;
|
|
6
|
-
schemaMode: SchemaMode;
|
|
7
|
-
createRequiredMode: CreateRequiredMode;
|
|
8
|
-
}): string;
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import { quotePropertyKey, toSafeConstKey } from './identifiers.js';
|
|
2
|
-
function isPrimaryCreateField(field, primaryFieldId, createRequiredMode) {
|
|
3
|
-
return (createRequiredMode === 'primaryField' &&
|
|
4
|
-
field.id === primaryFieldId &&
|
|
5
|
-
Boolean(field.createType));
|
|
6
|
-
}
|
|
7
|
-
function emitInterface({ name, fields, kind, primaryFieldId, createRequiredMode, }) {
|
|
8
|
-
const writableFields = fields.filter((field) => {
|
|
9
|
-
if (kind === 'read')
|
|
10
|
-
return true;
|
|
11
|
-
if (kind === 'create')
|
|
12
|
-
return Boolean(field.createType);
|
|
13
|
-
return Boolean(field.updateType);
|
|
14
|
-
});
|
|
15
|
-
const lines = writableFields.map((field) => {
|
|
16
|
-
const type = kind === 'read'
|
|
17
|
-
? field.readType
|
|
18
|
-
: kind === 'create'
|
|
19
|
-
? field.createType
|
|
20
|
-
: field.updateType;
|
|
21
|
-
const isRequired = kind === 'create' &&
|
|
22
|
-
isPrimaryCreateField(field, primaryFieldId, createRequiredMode);
|
|
23
|
-
return ` ${quotePropertyKey(field.tsKey)}${isRequired ? '' : '?'}: ${type};`;
|
|
24
|
-
});
|
|
25
|
-
if (!lines.length) {
|
|
26
|
-
return `export interface ${name} {}`;
|
|
27
|
-
}
|
|
28
|
-
return [`export interface ${name} {`, ...lines, `}`].join('\n');
|
|
29
|
-
}
|
|
30
|
-
function emitEnumAliases(table) {
|
|
31
|
-
return table.fields
|
|
32
|
-
.filter((field) => Boolean(field.enumTypeAlias))
|
|
33
|
-
.map((field) => `export type ${field.tsTypeName} = ${field.enumTypeAlias};`);
|
|
34
|
-
}
|
|
35
|
-
function emitTableIds(normalizedBase) {
|
|
36
|
-
const lines = normalizedBase.tables.map((table) => ` ${toSafeConstKey(table.tsName)}: ${JSON.stringify(table.id)},`);
|
|
37
|
-
return ['export const tables = {', ...lines, '} as const;'].join('\n');
|
|
38
|
-
}
|
|
39
|
-
function emitFieldIds(normalizedBase) {
|
|
40
|
-
const lines = normalizedBase.tables.map((table) => {
|
|
41
|
-
const fieldLines = table.fields.map((field) => ` ${toSafeConstKey(field.tsKey)}: ${JSON.stringify(field.id)},`);
|
|
42
|
-
return [` ${toSafeConstKey(table.tsName)}: {`, ...fieldLines, ' },'].join('\n');
|
|
43
|
-
});
|
|
44
|
-
return ['export const fields = {', ...lines, '} as const;'].join('\n');
|
|
45
|
-
}
|
|
46
|
-
export function emitTypeScript({ normalizedBase, includeTableIds, includeFieldIds, schemaMode, createRequiredMode, }) {
|
|
47
|
-
const sections = [
|
|
48
|
-
'/* eslint-disable */',
|
|
49
|
-
'// Generated by easy-airtable-api. Do not edit manually.',
|
|
50
|
-
'',
|
|
51
|
-
"import type { AirtableRecord, Attachment, AttachmentWrite, Collaborator } from 'easy-airtable-api';",
|
|
52
|
-
'',
|
|
53
|
-
'export interface Barcode {',
|
|
54
|
-
' text: string;',
|
|
55
|
-
' type?: string;',
|
|
56
|
-
'}',
|
|
57
|
-
'',
|
|
58
|
-
'export interface ButtonFieldValue {',
|
|
59
|
-
' label: string;',
|
|
60
|
-
' url: string | null;',
|
|
61
|
-
'}',
|
|
62
|
-
];
|
|
63
|
-
if (includeTableIds) {
|
|
64
|
-
sections.push('', emitTableIds(normalizedBase));
|
|
65
|
-
}
|
|
66
|
-
if (includeFieldIds) {
|
|
67
|
-
sections.push('', emitFieldIds(normalizedBase));
|
|
68
|
-
}
|
|
69
|
-
normalizedBase.tables.forEach((table) => {
|
|
70
|
-
sections.push('');
|
|
71
|
-
sections.push(`// ${table.name} (${table.id})`);
|
|
72
|
-
const enumAliases = emitEnumAliases(table);
|
|
73
|
-
if (enumAliases.length) {
|
|
74
|
-
sections.push(...enumAliases, '');
|
|
75
|
-
}
|
|
76
|
-
if (schemaMode === 'read' || schemaMode === 'full') {
|
|
77
|
-
sections.push(emitInterface({
|
|
78
|
-
name: `${table.tsName}RecordFields`,
|
|
79
|
-
fields: table.fields,
|
|
80
|
-
kind: 'read',
|
|
81
|
-
primaryFieldId: table.primaryFieldId,
|
|
82
|
-
createRequiredMode,
|
|
83
|
-
}));
|
|
84
|
-
sections.push(`export type ${table.tsName}Record = AirtableRecord<${table.tsName}RecordFields>;`);
|
|
85
|
-
}
|
|
86
|
-
if (schemaMode === 'write' || schemaMode === 'full') {
|
|
87
|
-
sections.push(emitInterface({
|
|
88
|
-
name: `${table.tsName}CreateFields`,
|
|
89
|
-
fields: table.fields,
|
|
90
|
-
kind: 'create',
|
|
91
|
-
primaryFieldId: table.primaryFieldId,
|
|
92
|
-
createRequiredMode,
|
|
93
|
-
}));
|
|
94
|
-
sections.push(emitInterface({
|
|
95
|
-
name: `${table.tsName}UpdateFields`,
|
|
96
|
-
fields: table.fields,
|
|
97
|
-
kind: 'update',
|
|
98
|
-
primaryFieldId: table.primaryFieldId,
|
|
99
|
-
createRequiredMode,
|
|
100
|
-
}));
|
|
101
|
-
}
|
|
102
|
-
});
|
|
103
|
-
return `${sections.join('\n')}\n`;
|
|
104
|
-
}
|
package/lib/codegen/generate.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { access } from 'node:fs/promises';
|
|
2
|
-
import { resolve } from 'node:path';
|
|
3
|
-
import { buildAirtableTypes } from './build.js';
|
|
4
|
-
import { writeAtomic } from './write-atomic.js';
|
|
5
|
-
async function defaultOutputPath() {
|
|
6
|
-
try {
|
|
7
|
-
await access(resolve('src'));
|
|
8
|
-
return './src/airtable.generated.ts';
|
|
9
|
-
}
|
|
10
|
-
catch {
|
|
11
|
-
return './airtable.generated.ts';
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
export async function generateAirtableTypes(options) {
|
|
15
|
-
const result = await buildAirtableTypes(options);
|
|
16
|
-
const outputPath = options.output ?? (await defaultOutputPath());
|
|
17
|
-
const writtenPath = await writeAtomic(outputPath, result.content);
|
|
18
|
-
return {
|
|
19
|
-
outputPath: writtenPath,
|
|
20
|
-
tablesGenerated: result.tablesGenerated,
|
|
21
|
-
warnings: result.warnings,
|
|
22
|
-
};
|
|
23
|
-
}
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
export declare function toPascalCase(value: string): string;
|
|
2
|
-
export declare function toSafeConstKey(value: string): string;
|
|
3
|
-
export declare function makeUniquePascalNames<T extends {
|
|
4
|
-
id: string;
|
|
5
|
-
name: string;
|
|
6
|
-
}>(items: T[]): Map<string, string>;
|
|
7
|
-
export declare function quotePropertyKey(value: string): string;
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
const NON_IDENTIFIER = /[^a-zA-Z0-9_$]+/g;
|
|
2
|
-
const MULTIPLE_UNDERSCORES = /_+/g;
|
|
3
|
-
function suffixFromId(id) {
|
|
4
|
-
return id.replace(/[^a-zA-Z0-9]/g, '').slice(-6) || 'Id';
|
|
5
|
-
}
|
|
6
|
-
export function toPascalCase(value) {
|
|
7
|
-
const normalized = value
|
|
8
|
-
.replace(NON_IDENTIFIER, ' ')
|
|
9
|
-
.trim()
|
|
10
|
-
.split(/\s+/)
|
|
11
|
-
.filter(Boolean)
|
|
12
|
-
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
13
|
-
.join('');
|
|
14
|
-
if (!normalized)
|
|
15
|
-
return 'Generated';
|
|
16
|
-
if (/^[0-9]/.test(normalized))
|
|
17
|
-
return `T${normalized}`;
|
|
18
|
-
return normalized;
|
|
19
|
-
}
|
|
20
|
-
export function toSafeConstKey(value) {
|
|
21
|
-
const normalized = value
|
|
22
|
-
.replace(NON_IDENTIFIER, '_')
|
|
23
|
-
.replace(MULTIPLE_UNDERSCORES, '_')
|
|
24
|
-
.replace(/^_+|_+$/g, '');
|
|
25
|
-
if (!normalized)
|
|
26
|
-
return 'generated';
|
|
27
|
-
if (/^[0-9]/.test(normalized))
|
|
28
|
-
return `_${normalized}`;
|
|
29
|
-
return normalized;
|
|
30
|
-
}
|
|
31
|
-
export function makeUniquePascalNames(items) {
|
|
32
|
-
const result = new Map();
|
|
33
|
-
const counts = new Map();
|
|
34
|
-
items.forEach((item) => {
|
|
35
|
-
const base = toPascalCase(item.name);
|
|
36
|
-
const count = counts.get(base) ?? 0;
|
|
37
|
-
counts.set(base, count + 1);
|
|
38
|
-
});
|
|
39
|
-
items.forEach((item) => {
|
|
40
|
-
const base = toPascalCase(item.name);
|
|
41
|
-
if ((counts.get(base) ?? 0) === 1) {
|
|
42
|
-
result.set(item.id, base);
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
result.set(item.id, `${base}_${suffixFromId(item.id)}`);
|
|
46
|
-
});
|
|
47
|
-
return result;
|
|
48
|
-
}
|
|
49
|
-
export function quotePropertyKey(value) {
|
|
50
|
-
return JSON.stringify(value);
|
|
51
|
-
}
|
package/lib/codegen/index.d.ts
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
export { buildAirtableTypes } from './build.js';
|
|
2
|
-
export { generateAirtableTypes } from './generate.js';
|
|
3
|
-
export type { AirtableCodegenResult, AirtableSchemaSource, CreateRequiredMode, EnumMode, GenerateAirtableTypesOptions, GenerateAirtableTypesResult, SchemaMode, UnknownFieldBehavior, } from './types.js';
|
package/lib/codegen/index.js
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { readFile } from 'node:fs/promises';
|
|
2
|
-
import { resolve } from 'node:path';
|
|
3
|
-
import { getBaseSchema } from '../bases.js';
|
|
4
|
-
import { isRecord } from './utils.js';
|
|
5
|
-
function isAirtableBaseSchema(value) {
|
|
6
|
-
if (!isRecord(value))
|
|
7
|
-
return false;
|
|
8
|
-
return Array.isArray(value.tables);
|
|
9
|
-
}
|
|
10
|
-
export async function loadSchema(source) {
|
|
11
|
-
if ('schema' in source) {
|
|
12
|
-
return source.schema;
|
|
13
|
-
}
|
|
14
|
-
if ('schemaPath' in source) {
|
|
15
|
-
const filePath = resolve(source.schemaPath);
|
|
16
|
-
const content = await readFile(filePath, 'utf8');
|
|
17
|
-
const parsed = JSON.parse(content);
|
|
18
|
-
if (!isAirtableBaseSchema(parsed)) {
|
|
19
|
-
throw new Error(`Schema file at ${filePath} is not a valid Airtable base schema.`);
|
|
20
|
-
}
|
|
21
|
-
return parsed;
|
|
22
|
-
}
|
|
23
|
-
const token = source.accessToken || source.apiKey;
|
|
24
|
-
if (!token) {
|
|
25
|
-
throw new Error('An Airtable access token is required when loading schema from the Airtable metadata API.');
|
|
26
|
-
}
|
|
27
|
-
return getBaseSchema({ apiKey: token, baseId: source.baseId });
|
|
28
|
-
}
|