easy-airtable-api 0.0.15 → 0.0.17

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.md +402 -130
  3. package/easy-airtable-api-0.0.17.tgz +0 -0
  4. package/lib/bases.d.ts +18 -0
  5. package/lib/bases.js +40 -0
  6. package/lib/cli.d.ts +2 -0
  7. package/lib/cli.js +82 -0
  8. package/lib/codegen/build.d.ts +2 -0
  9. package/lib/codegen/build.js +25 -0
  10. package/lib/codegen/emit-typescript.d.ts +8 -0
  11. package/lib/codegen/emit-typescript.js +104 -0
  12. package/lib/codegen/generate.d.ts +2 -0
  13. package/lib/codegen/generate.js +23 -0
  14. package/lib/codegen/identifiers.d.ts +7 -0
  15. package/lib/codegen/identifiers.js +51 -0
  16. package/lib/codegen/index.d.ts +3 -0
  17. package/lib/codegen/index.js +2 -0
  18. package/lib/codegen/load-schema.d.ts +3 -0
  19. package/lib/codegen/load-schema.js +28 -0
  20. package/lib/codegen/map-field.d.ts +31 -0
  21. package/lib/codegen/map-field.js +278 -0
  22. package/lib/codegen/normalize-schema.d.ts +11 -0
  23. package/lib/codegen/normalize-schema.js +61 -0
  24. package/lib/codegen/types.d.ts +62 -0
  25. package/lib/codegen/types.js +1 -0
  26. package/lib/codegen/utils.d.ts +14 -0
  27. package/lib/codegen/utils.js +30 -0
  28. package/lib/codegen/write-atomic.d.ts +1 -0
  29. package/lib/codegen/write-atomic.js +11 -0
  30. package/lib/index.d.ts +8 -2
  31. package/lib/index.js +3 -2
  32. package/lib/records.d.ts +75 -9
  33. package/lib/records.js +110 -21
  34. package/lib/requests.d.ts +65 -21
  35. package/lib/requests.js +281 -31
  36. package/lib/types/bases.d.ts +8 -40
  37. package/lib/types/fields.d.ts +8 -8
  38. package/lib/types/metadata.d.ts +24 -0
  39. package/lib/types/metadata.js +1 -0
  40. package/lib/types/records.d.ts +1 -1
  41. package/lib/utils.d.ts +2 -2
  42. package/package.json +17 -9
  43. package/lib/generate-types.d.ts +0 -5
  44. package/lib/generate-types.js +0 -78
package/lib/bases.d.ts ADDED
@@ -0,0 +1,18 @@
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 ADDED
@@ -0,0 +1,40 @@
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 ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/lib/cli.js ADDED
@@ -0,0 +1,82 @@
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
+ });
@@ -0,0 +1,2 @@
1
+ import type { AirtableCodegenResult, GenerateAirtableTypesOptions } from './types.js';
2
+ export declare function buildAirtableTypes(options: Omit<GenerateAirtableTypesOptions, 'output'>): Promise<AirtableCodegenResult>;
@@ -0,0 +1,25 @@
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
+ }
@@ -0,0 +1,8 @@
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;
@@ -0,0 +1,104 @@
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
+ }
@@ -0,0 +1,2 @@
1
+ import type { GenerateAirtableTypesOptions, GenerateAirtableTypesResult } from './types.js';
2
+ export declare function generateAirtableTypes(options: GenerateAirtableTypesOptions): Promise<GenerateAirtableTypesResult>;
@@ -0,0 +1,23 @@
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
+ }
@@ -0,0 +1,7 @@
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;
@@ -0,0 +1,51 @@
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
+ }
@@ -0,0 +1,3 @@
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';
@@ -0,0 +1,2 @@
1
+ export { buildAirtableTypes } from './build.js';
2
+ export { generateAirtableTypes } from './generate.js';
@@ -0,0 +1,3 @@
1
+ import type { AirtableBaseSchema } from '../types/metadata.js';
2
+ import type { AirtableSchemaSource } from './types.js';
3
+ export declare function loadSchema(source: AirtableSchemaSource): Promise<AirtableBaseSchema>;
@@ -0,0 +1,28 @@
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
+ }
@@ -0,0 +1,31 @@
1
+ import type { AirtableFieldSchema } from '../types/metadata.js';
2
+ import type { EnumMode, NormalizedField, UnknownFieldBehavior } from './types.js';
3
+ export declare function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }: {
4
+ field: AirtableFieldSchema;
5
+ enumMode: EnumMode;
6
+ unknownFieldBehavior: UnknownFieldBehavior;
7
+ }): {
8
+ read: {
9
+ type: string;
10
+ warning?: string;
11
+ };
12
+ create?: {
13
+ type: string;
14
+ warning?: string;
15
+ };
16
+ update?: {
17
+ type: string;
18
+ warning?: string;
19
+ };
20
+ readonly: boolean;
21
+ computed: boolean;
22
+ linkedTableId?: string;
23
+ enumTypeAlias?: string;
24
+ };
25
+ export declare function mapFieldToNormalizedField({ field, enumMode, unknownFieldBehavior, tsKey, tsTypeName, }: {
26
+ field: AirtableFieldSchema;
27
+ enumMode: EnumMode;
28
+ unknownFieldBehavior: UnknownFieldBehavior;
29
+ tsKey: string;
30
+ tsTypeName: string;
31
+ }): NormalizedField;