easy-airtable-api 0.1.0 → 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 +30 -0
- package/README.md +55 -1
- package/package.json +5 -2
- package/easy-airtable-api-0.1.0.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 -117
- package/lib/codegen/generate.d.ts +0 -2
- package/lib/codegen/generate.js +0 -23
- package/lib/codegen/identifiers.d.ts +0 -11
- package/lib/codegen/identifiers.js +0 -73
- 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 -30
- package/lib/codegen/map-field.js +0 -296
- package/lib/codegen/normalize-schema.d.ts +0 -11
- package/lib/codegen/normalize-schema.js +0 -79
- package/lib/codegen/types.d.ts +0 -64
- 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 -197
- 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 -330
- 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 -130
- 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,35 @@
|
|
|
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
|
+
|
|
3
33
|
## 0.1.0
|
|
4
34
|
|
|
5
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`.
|
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,10 @@ 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
|
+
|
|
192
198
|
### Generated type assumptions
|
|
193
199
|
|
|
194
200
|
Generated read types target Airtable's default JSON response mode:
|
|
@@ -317,17 +323,39 @@ const records = await getRecords({
|
|
|
317
323
|
retry: {
|
|
318
324
|
maxRetries: 2,
|
|
319
325
|
baseDelayMs: 250,
|
|
320
|
-
maxDelayMs:
|
|
326
|
+
maxDelayMs: 30000,
|
|
321
327
|
retryOn429: true,
|
|
322
328
|
retryOn5xx: true,
|
|
323
329
|
retryOnNetworkErrors: true,
|
|
324
330
|
useJitter: false,
|
|
331
|
+
timeoutMs: 60000,
|
|
325
332
|
},
|
|
326
333
|
});
|
|
327
334
|
```
|
|
328
335
|
|
|
329
336
|
The same `retry` option is supported by metadata helpers such as `listBases()` / `getBaseSchema()` and by `airtableRequestRaw()`.
|
|
330
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
|
+
|
|
331
359
|
## Runtime examples
|
|
332
360
|
|
|
333
361
|
### Get a single record
|
|
@@ -480,12 +508,38 @@ await deleteRecords({
|
|
|
480
508
|
});
|
|
481
509
|
```
|
|
482
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
|
+
|
|
483
536
|
## Exports
|
|
484
537
|
|
|
485
538
|
Runtime package:
|
|
486
539
|
|
|
487
540
|
```ts
|
|
488
541
|
import {
|
|
542
|
+
AirtableBatchError,
|
|
489
543
|
airtableRequestRaw,
|
|
490
544
|
createBase,
|
|
491
545
|
createRecord,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "easy-airtable-api",
|
|
3
|
-
"version": "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,
|
|
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,117 +0,0 @@
|
|
|
1
|
-
import { quotePropertyKey } from './identifiers.js';
|
|
2
|
-
function isPrimaryCreateField(field, primaryFieldId, createRequiredMode) {
|
|
3
|
-
return (createRequiredMode === 'primaryField' &&
|
|
4
|
-
field.id === primaryFieldId &&
|
|
5
|
-
Boolean(field.createType));
|
|
6
|
-
}
|
|
7
|
-
function getFieldTypeForKind(field, kind) {
|
|
8
|
-
if (kind === 'read')
|
|
9
|
-
return field.readType;
|
|
10
|
-
if (kind === 'create')
|
|
11
|
-
return field.createType;
|
|
12
|
-
return field.updateType;
|
|
13
|
-
}
|
|
14
|
-
function groupFieldsByPropertyKey(fields, kind) {
|
|
15
|
-
const groups = new Map();
|
|
16
|
-
fields.forEach((field) => {
|
|
17
|
-
const type = getFieldTypeForKind(field, kind);
|
|
18
|
-
if (!type)
|
|
19
|
-
return;
|
|
20
|
-
const existing = groups.get(field.tsKey);
|
|
21
|
-
if (existing) {
|
|
22
|
-
existing.push(field);
|
|
23
|
-
return;
|
|
24
|
-
}
|
|
25
|
-
groups.set(field.tsKey, [field]);
|
|
26
|
-
});
|
|
27
|
-
return [...groups.entries()].map(([key, groupedFields]) => ({
|
|
28
|
-
key,
|
|
29
|
-
fields: groupedFields,
|
|
30
|
-
}));
|
|
31
|
-
}
|
|
32
|
-
function unionTypes(types) {
|
|
33
|
-
const distinctTypes = [...new Set(types)];
|
|
34
|
-
return distinctTypes.join(' | ');
|
|
35
|
-
}
|
|
36
|
-
function emitInterface({ name, fields, kind, primaryFieldId, createRequiredMode, }) {
|
|
37
|
-
const groupedFields = groupFieldsByPropertyKey(fields, kind);
|
|
38
|
-
const lines = groupedFields.map(({ key, fields: grouped }) => {
|
|
39
|
-
const propertyTypes = grouped
|
|
40
|
-
.map((field) => getFieldTypeForKind(field, kind))
|
|
41
|
-
.filter((type) => Boolean(type));
|
|
42
|
-
const propertyType = unionTypes(propertyTypes);
|
|
43
|
-
const isRequired = kind === 'create' &&
|
|
44
|
-
grouped.some((field) => isPrimaryCreateField(field, primaryFieldId, createRequiredMode));
|
|
45
|
-
return ` ${quotePropertyKey(key)}${isRequired ? '' : '?'}: ${propertyType};`;
|
|
46
|
-
});
|
|
47
|
-
if (!lines.length) {
|
|
48
|
-
return `export interface ${name} {}`;
|
|
49
|
-
}
|
|
50
|
-
return [`export interface ${name} {`, ...lines, `}`].join('\n');
|
|
51
|
-
}
|
|
52
|
-
function emitEnumAliases(table) {
|
|
53
|
-
return table.fields
|
|
54
|
-
.filter((field) => Boolean(field.enumTypeAlias))
|
|
55
|
-
.map((field) => `export type ${field.tsTypeName} = ${field.enumTypeAlias};`);
|
|
56
|
-
}
|
|
57
|
-
function emitTableIds(normalizedBase) {
|
|
58
|
-
const lines = normalizedBase.tables.map((table) => ` ${table.tsConstKey}: ${JSON.stringify(table.id)},`);
|
|
59
|
-
return ['export const tables = {', ...lines, '} as const;'].join('\n');
|
|
60
|
-
}
|
|
61
|
-
function emitFieldIds(normalizedBase) {
|
|
62
|
-
const lines = normalizedBase.tables.map((table) => {
|
|
63
|
-
const fieldLines = table.fields.map((field) => ` ${field.tsConstKey}: ${JSON.stringify(field.id)},`);
|
|
64
|
-
return [` ${table.tsConstKey}: {`, ...fieldLines, ' },'].join('\n');
|
|
65
|
-
});
|
|
66
|
-
return ['export const fields = {', ...lines, '} as const;'].join('\n');
|
|
67
|
-
}
|
|
68
|
-
export function emitTypeScript({ normalizedBase, includeTableIds, includeFieldIds, schemaMode, createRequiredMode, }) {
|
|
69
|
-
const sections = [
|
|
70
|
-
'/* eslint-disable */',
|
|
71
|
-
'// Generated by easy-airtable-api. Do not edit manually.',
|
|
72
|
-
"// Generated record-field types assume Airtable's default response mode: cellFormat: 'json' and returnFieldsByFieldId: false.",
|
|
73
|
-
'',
|
|
74
|
-
"import type { AICell, AirtableRecord, Attachment, AttachmentWrite, BarcodeCell, BarcodeWrite, ButtonCell, Collaborator, CollaboratorWrite } from 'easy-airtable-api';",
|
|
75
|
-
];
|
|
76
|
-
if (includeTableIds) {
|
|
77
|
-
sections.push('', emitTableIds(normalizedBase));
|
|
78
|
-
}
|
|
79
|
-
if (includeFieldIds) {
|
|
80
|
-
sections.push('', emitFieldIds(normalizedBase));
|
|
81
|
-
}
|
|
82
|
-
normalizedBase.tables.forEach((table) => {
|
|
83
|
-
sections.push('');
|
|
84
|
-
sections.push(`// ${table.name} (${table.id})`);
|
|
85
|
-
const enumAliases = emitEnumAliases(table);
|
|
86
|
-
if (enumAliases.length) {
|
|
87
|
-
sections.push(...enumAliases, '');
|
|
88
|
-
}
|
|
89
|
-
if (schemaMode === 'read' || schemaMode === 'full') {
|
|
90
|
-
sections.push(emitInterface({
|
|
91
|
-
name: `${table.tsName}RecordFields`,
|
|
92
|
-
fields: table.fields,
|
|
93
|
-
kind: 'read',
|
|
94
|
-
primaryFieldId: table.primaryFieldId,
|
|
95
|
-
createRequiredMode,
|
|
96
|
-
}));
|
|
97
|
-
sections.push(`export type ${table.tsName}Record = AirtableRecord<${table.tsName}RecordFields>;`);
|
|
98
|
-
}
|
|
99
|
-
if (schemaMode === 'write' || schemaMode === 'full') {
|
|
100
|
-
sections.push(emitInterface({
|
|
101
|
-
name: `${table.tsName}CreateFields`,
|
|
102
|
-
fields: table.fields,
|
|
103
|
-
kind: 'create',
|
|
104
|
-
primaryFieldId: table.primaryFieldId,
|
|
105
|
-
createRequiredMode,
|
|
106
|
-
}));
|
|
107
|
-
sections.push(emitInterface({
|
|
108
|
-
name: `${table.tsName}UpdateFields`,
|
|
109
|
-
fields: table.fields,
|
|
110
|
-
kind: 'update',
|
|
111
|
-
primaryFieldId: table.primaryFieldId,
|
|
112
|
-
createRequiredMode,
|
|
113
|
-
}));
|
|
114
|
-
}
|
|
115
|
-
});
|
|
116
|
-
return `${sections.join('\n')}\n`;
|
|
117
|
-
}
|
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,11 +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 makeUniqueConstKeys<T extends {
|
|
8
|
-
id: string;
|
|
9
|
-
name: string;
|
|
10
|
-
}>(items: T[]): Map<string, string>;
|
|
11
|
-
export declare function quotePropertyKey(value: string): string;
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
const NON_IDENTIFIER = /[^a-zA-Z0-9_$]+/g;
|
|
2
|
-
const MULTIPLE_UNDERSCORES = /_+/g;
|
|
3
|
-
const COMBINING_MARKS = /[\u0300-\u036f]/g;
|
|
4
|
-
function normalizeIdentifierInput(value) {
|
|
5
|
-
return value.normalize('NFKD').replace(COMBINING_MARKS, '');
|
|
6
|
-
}
|
|
7
|
-
function suffixFromId(id) {
|
|
8
|
-
return id.replace(/[^a-zA-Z0-9]/g, '').slice(-6) || 'Id';
|
|
9
|
-
}
|
|
10
|
-
export function toPascalCase(value) {
|
|
11
|
-
const normalized = normalizeIdentifierInput(value)
|
|
12
|
-
.replace(NON_IDENTIFIER, ' ')
|
|
13
|
-
.trim()
|
|
14
|
-
.split(/\s+/)
|
|
15
|
-
.filter(Boolean)
|
|
16
|
-
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
17
|
-
.join('');
|
|
18
|
-
if (!normalized)
|
|
19
|
-
return 'Generated';
|
|
20
|
-
if (/^[0-9]/.test(normalized))
|
|
21
|
-
return `T${normalized}`;
|
|
22
|
-
return normalized;
|
|
23
|
-
}
|
|
24
|
-
export function toSafeConstKey(value) {
|
|
25
|
-
const normalized = normalizeIdentifierInput(value)
|
|
26
|
-
.replace(NON_IDENTIFIER, '_')
|
|
27
|
-
.replace(MULTIPLE_UNDERSCORES, '_')
|
|
28
|
-
.replace(/^_+|_+$/g, '');
|
|
29
|
-
if (!normalized)
|
|
30
|
-
return 'generated';
|
|
31
|
-
if (/^[0-9]/.test(normalized))
|
|
32
|
-
return `_${normalized}`;
|
|
33
|
-
return normalized;
|
|
34
|
-
}
|
|
35
|
-
export function makeUniquePascalNames(items) {
|
|
36
|
-
const result = new Map();
|
|
37
|
-
const counts = new Map();
|
|
38
|
-
items.forEach((item) => {
|
|
39
|
-
const base = toPascalCase(item.name);
|
|
40
|
-
const count = counts.get(base) ?? 0;
|
|
41
|
-
counts.set(base, count + 1);
|
|
42
|
-
});
|
|
43
|
-
items.forEach((item) => {
|
|
44
|
-
const base = toPascalCase(item.name);
|
|
45
|
-
if ((counts.get(base) ?? 0) === 1) {
|
|
46
|
-
result.set(item.id, base);
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
result.set(item.id, `${base}_${suffixFromId(item.id)}`);
|
|
50
|
-
});
|
|
51
|
-
return result;
|
|
52
|
-
}
|
|
53
|
-
export function makeUniqueConstKeys(items) {
|
|
54
|
-
const result = new Map();
|
|
55
|
-
const counts = new Map();
|
|
56
|
-
items.forEach((item) => {
|
|
57
|
-
const base = toSafeConstKey(item.name);
|
|
58
|
-
const count = counts.get(base) ?? 0;
|
|
59
|
-
counts.set(base, count + 1);
|
|
60
|
-
});
|
|
61
|
-
items.forEach((item) => {
|
|
62
|
-
const base = toSafeConstKey(item.name);
|
|
63
|
-
if ((counts.get(base) ?? 0) === 1) {
|
|
64
|
-
result.set(item.id, base);
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
result.set(item.id, `${base}_${suffixFromId(item.id)}`);
|
|
68
|
-
});
|
|
69
|
-
return result;
|
|
70
|
-
}
|
|
71
|
-
export function quotePropertyKey(value) {
|
|
72
|
-
return JSON.stringify(value);
|
|
73
|
-
}
|
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
|
-
}
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import type { AirtableFieldSchema } from '../types/metadata.js';
|
|
2
|
-
import type { EnumMode, NormalizedField, UnknownFieldBehavior } from './types.js';
|
|
3
|
-
type CollectionKind = 'scalar' | 'array';
|
|
4
|
-
type MappedFieldType = {
|
|
5
|
-
type: string;
|
|
6
|
-
warning?: string;
|
|
7
|
-
collection: CollectionKind;
|
|
8
|
-
};
|
|
9
|
-
export declare function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }: {
|
|
10
|
-
field: AirtableFieldSchema;
|
|
11
|
-
enumMode: EnumMode;
|
|
12
|
-
unknownFieldBehavior: UnknownFieldBehavior;
|
|
13
|
-
}): {
|
|
14
|
-
read: MappedFieldType;
|
|
15
|
-
create?: MappedFieldType;
|
|
16
|
-
update?: MappedFieldType;
|
|
17
|
-
readonly: boolean;
|
|
18
|
-
computed: boolean;
|
|
19
|
-
linkedTableId?: string;
|
|
20
|
-
enumTypeAlias?: string;
|
|
21
|
-
};
|
|
22
|
-
export declare function mapFieldToNormalizedField({ field, enumMode, unknownFieldBehavior, tsKey, tsConstKey, tsTypeName, }: {
|
|
23
|
-
field: AirtableFieldSchema;
|
|
24
|
-
enumMode: EnumMode;
|
|
25
|
-
unknownFieldBehavior: UnknownFieldBehavior;
|
|
26
|
-
tsKey: string;
|
|
27
|
-
tsConstKey: string;
|
|
28
|
-
tsTypeName: string;
|
|
29
|
-
}): NormalizedField;
|
|
30
|
-
export {};
|