@atproto/lex-builder 0.0.9 → 0.0.10

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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # @atproto/lex-builder
2
2
 
3
+ ## 0.0.10
4
+
5
+ ### Patch Changes
6
+
7
+ - [#4512](https://github.com/bluesky-social/atproto/pull/4512) [`d78484f`](https://github.com/bluesky-social/atproto/commit/d78484f94d8ba1352ec66030115000d515c9dafe) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Improve naming of exported types
8
+
9
+ - Updated dependencies [[`d78484f`](https://github.com/bluesky-social/atproto/commit/d78484f94d8ba1352ec66030115000d515c9dafe), [`d78484f`](https://github.com/bluesky-social/atproto/commit/d78484f94d8ba1352ec66030115000d515c9dafe)]:
10
+ - @atproto/lex-schema@0.0.8
11
+ - @atproto/lex-document@0.0.9
12
+
3
13
  ## 0.0.9
4
14
 
5
15
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"lex-def-builder.d.ts","sourceRoot":"","sources":["../src/lex-def-builder.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,UAAU,EAEX,MAAM,UAAU,CAAA;AACjB,OAAO,EAOL,eAAe,EAEf,cAAc,EAMd,gBAAgB,EAChB,YAAY,EAKZ,mBAAmB,EAGpB,MAAM,uBAAuB,CAAA;AAE9B,OAAO,EAEL,kBAAkB,EAClB,WAAW,EAEZ,MAAM,mBAAmB,CAAA;AAG1B,MAAM,MAAM,oBAAoB,GAAG,kBAAkB,GAAG;IACtD,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B,CAAA;AAED;;GAEG;AACH,qBAAa,aAAa;IAItB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAA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oBAAoB;YAIpB,kBAAkB;YAIlB,gBAAgB;YAOhB,cAAc;YAKd,qBAAqB;YAmBrB,mBAAmB;YAWnB,kBAAkB;YAalB,gBAAgB;YAShB,iBAAiB;YAgBjB,eAAe;CAK9B"}
@@ -1,8 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LexDefBuilder = void 0;
4
- const tslib_1 = require("tslib");
5
- const node_assert_1 = tslib_1.__importDefault(require("node:assert"));
6
4
  const ts_morph_1 = require("ts-morph");
7
5
  const lex_schema_1 = require("@atproto/lex-schema");
8
6
  const ref_resolver_js_1 = require("./ref-resolver.js");
@@ -267,10 +265,6 @@ class LexDefBuilder {
267
265
  async addSchema(hash, def, { type, schema, objectUtils, validationUtils, }) {
268
266
  const ref = await this.refResolver.resolveLocal(hash);
269
267
  const pub = (0, ref_resolver_js_1.getPublicIdentifiers)(hash);
270
- // Fool-proofing
271
- (0, node_assert_1.default)((0, ts_lang_js_1.isSafeIdentifier)(ref.varName), 'Expected safe type identifier');
272
- (0, node_assert_1.default)((0, ts_lang_js_1.isSafeIdentifier)(ref.typeName), 'Expected safe type identifier');
273
- (0, node_assert_1.default)((0, ts_lang_js_1.isSafeIdentifier)(pub.typeName), 'Expected safe type identifier');
274
268
  if (type) {
275
269
  this.file.addTypeAlias({
276
270
  name: ref.typeName,
@@ -282,7 +276,9 @@ class LexDefBuilder {
282
276
  namedExports: [
283
277
  {
284
278
  name: ref.typeName,
285
- alias: ref.typeName === pub.typeName ? undefined : pub.typeName,
279
+ alias: ref.typeName === pub.typeName
280
+ ? undefined
281
+ : (0, ts_lang_js_1.asNamespaceExport)(pub.typeName),
286
282
  },
287
283
  ],
288
284
  });
@@ -304,9 +300,7 @@ class LexDefBuilder {
304
300
  name: ref.varName,
305
301
  alias: ref.varName === pub.varName
306
302
  ? undefined
307
- : (0, ts_lang_js_1.isSafeIdentifier)(pub.varName)
308
- ? pub.varName
309
- : JSON.stringify(pub.varName),
303
+ : (0, ts_lang_js_1.asNamespaceExport)(pub.varName),
310
304
  },
311
305
  ],
312
306
  });
@@ -1 +1 @@
1
- {"version":3,"file":"lex-def-builder.js","sourceRoot":"","sources":["../src/lex-def-builder.ts"],"names":[],"mappings":";;;;AAAA,sEAAgC;AAChC,uCAKiB;AA0BjB,oDAAuC;AACvC,uDAK0B;AAC1B,6CAA+C;AAQ/C;;GAEG;AACH,MAAa,aAAa;IAIL;IACA;IACA;IALF,WAAW,CAAa;IAEzC,YACmB,OAA6B,EAC7B,IAAgB,EAChB,GAAoB,EACrC,OAAuB;QAHN,YAAO,GAAP,OAAO,CAAsB;QAC7B,SAAI,GAAJ,IAAI,CAAY;QAChB,QAAG,GAAH,GAAG,CAAiB;QAGrC,IAAI,CAAC,WAAW,GAAG,IAAI,6BAAW,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;IACjE,CAAC;IAEO,IAAI,CAAC,IAAY;QACvB,OAAO,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IAC7D,CAAC;IAED,KAAK,CAAC,KAAK;QACT,IAAI,CAAC,IAAI,CAAC,oBAAoB,CAAC;YAC7B,eAAe,EAAE,kCAAuB,CAAC,KAAK;YAC9C,YAAY,EAAE;gBACZ,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;aAC5D;SACF,CAAC,CAAA;QAEF,IAAI,CAAC,IAAI,CAAC,oBAAoB,CAAC;YAC7B,YAAY,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;SAClC,CAAC,CAAA;QAEF,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACvC,IAAI,IAAI,CAAC,M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C;AAED,SAAS,QAAQ,CACf,GAAM;IAEN,OAAO,GAAG,CAAC,KAAK,IAAI,IAAI,CAAA;AAC1B,CAAC;AAED,SAAS,OAAO,CACd,GAAM;IAEN,OAAO,GAAG,CAAC,IAAI,IAAI,IAAI,CAAA;AACzB,CAAC;AAED,SAAS,QAAQ,CAAmB,CAAI;IACtC,OAAO,iBAAiB,CAAC,EAAE,CAAA;AAC7B,CAAC","sourcesContent":["import assert from 'node:assert'\nimport {\n JSDocStructure,\n OptionalKind,\n SourceFile,\n VariableDeclarationKind,\n} from 'ts-morph'\nimport {\n LexiconArray,\n LexiconArrayItems,\n LexiconBlob,\n LexiconBoolean,\n LexiconBytes,\n LexiconCid,\n LexiconDocument,\n LexiconError,\n LexiconIndexer,\n LexiconInteger,\n LexiconObject,\n LexiconParameters,\n LexiconPayload,\n LexiconPermissionSet,\n LexiconProcedure,\n LexiconQuery,\n LexiconRecord,\n LexiconRef,\n LexiconRefUnion,\n LexiconString,\n LexiconSubscription,\n LexiconToken,\n LexiconUnknown,\n} from '@atproto/lex-document'\nimport { l } from '@atproto/lex-schema'\nimport {\n RefResolver,\n RefResolverOptions,\n ResolvedRef,\n getPublicIdentifiers,\n} from './ref-resolver.js'\nimport { isSafeIdentifier } from './ts-lang.js'\n\nexport type LexDefBuilderOptions = RefResolverOptions & {\n lib?: string\n allowLegacyBlobs?: boolean\n pureAnnotations?: boolean\n}\n\n/**\n * Utility class to build a TypeScript source file from a lexicon document.\n */\nexport class LexDefBuilder {\n private readonly refResolver: RefResolver\n\n constructor(\n private readonly options: LexDefBuilderOptions,\n private readonly file: SourceFile,\n private readonly doc: LexiconDocument,\n indexer: LexiconIndexer,\n ) {\n this.refResolver = new RefResolver(doc, file, indexer, options)\n }\n\n private pure(code: string) {\n return this.options.pureAnnotations ? markPure(code) : code\n }\n\n async build() {\n this.file.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n declarations: [\n { name: '$nsid', initializer: JSON.stringify(this.doc.id) },\n ],\n })\n\n this.file.addExportDeclaration({\n namedExports: [{ name: '$nsid' }],\n })\n\n const defs = Object.keys(this.doc.defs)\n if (defs.length) {\n const moduleSpecifier = this.options?.lib ?? '@atproto/lex-schema'\n this.file\n .addImportDeclaration({ moduleSpecifier })\n .addNamedImports([{ name: 'l' }])\n\n for (const hash of defs) {\n await this.addDef(hash)\n }\n }\n }\n\n private addUtils(definitions: Record<string, undefined | string>) {\n const entries = Object.entries(definitions).filter(\n (e): e is [(typeof e)[0], NonNullable<(typeof e)[1]>] => e[1] != null,\n )\n if (entries.length) {\n this.file.addVariableStatement({\n isExported: true,\n declarationKind: VariableDeclarationKind.Const,\n declarations: entries.map(([name, initializer]) => ({\n name,\n initializer,\n })),\n })\n }\n }\n\n private async addDef(hash: string) {\n const def = Object.hasOwn(this.doc.defs, hash) ? this.doc.defs[hash] : null\n if (def == null) return\n\n switch (def.type) {\n case 'permission-set':\n return this.addPermissionSet(hash, def)\n case 'procedure':\n return this.addProcedure(hash, def)\n case 'query':\n return this.addQuery(hash, def)\n case 'subscription':\n return this.addSubscription(hash, def)\n case 'record':\n return this.addRecord(hash, def)\n case 'token':\n return this.addToken(hash, def)\n case 'object':\n return this.addObject(hash, def)\n case 'array':\n return this.addArray(hash, def)\n default:\n await this.addSchema(hash, def, {\n type: await this.compileContainedType(def),\n schema: await this.compileContainedSchema(def),\n validationUtils: true,\n })\n }\n }\n\n private async addPermissionSet(hash: string, def: LexiconPermissionSet) {\n const permission = def.permissions.map((def) => {\n const options = stringifyOptions(def, undefined, ['resource', 'type'])\n return this.pure(\n `l.permission(${JSON.stringify(def.resource)}, ${options})`,\n )\n })\n\n const options = stringifyOptions(def, [\n 'title',\n 'title:lang',\n 'detail',\n 'detail:lang',\n ] satisfies (keyof l.PermissionSetOptions)[])\n\n await this.addSchema(hash, def, {\n schema: this.pure(\n `l.permissionSet($nsid, [${permission.join(',')}], ${options})`,\n ),\n })\n }\n\n private async addProcedure(hash: string, def: LexiconProcedure) {\n if (hash !== 'main') {\n throw new Error(`Definition ${hash} cannot be of type ${def.type}`)\n }\n\n // @TODO Build the types instead of using an inferred type.\n\n const ref = await this.addSchema(hash, def, {\n schema: this.pure(`\n l.procedure(\n $nsid,\n ${await this.compileParamsSchema(def.parameters)},\n ${await this.compilePayload(def.input)},\n ${await this.compilePayload(def.output)},\n ${await this.compileErrors(def.errors)}\n )\n `),\n })\n\n this.addMethodTypeUtils(ref, def)\n this.addUtils({\n $lxm: this.pure(`${ref.varName}.nsid`),\n $params: this.pure(`${ref.varName}.parameters`),\n $input: this.pure(`${ref.varName}.input`),\n $output: this.pure(`${ref.varName}.output`),\n })\n }\n\n private async addQuery(hash: string, def: LexiconQuery) {\n if (hash !== 'main') {\n throw new Error(`Definition ${hash} cannot be of type ${def.type}`)\n }\n\n // @TODO Build the types instead of using an inferred type.\n\n const ref = await this.addSchema(hash, def, {\n schema: this.pure(`\n l.query(\n $nsid,\n ${await this.compileParamsSchema(def.parameters)},\n ${await this.compilePayload(def.output)},\n ${await this.compileErrors(def.errors)}\n )\n `),\n })\n\n this.addMethodTypeUtils(ref, def)\n this.addUtils({\n $lxm: this.pure(`${ref.varName}.nsid`),\n $params: `${ref.varName}.parameters`,\n $output: `${ref.varName}.output`,\n })\n }\n\n private async addSubscription(hash: string, def: LexiconSubscription) {\n if (hash !== 'main') {\n throw new Error(`Definition ${hash} cannot be of type ${def.type}`)\n }\n\n // @TODO Build the types instead of using an inferred type.\n\n const ref = await this.addSchema(hash, def, {\n schema: this.pure(`\n l.subscription(\n $nsid,\n ${await this.compileParamsSchema(def.parameters)},\n ${await this.compileBodySchema(def.message?.schema)},\n ${await this.compileErrors(def.errors)}\n )\n `),\n })\n\n this.addMethodTypeUtils(ref, def)\n this.addUtils({\n $lxm: this.pure(`${ref.varName}.nsid`),\n $params: `${ref.varName}.parameters`,\n $message: `${ref.varName}.message`,\n })\n }\n\n addMethodTypeUtils(\n ref: ResolvedRef,\n def: LexiconProcedure | LexiconQuery | LexiconSubscription,\n ) {\n this.file.addTypeAlias({\n isExported: true,\n name: 'Params',\n type: `l.InferMethodParams<typeof ${ref.varName}>`,\n docs: compileDocs(def.parameters?.description),\n })\n\n if (def.type === 'procedure') {\n this.file.addTypeAlias({\n isExported: true,\n name: 'Input',\n type: `l.InferMethodInput<typeof ${ref.varName}>`,\n docs: compileDocs(def.input?.description),\n })\n\n this.file.addTypeAlias({\n isExported: true,\n name: 'InputBody',\n type: `l.InferMethodInputBody<typeof ${ref.varName}>`,\n docs: compileDocs(def.input?.description),\n })\n }\n\n if (def.type === 'procedure' || def.type === 'query') {\n this.file.addTypeAlias({\n isExported: true,\n name: 'Output',\n type: `l.InferMethodOutput<typeof ${ref.varName}>`,\n docs: compileDocs(def.output?.description),\n })\n\n this.file.addTypeAlias({\n isExported: true,\n name: 'OutputBody',\n type: `l.InferMethodOutputBody<typeof ${ref.varName}>`,\n docs: compileDocs(def.output?.description),\n })\n }\n\n if (def.type === 'subscription') {\n this.file.addTypeAlias({\n isExported: true,\n name: 'Message',\n type: `l.InferSubscriptionMessage<typeof ${ref.varName}>`,\n docs: compileDocs(def.message?.description),\n })\n }\n }\n\n private async addRecord(hash: string, def: LexiconRecord) {\n if (hash !== 'main') {\n throw new Error(`Definition ${hash} cannot be of type ${def.type}`)\n }\n\n const key = JSON.stringify(def.key ?? 'any')\n const objectSchema = await this.compileObjectSchema(def.record)\n\n const properties = await this.compilePropertiesTypes(def.record)\n properties.unshift(`$type: ${JSON.stringify(l.$type(this.doc.id, hash))}`)\n\n await this.addSchema(hash, def, {\n type: `{ ${properties.join(';')} }`,\n schema: (ref) =>\n this.pure(\n `l.record<${key}, ${ref.typeName}>(${key}, $nsid, ${objectSchema})`,\n ),\n objectUtils: true,\n validationUtils: true,\n })\n }\n\n private async addObject(hash: string, def: LexiconObject) {\n const objectSchema = await this.compileObjectSchema(def)\n\n const properties = await this.compilePropertiesTypes(def)\n properties.unshift(`$type?: ${JSON.stringify(l.$type(this.doc.id, hash))}`)\n\n await this.addSchema(hash, def, {\n type: `{ ${properties.join(';')} }`,\n schema: (ref) =>\n this.pure(\n `l.typedObject<${ref.typeName}>($nsid, ${JSON.stringify(hash)}, ${objectSchema})`,\n ),\n objectUtils: true,\n validationUtils: true,\n })\n }\n\n private async addToken(hash: string, def: LexiconToken) {\n await this.addSchema(hash, def, {\n schema: this.pure(`l.token($nsid, ${JSON.stringify(hash)})`),\n type: JSON.stringify(l.$type(this.doc.id, hash)),\n validationUtils: true,\n })\n }\n\n private async addArray(hash: string, def: LexiconArray) {\n // @TODO It could be nice to expose the array item type as a separate type.\n // This was not done (yet) as there is no easy way to name it to avoid\n // collisions.\n\n const itemSchema = await this.compileContainedSchema(def.items)\n const options = stringifyOptions(def, [\n 'minLength',\n 'maxLength',\n ] satisfies (keyof l.ArraySchemaOptions)[])\n\n await this.addSchema(hash, def, {\n type: `(${await this.compileContainedType(def.items)})[]`,\n // @NOTE Not using compileArraySchema to allow specifying the generic\n // parameter to l.array<>.\n schema: (ref) =>\n this.pure(\n `l.array<${ref.typeName}[number]>(${itemSchema}, ${options})`,\n ),\n validationUtils: true,\n })\n }\n\n private async addSchema(\n hash: string,\n def: { description?: string },\n {\n type,\n schema,\n objectUtils,\n validationUtils,\n }: {\n type?: string | ((ref: ResolvedRef) => string)\n schema?: string | ((ref: ResolvedRef) => string)\n objectUtils?: boolean\n validationUtils?: boolean\n },\n ): Promise<ResolvedRef> {\n const ref = await this.refResolver.resolveLocal(hash)\n const pub = getPublicIdentifiers(hash)\n\n // Fool-proofing\n assert(isSafeIdentifier(ref.varName), 'Expected safe type identifier')\n assert(isSafeIdentifier(ref.typeName), 'Expected safe type identifier')\n assert(isSafeIdentifier(pub.typeName), 'Expected safe type identifier')\n\n if (type) {\n this.file.addTypeAlias({\n name: ref.typeName,\n type: typeof type === 'function' ? type(ref) : type,\n docs: compileDocs(def.description),\n })\n\n this.file.addExportDeclaration({\n isTypeOnly: true,\n namedExports: [\n {\n name: ref.typeName,\n alias: ref.typeName === pub.typeName ? undefined : pub.typeName,\n },\n ],\n })\n }\n\n if (schema) {\n this.file.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n declarations: [\n {\n name: ref.varName,\n initializer: typeof schema === 'function' ? schema(ref) : schema,\n },\n ],\n docs: compileDocs(def.description),\n })\n\n this.file.addExportDeclaration({\n namedExports: [\n {\n name: ref.varName,\n alias:\n ref.varName === pub.varName\n ? undefined\n : isSafeIdentifier(pub.varName)\n ? pub.varName\n : JSON.stringify(pub.varName),\n },\n ],\n })\n }\n\n if (hash === 'main' && objectUtils) {\n this.addUtils({\n $isTypeOf: markPure(`${ref.varName}.isTypeOf.bind(${ref.varName})`),\n $build: markPure(`${ref.varName}.build.bind(${ref.varName})`),\n $type: markPure(`${ref.varName}.$type`),\n })\n }\n\n if (hash === 'main' && validationUtils) {\n this.addUtils({\n $assert: markPure(`${ref.varName}.assert.bind(${ref.varName})`),\n $ifMatches: markPure(`${ref.varName}.ifMatches.bind(${ref.varName})`),\n $matches: markPure(`${ref.varName}.matches.bind(${ref.varName})`),\n $parse: markPure(`${ref.varName}.parse.bind(${ref.varName})`),\n $safeParse: markPure(`${ref.varName}.safeParse.bind(${ref.varName})`),\n })\n }\n\n return ref\n }\n\n private async compilePayload(def: LexiconPayload | undefined) {\n if (!def) return this.pure(`l.payload()`)\n\n // Special case for JSON object payloads\n if (def.encoding === 'application/json' && def.schema?.type === 'object') {\n const properties = await this.compilePropertiesSchemas(def.schema)\n return this.pure(`l.jsonPayload({${properties.join(',')}})`)\n }\n\n const encodedEncoding = JSON.stringify(def.encoding)\n if (def.schema) {\n const bodySchema = await this.compileBodySchema(def.schema)\n return this.pure(`l.payload(${encodedEncoding}, ${bodySchema})`)\n } else {\n return this.pure(`l.payload(${encodedEncoding})`)\n }\n }\n\n private async compileBodySchema(\n def?: LexiconRef | LexiconRefUnion | LexiconObject,\n ): Promise<string> {\n if (!def) return 'undefined'\n if (def.type === 'object') return this.compileObjectSchema(def)\n return this.compileContainedSchema(def)\n }\n\n private async compileParamsSchema(def: undefined | LexiconParameters) {\n if (!def) return this.pure(`l.params()`)\n\n const properties = await this.compilePropertiesSchemas(def)\n return this.pure(`l.params({${properties.join(',')}})`)\n }\n\n private async compileErrors(defs?: readonly LexiconError[]) {\n if (!defs?.length) return ''\n return JSON.stringify(defs.map((d) => d.name))\n }\n\n private async compileObjectSchema(def: LexiconObject): Promise<string> {\n const properties = await this.compilePropertiesSchemas(def)\n return this.pure(`l.object({${properties.join(',')}})`)\n }\n\n private async compilePropertiesSchemas(options: {\n properties: Record<string, LexiconArray | LexiconArrayItems>\n required?: readonly string[]\n nullable?: readonly string[]\n }): Promise<string[]> {\n for (const opt of ['required', 'nullable'] as const) {\n if (options[opt]) {\n for (const prop of options[opt]) {\n if (!Object.hasOwn(options.properties, prop)) {\n throw new Error(`No schema found for ${opt} property \"${prop}\"`)\n }\n }\n }\n }\n\n return Promise.all(\n Object.entries(options.properties).map((entry) => {\n return this.compilePropertyEntrySchema(entry, options)\n }),\n )\n }\n\n private async compilePropertiesTypes(options: {\n properties: Record<string, LexiconArray | LexiconArrayItems>\n required?: readonly string[]\n nullable?: readonly string[]\n }) {\n return Promise.all(\n Object.entries(options.properties).map((entry) => {\n return this.compilePropertyEntryType(entry, options)\n }),\n )\n }\n\n private async compilePropertyEntrySchema(\n [key, def]: [string, LexiconArray | LexiconArrayItems],\n options: {\n required?: readonly string[]\n nullable?: readonly string[]\n },\n ) {\n const isNullable = options.nullable?.includes(key)\n const isRequired = options.required?.includes(key)\n\n let schema = await this.compileContainedSchema(def)\n\n if (isNullable) {\n schema = this.pure(`l.nullable(${schema})`)\n }\n\n if (!isRequired) {\n schema = this.pure(`l.optional(${schema})`)\n }\n\n return `${JSON.stringify(key)}:${schema}`\n }\n\n private async compilePropertyEntryType(\n [key, def]: [string, LexiconArray | LexiconArrayItems],\n options: {\n required?: readonly string[]\n nullable?: readonly string[]\n },\n ) {\n const isNullable = options.nullable?.includes(key)\n const isRequired = options.required?.includes(key)\n\n const optional = isRequired ? '' : '?'\n const append = isNullable ? ' | null' : ''\n\n const jsDoc = compileLeadingTrivia(def.description) || ''\n const name = JSON.stringify(key)\n const type = await this.compileContainedType(def)\n\n return `${jsDoc}${name}${optional}:${type}${append}`\n }\n\n private async compileContainedSchema(\n def: LexiconArray | LexiconArrayItems,\n ): Promise<string> {\n switch (def.type) {\n case 'unknown':\n return this.compileUnknownSchema(def)\n case 'boolean':\n return this.compileBooleanSchema(def)\n case 'integer':\n return this.compileIntegerSchema(def)\n case 'string':\n return this.compileStringSchema(def)\n case 'bytes':\n return this.compileBytesSchema(def)\n case 'blob':\n return this.compileBlobSchema(def)\n case 'cid-link':\n return this.compileCidLinkSchema(def)\n case 'ref':\n return this.compileRefSchema(def)\n case 'union':\n return this.compileRefUnionSchema(def)\n case 'array':\n return this.compileArraySchema(def)\n default:\n // @ts-expect-error\n throw new Error(`Unsupported def type: ${def.type}`)\n }\n }\n\n private async compileContainedType(\n def: LexiconArray | LexiconArrayItems,\n ): Promise<string> {\n switch (def.type) {\n case 'unknown':\n return this.compileUnknownType(def)\n case 'boolean':\n return this.compileBooleanType(def)\n case 'integer':\n return this.compileIntegerType(def)\n case 'string':\n return this.compileStringType(def)\n case 'bytes':\n return this.compileBytesType(def)\n case 'blob':\n return this.compileBlobType(def)\n case 'cid-link':\n return this.compileCidLinkType(def)\n case 'ref':\n return this.compileRefType(def)\n case 'union':\n return this.compileRefUnionType(def)\n case 'array':\n return this.compileArrayType(def)\n default:\n // @ts-expect-error\n throw new Error(`Unsupported def type: ${def.type}`)\n }\n }\n\n private async compileArraySchema(def: LexiconArray): Promise<string> {\n const itemSchema = await this.compileContainedSchema(def.items)\n const options = stringifyOptions(def, [\n 'minLength',\n 'maxLength',\n ] satisfies (keyof l.ArraySchemaOptions)[])\n return this.pure(`l.array(${itemSchema}, ${options})`)\n }\n\n private async compileArrayType(def: LexiconArray): Promise<string> {\n return `(${await this.compileContainedType(def.items)})[]`\n }\n\n private async compileUnknownSchema(_def: LexiconUnknown): Promise<string> {\n return this.pure(`l.unknownObject()`)\n }\n\n private async compileUnknownType(_def: LexiconUnknown): Promise<string> {\n return `l.UnknownObject`\n }\n\n private async compileBooleanSchema(def: LexiconBoolean): Promise<string> {\n if (hasConst(def)) return this.compileConstSchema(def)\n\n const options = stringifyOptions(def, [\n 'default',\n ] satisfies (keyof l.BooleanSchemaOptions)[])\n return this.pure(`l.boolean(${options})`)\n }\n\n private async compileBooleanType(def: LexiconBoolean): Promise<string> {\n if (hasConst(def)) return this.compileConstType(def)\n return 'boolean'\n }\n\n private async compileIntegerSchema(def: LexiconInteger): Promise<string> {\n if (hasConst(def)) {\n const schema: l.IntegerSchema = l.integer(def)\n schema.assert(def.const)\n }\n\n if (hasEnum(def)) {\n const schema: l.IntegerSchema = l.integer(def)\n for (const val of def.enum) schema.assert(val)\n }\n\n if (hasConst(def)) return this.compileConstSchema(def)\n if (hasEnum(def)) return this.compileEnumSchema(def)\n\n const options = stringifyOptions(def, [\n 'default',\n 'maximum',\n 'minimum',\n ] satisfies (keyof l.IntegerSchemaOptions)[])\n return this.pure(`l.integer(${options})`)\n }\n\n private async compileIntegerType(def: LexiconInteger): Promise<string> {\n if (hasConst(def)) return this.compileConstType(def)\n if (hasEnum(def)) return this.compileEnumType(def)\n\n return 'number'\n }\n\n private async compileStringSchema(def: LexiconString): Promise<string> {\n if (hasConst(def)) {\n const schema: l.StringSchema = l.string(def)\n schema.assert(def.const)\n } else if (hasEnum(def)) {\n const schema: l.StringSchema = l.string(def)\n for (const val of def.enum) schema.assert(val)\n }\n\n if (hasConst(def)) return this.compileConstSchema(def)\n if (hasEnum(def)) return this.compileEnumSchema(def)\n\n const options = stringifyOptions(def, [\n 'default',\n 'format',\n 'maxGraphemes',\n 'minGraphemes',\n 'maxLength',\n 'minLength',\n ] satisfies (keyof l.StringSchemaOptions)[])\n return this.pure(`l.string(${options})`)\n }\n\n private async compileStringType(def: LexiconString): Promise<string> {\n if (hasConst(def)) return this.compileConstType(def)\n if (hasEnum(def)) return this.compileEnumType(def)\n\n switch (def.format) {\n case undefined:\n break\n case 'datetime':\n return 'l.DatetimeString'\n case 'uri':\n return 'l.UriString'\n case 'at-uri':\n return 'l.AtUriString'\n case 'did':\n return 'l.DidString'\n case 'handle':\n return 'l.HandleString'\n case 'at-identifier':\n return 'l.AtIdentifierString'\n case 'nsid':\n return 'l.NsidString'\n case 'tid':\n return 'l.TidString'\n case 'cid':\n return 'l.CidString'\n case 'language':\n return 'l.LanguageString'\n case 'record-key':\n return 'l.RecordKeyString'\n default:\n throw new Error(`Unknown string format: ${def.format}`)\n }\n\n if (def.knownValues?.length) {\n return (\n def.knownValues.map((v) => JSON.stringify(v)).join(' | ') +\n ' | l.UnknownString'\n )\n }\n\n return 'string'\n }\n\n private async compileBytesSchema(def: LexiconBytes): Promise<string> {\n const options = stringifyOptions(def, [\n 'minLength',\n 'maxLength',\n ] satisfies (keyof l.BytesSchemaOptions)[])\n return this.pure(`l.bytes(${options})`)\n }\n\n private async compileBytesType(_def: LexiconBytes): Promise<string> {\n return 'Uint8Array'\n }\n\n private async compileBlobSchema(def: LexiconBlob): Promise<string> {\n const opts = { ...def, allowLegacy: this.options.allowLegacyBlobs === true }\n const options = stringifyOptions(opts, [\n 'maxSize',\n 'accept',\n 'allowLegacy',\n ] satisfies (keyof l.BlobSchemaOptions)[])\n return this.pure(`l.blob(${options})`)\n }\n\n private async compileBlobType(_def: LexiconBlob): Promise<string> {\n return this.options.allowLegacyBlobs\n ? 'l.BlobRef | l.LegacyBlobRef'\n : 'l.BlobRef'\n }\n\n private async compileCidLinkSchema(_def: LexiconCid): Promise<string> {\n return this.pure(`l.cidLink()`)\n }\n\n private async compileCidLinkType(_def: LexiconCid): Promise<string> {\n return 'l.Cid'\n }\n\n private async compileRefSchema(def: LexiconRef): Promise<string> {\n const { varName, typeName } = await this.refResolver.resolve(def.ref)\n // @NOTE \"as any\" is needed in schemas with circular refs as TypeScript\n // cannot infer the type of a value that depends on its initializer type\n return this.pure(`l.ref<${typeName}>((() => ${varName}) as any)`)\n }\n\n private async compileRefType(def: LexiconRef): Promise<string> {\n const ref = await this.refResolver.resolve(def.ref)\n return ref.typeName\n }\n\n private async compileRefUnionSchema(def: LexiconRefUnion): Promise<string> {\n if (def.refs.length === 0 && def.closed) {\n return this.pure(`l.never()`)\n }\n\n const refs = await Promise.all(\n def.refs.map(async (ref: string) => {\n const { varName, typeName } = await this.refResolver.resolve(ref)\n // @NOTE \"as any\" is needed in schemas with circular refs as TypeScript\n // cannot infer the type of a value that depends on its initializer type\n return this.pure(`l.typedRef<${typeName}>((() => ${varName}) as any)`)\n }),\n )\n\n return this.pure(\n `l.typedUnion([${refs.join(',')}], ${def.closed ?? false})`,\n )\n }\n\n private async compileRefUnionType(def: LexiconRefUnion): Promise<string> {\n const types = await Promise.all(\n def.refs.map(async (ref) => {\n const { typeName } = await this.refResolver.resolve(ref)\n return `l.TypedRef<${typeName}>`\n }),\n )\n if (!def.closed) types.push('l.TypedObject')\n return types.join(' | ') || 'never'\n }\n\n private async compileConstSchema<\n T extends null | number | string | boolean,\n >(def: { const: T; enum?: readonly T[]; default?: T }): Promise<string> {\n if (hasEnum(def) && !def.enum.includes(def.const)) {\n return this.pure(`l.never()`)\n }\n\n const options = stringifyOptions(def, [\n 'default',\n ] satisfies (keyof l.LiteralSchemaOptions<any>)[])\n return this.pure(`l.literal(${JSON.stringify(def.const)}, ${options})`)\n }\n\n private async compileConstType<\n T extends null | number | string | boolean,\n >(def: { const: T; enum?: readonly T[] }): Promise<string> {\n if (hasEnum(def) && !def.enum.includes(def.const)) {\n return 'never'\n }\n return JSON.stringify(def.const)\n }\n\n private async compileEnumSchema<T extends null | number | string>(def: {\n enum: readonly T[]\n default?: T\n }): Promise<string> {\n if (def.enum.length === 0) {\n return this.pure(`l.never()`)\n }\n if (def.enum.length === 1 && def.default === undefined) {\n return this.pure(`l.literal(${JSON.stringify(def.enum[0])})`)\n }\n const options = stringifyOptions(def, [\n 'default',\n ] satisfies (keyof l.EnumSchemaOptions<any>)[])\n return this.pure(`l.enum(${JSON.stringify(def.enum)}, ${options})`)\n }\n\n private async compileEnumType<T extends null | number | string>(def: {\n enum: readonly T[]\n }): Promise<string> {\n return def.enum.map((v) => JSON.stringify(v)).join(' | ') || 'never'\n }\n}\n\ntype ParsedDescription = OptionalKind<JSDocStructure> & {\n description?: string\n tags?: { tagName: string; text?: string }[]\n}\n\nfunction parseDescription(description: string): ParsedDescription {\n if (/deprecated/i.test(description)) {\n const deprecationMatch = description.match(\n /(\\s*deprecated\\s*(?:--?|:)?\\s*([^-]*)(?:-+)?)/i,\n )\n if (deprecationMatch) {\n const { 1: match, 2: deprecationNotice } = deprecationMatch\n return {\n description: description.replace(match, '').trim() || undefined,\n tags: [{ tagName: 'deprecated', text: deprecationNotice?.trim() }],\n }\n } else {\n return {\n description: description.trim() || undefined,\n tags: [{ tagName: 'deprecated' }],\n }\n }\n }\n\n return {\n description: description.trim() || undefined,\n }\n}\n\nfunction compileLeadingTrivia(description?: string) {\n if (!description) return undefined\n const parsed = parseDescription(description)\n if (!parsed.description && !parsed.tags?.length) return undefined\n const tags = parsed.tags\n ?.map(({ tagName, text }) => (text ? `@${tagName} ${text}` : `@${tagName}`))\n ?.join('\\n')\n const text = `\\n${[parsed.description, tags].filter(Boolean).join('\\n\\n')}`\n return `\\n\\n/**${text.replaceAll('\\n', '\\n * ')}\\n */\\n`\n}\n\nfunction compileDocs(description?: string) {\n if (!description) return undefined\n return [parseDescription(description)]\n}\n\nfunction stringifyOptions<O extends Record<string, unknown>>(\n obj: O,\n include?: (keyof O)[],\n exclude?: (keyof O)[],\n) {\n const filtered = Object.entries(obj).filter(\n ([k]) => (!include || include.includes(k)) && !exclude?.includes(k),\n )\n return filtered.length ? JSON.stringify(Object.fromEntries(filtered)) : ''\n}\n\nfunction hasConst<T extends { const?: unknown }>(\n def: T,\n): def is T & { const: NonNullable<T['const']> } {\n return def.const != null\n}\n\nfunction hasEnum<T extends { enum?: readonly unknown[] }>(\n def: T,\n): def is T & { enum: unknown[] } {\n return def.enum != null\n}\n\nfunction markPure<T extends string>(v: T): `/*#__PURE__*/ ${T}` {\n return `/*#__PURE__*/ ${v}`\n}\n"]}
1
+ {"version":3,"file":"lex-def-builder.js","sourceRoot":"","sources":["../src/lex-def-builder.ts"],"names":[],"mappings":";;;AAAA,uCAKiB;AA0BjB,oDAAuC;AACvC,uDAK0B;AAC1B,6CAAgD;AAQhD;;GAEG;AACH,MAAa,aAAa;IAIL;IACA;IACA;IALF,WAAW,CAAa;IAEzC,YACmB,OAA6B,EAC7B,IAAgB,EAChB,GAAoB,EACrC,OAAuB;QAHN,YAAO,GAAP,OAAO,CAAsB;QAC7B,SAAI,GAAJ,IAAI,CAAY;QAChB,QAAG,GAAH,GAAG,CAAiB;QAGrC,IAAI,CAAC,WAAW,GAAG,IAAI,6BAAW,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;IACjE,CAAC;IAEO,IAAI,CAAC,IAAY;QACvB,OAAO,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IAC7D,CAAC;IAED,KAAK,CAAC,KAAK;QACT,IAAI,CAAC,IAAI,CAAC,oBAAoB,CAAC;YAC7B,eAAe,EAAE,kCAAuB,CAAC,KAAK;YAC9C,YAAY,EAAE;gBACZ,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;aAC5D;SACF,CAAC,CAAA;QAEF,IAAI,CAAC,IAAI,CAAC,oBAAoB,CAAC;YAC7B,YAAY,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;SAClC,CAAC,CAAA;QAEF,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA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LexiconArrayItems,\n LexiconBlob,\n LexiconBoolean,\n LexiconBytes,\n LexiconCid,\n LexiconDocument,\n LexiconError,\n LexiconIndexer,\n LexiconInteger,\n LexiconObject,\n LexiconParameters,\n LexiconPayload,\n LexiconPermissionSet,\n LexiconProcedure,\n LexiconQuery,\n LexiconRecord,\n LexiconRef,\n LexiconRefUnion,\n LexiconString,\n LexiconSubscription,\n LexiconToken,\n LexiconUnknown,\n} from '@atproto/lex-document'\nimport { l } from '@atproto/lex-schema'\nimport {\n RefResolver,\n RefResolverOptions,\n ResolvedRef,\n getPublicIdentifiers,\n} from './ref-resolver.js'\nimport { asNamespaceExport } from './ts-lang.js'\n\nexport type LexDefBuilderOptions = RefResolverOptions & {\n lib?: string\n allowLegacyBlobs?: boolean\n pureAnnotations?: boolean\n}\n\n/**\n * Utility class to build a TypeScript source file from a lexicon document.\n */\nexport class LexDefBuilder {\n private readonly refResolver: RefResolver\n\n constructor(\n private readonly options: LexDefBuilderOptions,\n private readonly file: SourceFile,\n private readonly doc: LexiconDocument,\n indexer: LexiconIndexer,\n ) {\n this.refResolver = new RefResolver(doc, file, indexer, options)\n }\n\n private pure(code: string) {\n return this.options.pureAnnotations ? markPure(code) : code\n }\n\n async build() {\n this.file.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n declarations: [\n { name: '$nsid', initializer: JSON.stringify(this.doc.id) },\n ],\n })\n\n this.file.addExportDeclaration({\n namedExports: [{ name: '$nsid' }],\n })\n\n const defs = Object.keys(this.doc.defs)\n if (defs.length) {\n const moduleSpecifier = this.options?.lib ?? '@atproto/lex-schema'\n this.file\n .addImportDeclaration({ moduleSpecifier })\n .addNamedImports([{ name: 'l' }])\n\n for (const hash of defs) {\n await this.addDef(hash)\n }\n }\n }\n\n private addUtils(definitions: Record<string, undefined | string>) {\n const entries = Object.entries(definitions).filter(\n (e): e is [(typeof e)[0], NonNullable<(typeof e)[1]>] => e[1] != null,\n )\n if (entries.length) {\n this.file.addVariableStatement({\n isExported: true,\n declarationKind: VariableDeclarationKind.Const,\n declarations: entries.map(([name, initializer]) => ({\n name,\n initializer,\n })),\n })\n }\n }\n\n private async addDef(hash: string) {\n const def = Object.hasOwn(this.doc.defs, hash) ? this.doc.defs[hash] : null\n if (def == null) return\n\n switch (def.type) {\n case 'permission-set':\n return this.addPermissionSet(hash, def)\n case 'procedure':\n return this.addProcedure(hash, def)\n case 'query':\n return this.addQuery(hash, def)\n case 'subscription':\n return this.addSubscription(hash, def)\n case 'record':\n return this.addRecord(hash, def)\n case 'token':\n return this.addToken(hash, def)\n case 'object':\n return this.addObject(hash, def)\n case 'array':\n return this.addArray(hash, def)\n default:\n await this.addSchema(hash, def, {\n type: await this.compileContainedType(def),\n schema: await this.compileContainedSchema(def),\n validationUtils: true,\n })\n }\n }\n\n private async addPermissionSet(hash: string, def: LexiconPermissionSet) {\n const permission = def.permissions.map((def) => {\n const options = stringifyOptions(def, undefined, ['resource', 'type'])\n return this.pure(\n `l.permission(${JSON.stringify(def.resource)}, ${options})`,\n )\n })\n\n const options = stringifyOptions(def, [\n 'title',\n 'title:lang',\n 'detail',\n 'detail:lang',\n ] satisfies (keyof l.PermissionSetOptions)[])\n\n await this.addSchema(hash, def, {\n schema: this.pure(\n `l.permissionSet($nsid, [${permission.join(',')}], ${options})`,\n ),\n })\n }\n\n private async addProcedure(hash: string, def: LexiconProcedure) {\n if (hash !== 'main') {\n throw new Error(`Definition ${hash} cannot be of type ${def.type}`)\n }\n\n // @TODO Build the types instead of using an inferred type.\n\n const ref = await this.addSchema(hash, def, {\n schema: this.pure(`\n l.procedure(\n $nsid,\n ${await this.compileParamsSchema(def.parameters)},\n ${await this.compilePayload(def.input)},\n ${await this.compilePayload(def.output)},\n ${await this.compileErrors(def.errors)}\n )\n `),\n })\n\n this.addMethodTypeUtils(ref, def)\n this.addUtils({\n $lxm: this.pure(`${ref.varName}.nsid`),\n $params: this.pure(`${ref.varName}.parameters`),\n $input: this.pure(`${ref.varName}.input`),\n $output: this.pure(`${ref.varName}.output`),\n })\n }\n\n private async addQuery(hash: string, def: LexiconQuery) {\n if (hash !== 'main') {\n throw new Error(`Definition ${hash} cannot be of type ${def.type}`)\n }\n\n // @TODO Build the types instead of using an inferred type.\n\n const ref = await this.addSchema(hash, def, {\n schema: this.pure(`\n l.query(\n $nsid,\n ${await this.compileParamsSchema(def.parameters)},\n ${await this.compilePayload(def.output)},\n ${await this.compileErrors(def.errors)}\n )\n `),\n })\n\n this.addMethodTypeUtils(ref, def)\n this.addUtils({\n $lxm: this.pure(`${ref.varName}.nsid`),\n $params: `${ref.varName}.parameters`,\n $output: `${ref.varName}.output`,\n })\n }\n\n private async addSubscription(hash: string, def: LexiconSubscription) {\n if (hash !== 'main') {\n throw new Error(`Definition ${hash} cannot be of type ${def.type}`)\n }\n\n // @TODO Build the types instead of using an inferred type.\n\n const ref = await this.addSchema(hash, def, {\n schema: this.pure(`\n l.subscription(\n $nsid,\n ${await this.compileParamsSchema(def.parameters)},\n ${await this.compileBodySchema(def.message?.schema)},\n ${await this.compileErrors(def.errors)}\n )\n `),\n })\n\n this.addMethodTypeUtils(ref, def)\n this.addUtils({\n $lxm: this.pure(`${ref.varName}.nsid`),\n $params: `${ref.varName}.parameters`,\n $message: `${ref.varName}.message`,\n })\n }\n\n addMethodTypeUtils(\n ref: ResolvedRef,\n def: LexiconProcedure | LexiconQuery | LexiconSubscription,\n ) {\n this.file.addTypeAlias({\n isExported: true,\n name: 'Params',\n type: `l.InferMethodParams<typeof ${ref.varName}>`,\n docs: compileDocs(def.parameters?.description),\n })\n\n if (def.type === 'procedure') {\n this.file.addTypeAlias({\n isExported: true,\n name: 'Input',\n type: `l.InferMethodInput<typeof ${ref.varName}>`,\n docs: compileDocs(def.input?.description),\n })\n\n this.file.addTypeAlias({\n isExported: true,\n name: 'InputBody',\n type: `l.InferMethodInputBody<typeof ${ref.varName}>`,\n docs: compileDocs(def.input?.description),\n })\n }\n\n if (def.type === 'procedure' || def.type === 'query') {\n this.file.addTypeAlias({\n isExported: true,\n name: 'Output',\n type: `l.InferMethodOutput<typeof ${ref.varName}>`,\n docs: compileDocs(def.output?.description),\n })\n\n this.file.addTypeAlias({\n isExported: true,\n name: 'OutputBody',\n type: `l.InferMethodOutputBody<typeof ${ref.varName}>`,\n docs: compileDocs(def.output?.description),\n })\n }\n\n if (def.type === 'subscription') {\n this.file.addTypeAlias({\n isExported: true,\n name: 'Message',\n type: `l.InferSubscriptionMessage<typeof ${ref.varName}>`,\n docs: compileDocs(def.message?.description),\n })\n }\n }\n\n private async addRecord(hash: string, def: LexiconRecord) {\n if (hash !== 'main') {\n throw new Error(`Definition ${hash} cannot be of type ${def.type}`)\n }\n\n const key = JSON.stringify(def.key ?? 'any')\n const objectSchema = await this.compileObjectSchema(def.record)\n\n const properties = await this.compilePropertiesTypes(def.record)\n properties.unshift(`$type: ${JSON.stringify(l.$type(this.doc.id, hash))}`)\n\n await this.addSchema(hash, def, {\n type: `{ ${properties.join(';')} }`,\n schema: (ref) =>\n this.pure(\n `l.record<${key}, ${ref.typeName}>(${key}, $nsid, ${objectSchema})`,\n ),\n objectUtils: true,\n validationUtils: true,\n })\n }\n\n private async addObject(hash: string, def: LexiconObject) {\n const objectSchema = await this.compileObjectSchema(def)\n\n const properties = await this.compilePropertiesTypes(def)\n properties.unshift(`$type?: ${JSON.stringify(l.$type(this.doc.id, hash))}`)\n\n await this.addSchema(hash, def, {\n type: `{ ${properties.join(';')} }`,\n schema: (ref) =>\n this.pure(\n `l.typedObject<${ref.typeName}>($nsid, ${JSON.stringify(hash)}, ${objectSchema})`,\n ),\n objectUtils: true,\n validationUtils: true,\n })\n }\n\n private async addToken(hash: string, def: LexiconToken) {\n await this.addSchema(hash, def, {\n schema: this.pure(`l.token($nsid, ${JSON.stringify(hash)})`),\n type: JSON.stringify(l.$type(this.doc.id, hash)),\n validationUtils: true,\n })\n }\n\n private async addArray(hash: string, def: LexiconArray) {\n // @TODO It could be nice to expose the array item type as a separate type.\n // This was not done (yet) as there is no easy way to name it to avoid\n // collisions.\n\n const itemSchema = await this.compileContainedSchema(def.items)\n const options = stringifyOptions(def, [\n 'minLength',\n 'maxLength',\n ] satisfies (keyof l.ArraySchemaOptions)[])\n\n await this.addSchema(hash, def, {\n type: `(${await this.compileContainedType(def.items)})[]`,\n // @NOTE Not using compileArraySchema to allow specifying the generic\n // parameter to l.array<>.\n schema: (ref) =>\n this.pure(\n `l.array<${ref.typeName}[number]>(${itemSchema}, ${options})`,\n ),\n validationUtils: true,\n })\n }\n\n private async addSchema(\n hash: string,\n def: { description?: string },\n {\n type,\n schema,\n objectUtils,\n validationUtils,\n }: {\n type?: string | ((ref: ResolvedRef) => string)\n schema?: string | ((ref: ResolvedRef) => string)\n objectUtils?: boolean\n validationUtils?: boolean\n },\n ): Promise<ResolvedRef> {\n const ref = await this.refResolver.resolveLocal(hash)\n const pub = getPublicIdentifiers(hash)\n\n if (type) {\n this.file.addTypeAlias({\n name: ref.typeName,\n type: typeof type === 'function' ? type(ref) : type,\n docs: compileDocs(def.description),\n })\n\n this.file.addExportDeclaration({\n isTypeOnly: true,\n namedExports: [\n {\n name: ref.typeName,\n alias:\n ref.typeName === pub.typeName\n ? undefined\n : asNamespaceExport(pub.typeName),\n },\n ],\n })\n }\n\n if (schema) {\n this.file.addVariableStatement({\n declarationKind: VariableDeclarationKind.Const,\n declarations: [\n {\n name: ref.varName,\n initializer: typeof schema === 'function' ? schema(ref) : schema,\n },\n ],\n docs: compileDocs(def.description),\n })\n\n this.file.addExportDeclaration({\n namedExports: [\n {\n name: ref.varName,\n alias:\n ref.varName === pub.varName\n ? undefined\n : asNamespaceExport(pub.varName),\n },\n ],\n })\n }\n\n if (hash === 'main' && objectUtils) {\n this.addUtils({\n $isTypeOf: markPure(`${ref.varName}.isTypeOf.bind(${ref.varName})`),\n $build: markPure(`${ref.varName}.build.bind(${ref.varName})`),\n $type: markPure(`${ref.varName}.$type`),\n })\n }\n\n if (hash === 'main' && validationUtils) {\n this.addUtils({\n $assert: markPure(`${ref.varName}.assert.bind(${ref.varName})`),\n $ifMatches: markPure(`${ref.varName}.ifMatches.bind(${ref.varName})`),\n $matches: markPure(`${ref.varName}.matches.bind(${ref.varName})`),\n $parse: markPure(`${ref.varName}.parse.bind(${ref.varName})`),\n $safeParse: markPure(`${ref.varName}.safeParse.bind(${ref.varName})`),\n })\n }\n\n return ref\n }\n\n private async compilePayload(def: LexiconPayload | undefined) {\n if (!def) return this.pure(`l.payload()`)\n\n // Special case for JSON object payloads\n if (def.encoding === 'application/json' && def.schema?.type === 'object') {\n const properties = await this.compilePropertiesSchemas(def.schema)\n return this.pure(`l.jsonPayload({${properties.join(',')}})`)\n }\n\n const encodedEncoding = JSON.stringify(def.encoding)\n if (def.schema) {\n const bodySchema = await this.compileBodySchema(def.schema)\n return this.pure(`l.payload(${encodedEncoding}, ${bodySchema})`)\n } else {\n return this.pure(`l.payload(${encodedEncoding})`)\n }\n }\n\n private async compileBodySchema(\n def?: LexiconRef | LexiconRefUnion | LexiconObject,\n ): Promise<string> {\n if (!def) return 'undefined'\n if (def.type === 'object') return this.compileObjectSchema(def)\n return this.compileContainedSchema(def)\n }\n\n private async compileParamsSchema(def: undefined | LexiconParameters) {\n if (!def) return this.pure(`l.params()`)\n\n const properties = await this.compilePropertiesSchemas(def)\n return this.pure(`l.params({${properties.join(',')}})`)\n }\n\n private async compileErrors(defs?: readonly LexiconError[]) {\n if (!defs?.length) return ''\n return JSON.stringify(defs.map((d) => d.name))\n }\n\n private async compileObjectSchema(def: LexiconObject): Promise<string> {\n const properties = await this.compilePropertiesSchemas(def)\n return this.pure(`l.object({${properties.join(',')}})`)\n }\n\n private async compilePropertiesSchemas(options: {\n properties: Record<string, LexiconArray | LexiconArrayItems>\n required?: readonly string[]\n nullable?: readonly string[]\n }): Promise<string[]> {\n for (const opt of ['required', 'nullable'] as const) {\n if (options[opt]) {\n for (const prop of options[opt]) {\n if (!Object.hasOwn(options.properties, prop)) {\n throw new Error(`No schema found for ${opt} property \"${prop}\"`)\n }\n }\n }\n }\n\n return Promise.all(\n Object.entries(options.properties).map((entry) => {\n return this.compilePropertyEntrySchema(entry, options)\n }),\n )\n }\n\n private async compilePropertiesTypes(options: {\n properties: Record<string, LexiconArray | LexiconArrayItems>\n required?: readonly string[]\n nullable?: readonly string[]\n }) {\n return Promise.all(\n Object.entries(options.properties).map((entry) => {\n return this.compilePropertyEntryType(entry, options)\n }),\n )\n }\n\n private async compilePropertyEntrySchema(\n [key, def]: [string, LexiconArray | LexiconArrayItems],\n options: {\n required?: readonly string[]\n nullable?: readonly string[]\n },\n ) {\n const isNullable = options.nullable?.includes(key)\n const isRequired = options.required?.includes(key)\n\n let schema = await this.compileContainedSchema(def)\n\n if (isNullable) {\n schema = this.pure(`l.nullable(${schema})`)\n }\n\n if (!isRequired) {\n schema = this.pure(`l.optional(${schema})`)\n }\n\n return `${JSON.stringify(key)}:${schema}`\n }\n\n private async compilePropertyEntryType(\n [key, def]: [string, LexiconArray | LexiconArrayItems],\n options: {\n required?: readonly string[]\n nullable?: readonly string[]\n },\n ) {\n const isNullable = options.nullable?.includes(key)\n const isRequired = options.required?.includes(key)\n\n const optional = isRequired ? '' : '?'\n const append = isNullable ? ' | null' : ''\n\n const jsDoc = compileLeadingTrivia(def.description) || ''\n const name = JSON.stringify(key)\n const type = await this.compileContainedType(def)\n\n return `${jsDoc}${name}${optional}:${type}${append}`\n }\n\n private async compileContainedSchema(\n def: LexiconArray | LexiconArrayItems,\n ): Promise<string> {\n switch (def.type) {\n case 'unknown':\n return this.compileUnknownSchema(def)\n case 'boolean':\n return this.compileBooleanSchema(def)\n case 'integer':\n return this.compileIntegerSchema(def)\n case 'string':\n return this.compileStringSchema(def)\n case 'bytes':\n return this.compileBytesSchema(def)\n case 'blob':\n return this.compileBlobSchema(def)\n case 'cid-link':\n return this.compileCidLinkSchema(def)\n case 'ref':\n return this.compileRefSchema(def)\n case 'union':\n return this.compileRefUnionSchema(def)\n case 'array':\n return this.compileArraySchema(def)\n default:\n // @ts-expect-error\n throw new Error(`Unsupported def type: ${def.type}`)\n }\n }\n\n private async compileContainedType(\n def: LexiconArray | LexiconArrayItems,\n ): Promise<string> {\n switch (def.type) {\n case 'unknown':\n return this.compileUnknownType(def)\n case 'boolean':\n return this.compileBooleanType(def)\n case 'integer':\n return this.compileIntegerType(def)\n case 'string':\n return this.compileStringType(def)\n case 'bytes':\n return this.compileBytesType(def)\n case 'blob':\n return this.compileBlobType(def)\n case 'cid-link':\n return this.compileCidLinkType(def)\n case 'ref':\n return this.compileRefType(def)\n case 'union':\n return this.compileRefUnionType(def)\n case 'array':\n return this.compileArrayType(def)\n default:\n // @ts-expect-error\n throw new Error(`Unsupported def type: ${def.type}`)\n }\n }\n\n private async compileArraySchema(def: LexiconArray): Promise<string> {\n const itemSchema = await this.compileContainedSchema(def.items)\n const options = stringifyOptions(def, [\n 'minLength',\n 'maxLength',\n ] satisfies (keyof l.ArraySchemaOptions)[])\n return this.pure(`l.array(${itemSchema}, ${options})`)\n }\n\n private async compileArrayType(def: LexiconArray): Promise<string> {\n return `(${await this.compileContainedType(def.items)})[]`\n }\n\n private async compileUnknownSchema(_def: LexiconUnknown): Promise<string> {\n return this.pure(`l.unknownObject()`)\n }\n\n private async compileUnknownType(_def: LexiconUnknown): Promise<string> {\n return `l.UnknownObject`\n }\n\n private async compileBooleanSchema(def: LexiconBoolean): Promise<string> {\n if (hasConst(def)) return this.compileConstSchema(def)\n\n const options = stringifyOptions(def, [\n 'default',\n ] satisfies (keyof l.BooleanSchemaOptions)[])\n return this.pure(`l.boolean(${options})`)\n }\n\n private async compileBooleanType(def: LexiconBoolean): Promise<string> {\n if (hasConst(def)) return this.compileConstType(def)\n return 'boolean'\n }\n\n private async compileIntegerSchema(def: LexiconInteger): Promise<string> {\n if (hasConst(def)) {\n const schema: l.IntegerSchema = l.integer(def)\n schema.assert(def.const)\n }\n\n if (hasEnum(def)) {\n const schema: l.IntegerSchema = l.integer(def)\n for (const val of def.enum) schema.assert(val)\n }\n\n if (hasConst(def)) return this.compileConstSchema(def)\n if (hasEnum(def)) return this.compileEnumSchema(def)\n\n const options = stringifyOptions(def, [\n 'default',\n 'maximum',\n 'minimum',\n ] satisfies (keyof l.IntegerSchemaOptions)[])\n return this.pure(`l.integer(${options})`)\n }\n\n private async compileIntegerType(def: LexiconInteger): Promise<string> {\n if (hasConst(def)) return this.compileConstType(def)\n if (hasEnum(def)) return this.compileEnumType(def)\n\n return 'number'\n }\n\n private async compileStringSchema(def: LexiconString): Promise<string> {\n if (hasConst(def)) {\n const schema: l.StringSchema = l.string(def)\n schema.assert(def.const)\n } else if (hasEnum(def)) {\n const schema: l.StringSchema = l.string(def)\n for (const val of def.enum) schema.assert(val)\n }\n\n if (hasConst(def)) return this.compileConstSchema(def)\n if (hasEnum(def)) return this.compileEnumSchema(def)\n\n const options = stringifyOptions(def, [\n 'default',\n 'format',\n 'maxGraphemes',\n 'minGraphemes',\n 'maxLength',\n 'minLength',\n ] satisfies (keyof l.StringSchemaOptions)[])\n return this.pure(`l.string(${options})`)\n }\n\n private async compileStringType(def: LexiconString): Promise<string> {\n if (hasConst(def)) return this.compileConstType(def)\n if (hasEnum(def)) return this.compileEnumType(def)\n\n switch (def.format) {\n case undefined:\n break\n case 'datetime':\n return 'l.DatetimeString'\n case 'uri':\n return 'l.UriString'\n case 'at-uri':\n return 'l.AtUriString'\n case 'did':\n return 'l.DidString'\n case 'handle':\n return 'l.HandleString'\n case 'at-identifier':\n return 'l.AtIdentifierString'\n case 'nsid':\n return 'l.NsidString'\n case 'tid':\n return 'l.TidString'\n case 'cid':\n return 'l.CidString'\n case 'language':\n return 'l.LanguageString'\n case 'record-key':\n return 'l.RecordKeyString'\n default:\n throw new Error(`Unknown string format: ${def.format}`)\n }\n\n if (def.knownValues?.length) {\n return (\n def.knownValues.map((v) => JSON.stringify(v)).join(' | ') +\n ' | l.UnknownString'\n )\n }\n\n return 'string'\n }\n\n private async compileBytesSchema(def: LexiconBytes): Promise<string> {\n const options = stringifyOptions(def, [\n 'minLength',\n 'maxLength',\n ] satisfies (keyof l.BytesSchemaOptions)[])\n return this.pure(`l.bytes(${options})`)\n }\n\n private async compileBytesType(_def: LexiconBytes): Promise<string> {\n return 'Uint8Array'\n }\n\n private async compileBlobSchema(def: LexiconBlob): Promise<string> {\n const opts = { ...def, allowLegacy: this.options.allowLegacyBlobs === true }\n const options = stringifyOptions(opts, [\n 'maxSize',\n 'accept',\n 'allowLegacy',\n ] satisfies (keyof l.BlobSchemaOptions)[])\n return this.pure(`l.blob(${options})`)\n }\n\n private async compileBlobType(_def: LexiconBlob): Promise<string> {\n return this.options.allowLegacyBlobs\n ? 'l.BlobRef | l.LegacyBlobRef'\n : 'l.BlobRef'\n }\n\n private async compileCidLinkSchema(_def: LexiconCid): Promise<string> {\n return this.pure(`l.cidLink()`)\n }\n\n private async compileCidLinkType(_def: LexiconCid): Promise<string> {\n return 'l.Cid'\n }\n\n private async compileRefSchema(def: LexiconRef): Promise<string> {\n const { varName, typeName } = await this.refResolver.resolve(def.ref)\n // @NOTE \"as any\" is needed in schemas with circular refs as TypeScript\n // cannot infer the type of a value that depends on its initializer type\n return this.pure(`l.ref<${typeName}>((() => ${varName}) as any)`)\n }\n\n private async compileRefType(def: LexiconRef): Promise<string> {\n const ref = await this.refResolver.resolve(def.ref)\n return ref.typeName\n }\n\n private async compileRefUnionSchema(def: LexiconRefUnion): Promise<string> {\n if (def.refs.length === 0 && def.closed) {\n return this.pure(`l.never()`)\n }\n\n const refs = await Promise.all(\n def.refs.map(async (ref: string) => {\n const { varName, typeName } = await this.refResolver.resolve(ref)\n // @NOTE \"as any\" is needed in schemas with circular refs as TypeScript\n // cannot infer the type of a value that depends on its initializer type\n return this.pure(`l.typedRef<${typeName}>((() => ${varName}) as any)`)\n }),\n )\n\n return this.pure(\n `l.typedUnion([${refs.join(',')}], ${def.closed ?? false})`,\n )\n }\n\n private async compileRefUnionType(def: LexiconRefUnion): Promise<string> {\n const types = await Promise.all(\n def.refs.map(async (ref) => {\n const { typeName } = await this.refResolver.resolve(ref)\n return `l.TypedRef<${typeName}>`\n }),\n )\n if (!def.closed) types.push('l.TypedObject')\n return types.join(' | ') || 'never'\n }\n\n private async compileConstSchema<\n T extends null | number | string | boolean,\n >(def: { const: T; enum?: readonly T[]; default?: T }): Promise<string> {\n if (hasEnum(def) && !def.enum.includes(def.const)) {\n return this.pure(`l.never()`)\n }\n\n const options = stringifyOptions(def, [\n 'default',\n ] satisfies (keyof l.LiteralSchemaOptions<any>)[])\n return this.pure(`l.literal(${JSON.stringify(def.const)}, ${options})`)\n }\n\n private async compileConstType<\n T extends null | number | string | boolean,\n >(def: { const: T; enum?: readonly T[] }): Promise<string> {\n if (hasEnum(def) && !def.enum.includes(def.const)) {\n return 'never'\n }\n return JSON.stringify(def.const)\n }\n\n private async compileEnumSchema<T extends null | number | string>(def: {\n enum: readonly T[]\n default?: T\n }): Promise<string> {\n if (def.enum.length === 0) {\n return this.pure(`l.never()`)\n }\n if (def.enum.length === 1 && def.default === undefined) {\n return this.pure(`l.literal(${JSON.stringify(def.enum[0])})`)\n }\n const options = stringifyOptions(def, [\n 'default',\n ] satisfies (keyof l.EnumSchemaOptions<any>)[])\n return this.pure(`l.enum(${JSON.stringify(def.enum)}, ${options})`)\n }\n\n private async compileEnumType<T extends null | number | string>(def: {\n enum: readonly T[]\n }): Promise<string> {\n return def.enum.map((v) => JSON.stringify(v)).join(' | ') || 'never'\n }\n}\n\ntype ParsedDescription = OptionalKind<JSDocStructure> & {\n description?: string\n tags?: { tagName: string; text?: string }[]\n}\n\nfunction parseDescription(description: string): ParsedDescription {\n if (/deprecated/i.test(description)) {\n const deprecationMatch = description.match(\n /(\\s*deprecated\\s*(?:--?|:)?\\s*([^-]*)(?:-+)?)/i,\n )\n if (deprecationMatch) {\n const { 1: match, 2: deprecationNotice } = deprecationMatch\n return {\n description: description.replace(match, '').trim() || undefined,\n tags: [{ tagName: 'deprecated', text: deprecationNotice?.trim() }],\n }\n } else {\n return {\n description: description.trim() || undefined,\n tags: [{ tagName: 'deprecated' }],\n }\n }\n }\n\n return {\n description: description.trim() || undefined,\n }\n}\n\nfunction compileLeadingTrivia(description?: string) {\n if (!description) return undefined\n const parsed = parseDescription(description)\n if (!parsed.description && !parsed.tags?.length) return undefined\n const tags = parsed.tags\n ?.map(({ tagName, text }) => (text ? `@${tagName} ${text}` : `@${tagName}`))\n ?.join('\\n')\n const text = `\\n${[parsed.description, tags].filter(Boolean).join('\\n\\n')}`\n return `\\n\\n/**${text.replaceAll('\\n', '\\n * ')}\\n */\\n`\n}\n\nfunction compileDocs(description?: string) {\n if (!description) return undefined\n return [parseDescription(description)]\n}\n\nfunction stringifyOptions<O extends Record<string, unknown>>(\n obj: O,\n include?: (keyof O)[],\n exclude?: (keyof O)[],\n) {\n const filtered = Object.entries(obj).filter(\n ([k]) => (!include || include.includes(k)) && !exclude?.includes(k),\n )\n return filtered.length ? JSON.stringify(Object.fromEntries(filtered)) : ''\n}\n\nfunction hasConst<T extends { const?: unknown }>(\n def: T,\n): def is T & { const: NonNullable<T['const']> } {\n return def.const != null\n}\n\nfunction hasEnum<T extends { enum?: readonly unknown[] }>(\n def: T,\n): def is T & { enum: unknown[] } {\n return def.enum != null\n}\n\nfunction markPure<T extends string>(v: T): `/*#__PURE__*/ ${T}` {\n return `/*#__PURE__*/ ${v}`\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ref-resolver.d.ts","sourceRoot":"","sources":["../src/ref-resolver.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AACrC,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAA;AAWvE,MAAM,MAAM,kBAAkB,GAAG;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,MAAM,CAAA;CACjB,CAAA;AAED;;;GAGG;AAC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AO;IACf,OAAO,CAAC,OAAO;gBAHP,GAAG,EAAE,eAAe,EACpB,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE,kBAAkB;IAGrC,SAAgB,OAAO,QACT,MAAM,KAAG,OAAO,CAAC,WAAW,CAAC,CAW1C;IAGD,OAAO,CAAC,4BAA4B;IAyBpC;;;OAGG;IACH,SAAgB,YAAY,SACb,MAAM,KAAG,OAAO,CAAC,WAAW,CAAC,CAuD3C;IAED;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,CAAC,eAAe,CAiD/B;IAED,OAAO,CAAC,eAAe;IAiBvB,OAAO,CAAC,iCAAiC;IAazC,OAAO,CAAC,uBAAuB;IAU/B,OAAO,CAAC,qBAAqB;IAI7B,OAAO,CAAC,kBAAkB;IAc1B,OAAO,CAAC,sBAAsB;IAkB9B,OAAO,CAAC,8BAA8B;IActC,OAAO,CAAC,oBAAoB;CAe7B;AAoBD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CAkB9D"}
@@ -34,13 +34,20 @@ class RefResolver {
34
34
  }
35
35
  });
36
36
  #defCounters = new Map();
37
- nextSafeDefinitionIdentifier(safeIdentifier) {
38
- const count = this.#defCounters.get(safeIdentifier) ?? 0;
39
- this.#defCounters.set(safeIdentifier, count + 1);
37
+ nextSafeDefinitionIdentifier(name) {
38
+ // use camelCase version of the hash as base name
39
+ const nameSafe = (0, util_js_1.startsWithLower)(name) && (0, ts_lang_js_1.isValidJsIdentifier)(name)
40
+ ? name
41
+ : (0, util_js_1.toCamelCase)(name).replace(/^[0-9]+/g, '') || 'def';
42
+ const count = this.#defCounters.get(nameSafe) ?? 0;
43
+ this.#defCounters.set(nameSafe, count + 1);
40
44
  // @NOTE We don't need to check against local declarations in the file here
41
45
  // since we are using a naming system that should guarantee no other
42
- // identifier has a <safeIdentifier>$<number> format.
43
- return `${safeIdentifier}$${count}`;
46
+ // identifier has a <nameSafe>$<number> format ("$" cannot appear in
47
+ // hashes so only *we* are generating such identifiers).
48
+ const identifier = `${nameSafe}$${count}`;
49
+ (0, node_assert_1.default)((0, ts_lang_js_1.isValidJsIdentifier)(identifier), `Unable to generate safe identifier for: "${name}"`);
50
+ return identifier;
44
51
  }
45
52
  /**
46
53
  * @note The returned `typeName` and `varName` are *both* guaranteed to be
@@ -89,8 +96,9 @@ class RefResolver {
89
96
  // as base, and append a counter to avoid conflicts
90
97
  this.nextSafeDefinitionIdentifier(safeIdentifier)
91
98
  : // hash only contained unsafe characters, generate a safe one
92
- this.nextSafeDefinitionIdentifier('def');
99
+ this.nextSafeDefinitionIdentifier(hash);
93
100
  const typeName = (0, util_js_1.ucFirst)(varName);
101
+ (0, node_assert_1.default)((0, ts_lang_js_1.isSafeLocalIdentifier)(typeName), 'Expected safe type identifier');
94
102
  (0, node_assert_1.default)(varName !== typeName, 'Variable and type name should be different');
95
103
  return { varName, typeName };
96
104
  });
@@ -109,11 +117,25 @@ class RefResolver {
109
117
  if (!srcDef) {
110
118
  throw new Error(`Missing def "${hash}" in "${nsid}" (referenced from ${this.doc.id})`);
111
119
  }
120
+ const publicIds = getPublicIdentifiers(hash);
121
+ if (!(0, ts_lang_js_1.isValidJsIdentifier)(publicIds.typeName)) {
122
+ // If <typeName> is not a valid identifier, we cannot access the type
123
+ // using dot notation (<nsIdentifier>.<typeName>). Note that, unlike js
124
+ // variables, types cannot be accessed using string indexing (like:
125
+ // <nsIdentifier>['<typeName>']) because it generates TypeScript errors:
126
+ //
127
+ // > "Cannot use namespace '<nsIdentifier>' as a type."
128
+ // Instead the generated code should look like:
129
+ // import { "<unsafeTypeName>" as <safeIdentifier> } from './<moduleSpecifier>'
130
+ // Because it requires more complex management of local variables names,
131
+ // and we don't expect this to actually happen with properly designed
132
+ // lexicons documents, we do not support this for now.
133
+ throw new Error('Import of definitions with unsafe type names is not supported');
134
+ }
112
135
  // import * as <nsIdentifier> from './<moduleSpecifier>'
113
136
  const nsIdentifier = this.getNsIdentifier(nsid, moduleSpecifier);
114
- const publicIds = getPublicIdentifiers(hash);
115
137
  return {
116
- varName: (0, ts_lang_js_1.isSafeIdentifier)(publicIds.varName)
138
+ varName: (0, ts_lang_js_1.isValidJsIdentifier)(publicIds.varName)
117
139
  ? `${nsIdentifier}.${publicIds.varName}`
118
140
  : `${nsIdentifier}[${JSON.stringify(publicIds.varName)}]`,
119
141
  typeName: `${nsIdentifier}.${publicIds.typeName}`,
@@ -148,7 +170,7 @@ class RefResolver {
148
170
  this.conflictsWithImports(name));
149
171
  }
150
172
  conflictsWithKeywords(name) {
151
- return (0, ts_lang_js_1.isReservedWord)(name);
173
+ return (0, ts_lang_js_1.isJsKeyword)(name) || (0, ts_lang_js_1.isGlobalIdentifier)(name);
152
174
  }
153
175
  conflictsWithUtils(name) {
154
176
  // Do not allow "Main" as imported ns identifier since it has a special
@@ -214,7 +236,7 @@ function nsidToIdentifier(nsid) {
214
236
  // full NSID.
215
237
  for (let i = 2; i < parts.length; i++) {
216
238
  const identifier = (0, util_js_1.toPascalCase)(parts.slice(-i).join('.'));
217
- if ((0, ts_lang_js_1.isSafeIdentifier)(identifier))
239
+ if ((0, ts_lang_js_1.isSafeLocalIdentifier)(identifier))
218
240
  return identifier;
219
241
  }
220
242
  return undefined;
@@ -228,23 +250,24 @@ function nsidToIdentifier(nsid) {
228
250
  */
229
251
  function getPublicIdentifiers(hash) {
230
252
  const varName = hash;
231
- // @NOTE Type names *must* be valid TypeScript identifiers (this is because,
232
- // unlike variable names, we cannot use string indexing to access exported
233
- // types).
234
- const typeName = (0, util_js_1.toPascalCase)(hash);
235
- if (!typeName || varName === typeName || !(0, ts_lang_js_1.isSafeIdentifier)(typeName)) {
236
- return { varName, typeName: `Def${typeName}` };
253
+ // @NOTE we try to circumvent the issue of unsafe type names described in
254
+ // `RefResolver.resolveExternal` by ensuring that type names are always safe
255
+ // identifiers, even if it means changing them from the original hash.
256
+ let typeName = (0, util_js_1.toPascalCase)(hash);
257
+ if (varName === typeName || !(0, ts_lang_js_1.isValidJsIdentifier)(typeName)) {
258
+ typeName = `TypeOf${typeName}`;
237
259
  }
260
+ (0, node_assert_1.default)((0, ts_lang_js_1.isValidJsIdentifier)(typeName), `Unable to generate a predictable safe identifier for "${hash}"`);
238
261
  return { varName, typeName };
239
262
  }
240
263
  function asSafeDefinitionIdentifier(name) {
241
- if ((0, util_js_1.startsWithLowerLetter)(name) &&
242
- (0, ts_lang_js_1.isSafeIdentifier)(name) &&
243
- (0, ts_lang_js_1.isSafeIdentifier)((0, util_js_1.ucFirst)(name))) {
264
+ if ((0, util_js_1.startsWithLower)(name) &&
265
+ (0, ts_lang_js_1.isSafeLocalIdentifier)(name) &&
266
+ (0, ts_lang_js_1.isSafeLocalIdentifier)((0, util_js_1.ucFirst)(name))) {
244
267
  return name;
245
268
  }
246
269
  const camel = (0, util_js_1.toCamelCase)(name);
247
- if ((0, ts_lang_js_1.isSafeIdentifier)(camel) && (0, ts_lang_js_1.isSafeIdentifier)((0, util_js_1.ucFirst)(camel))) {
270
+ if ((0, ts_lang_js_1.isSafeLocalIdentifier)(camel) && (0, ts_lang_js_1.isSafeLocalIdentifier)((0, util_js_1.ucFirst)(camel))) {
248
271
  return camel;
249
272
  }
250
273
  return undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"ref-resolver.js","sourceRoot":"","sources":["../src/ref-resolver.ts"],"names":[],"mappings":";;;AAiSA,oDAUC;;AA3SD,sEAAgC;AAChC,yCAAgC;AAGhC,6CAA+D;AAC/D,uCAOkB;AAWlB;;;GAGG;AACH,MAAa,WAAW;IAEZ;IACA;IACA;IACA;IAJV,YACU,GAAoB,EACpB,IAAgB,EAChB,OAAuB,EACvB,OAA2B;QAH3B,QAAG,GAAH,GAAG,CAAiB;QACpB,SAAI,GAAJ,IAAI,CAAY;QAChB,YAAO,GAAP,OAAO,CAAgB;QACvB,YAAO,GAAP,OAAO,CAAoB;IAClC,CAAC;IAEY,OAAO,GAAG,IAAA,iBAAO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,EAAE,EAAE,CAAA;IAChD,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAA;AAC9B,CAAC;AAED,SAAS,0BAA0B,CAAC,IAAY;IAC9C,IACE,IAAA,+BAAqB,EAAC,IAAI,CAAC;QAC3B,IAAA,6BAAgB,EAAC,IAAI,CAAC;QACtB,IAAA,6BAAgB,EAAC,IAAA,iBAAO,EAAC,IAAI,CAAC,CAAC,EAC/B,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;IACD,MAAM,KAAK,GAAG,IAAA,qBAAW,EAAC,IAAI,CAAC,CAAA;IAC/B,IAAI,IAAA,6BAAgB,EAAC,KAAK,CAAC,IAAI,IAAA,6BAAgB,EAAC,IAAA,iBAAO,EAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QAChE,OAAO,KAAK,CAAA;IACd,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC","sourcesContent":["import assert from 'node:assert'\nimport { join } from 'node:path'\nimport { SourceFile } from 'ts-morph'\nimport { LexiconDocument, LexiconIndexer } from '@atproto/lex-document'\nimport { isReservedWord, isSafeIdentifier } from './ts-lang.js'\nimport {\n asRelativePath,\n memoize,\n startsWithLowerLetter,\n toCamelCase,\n toPascalCase,\n ucFirst,\n} from './util.js'\n\nexport type RefResolverOptions = {\n importExt?: string\n}\n\nexport type ResolvedRef = {\n varName: string\n typeName: string\n}\n\n/**\n * Utility class to resolve lexicon references to TypeScript identifiers,\n * generating \"import\" statements as needed.\n */\nexport class RefResolver {\n constructor(\n private doc: LexiconDocument,\n private file: SourceFile,\n private indexer: LexiconIndexer,\n private options: RefResolverOptions,\n ) {}\n\n public readonly resolve = memoize(\n async (ref: string): Promise<ResolvedRef> => {\n const [nsid, hash = 'main'] = ref.split('#')\n\n if (nsid === '' || nsid === this.doc.id) {\n return this.resolveLocal(hash)\n } else {\n // @NOTE: Normalize (#main fragment) to ensure proper memoization\n const fullRef = `${nsid}#${hash}`\n return this.resolveExternal(fullRef)\n }\n },\n )\n\n #defCounters = new Map<string, number>()\n private nextSafeDefinitionIdentifier(safeIdentifier: string) {\n const count = this.#defCounters.get(safeIdentifier) ?? 0\n this.#defCounters.set(safeIdentifier, count + 1)\n // @NOTE We don't need to check against local declarations in the file here\n // since we are using a naming system that should guarantee no other\n // identifier has a <safeIdentifier>$<number> format.\n return `${safeIdentifier}$${count}`\n }\n\n /**\n * @note The returned `typeName` and `varName` are *both* guaranteed to be\n * valid TypeScript identifiers.\n */\n public readonly resolveLocal = memoize(\n async (hash: string): Promise<ResolvedRef> => {\n const hashes = Object.keys(this.doc.defs)\n\n if (!hashes.includes(hash)) {\n throw new Error(`Definition ${hash} not found in ${this.doc.id}`)\n }\n\n // Because we are using predictable \"public\" identifiers for type names,\n // we need to ensure there are no conflicts between different definitions\n // in the same lexicon document.\n //\n // @NOTE It should be possible to implement a way to generate\n // non-conflicting type names for all public (type) identifiers in a\n // project. However, this would add a lot of complexity to the code\n // generation process, and the likelihood of such conflicts happening in\n // practice is very low, so we opt for a simpler approach of just throwing\n // an error if a conflict is detected.\n const pub = getPublicIdentifiers(hash)\n for (const otherHash of hashes) {\n if (otherHash === hash) continue\n const otherPub = getPublicIdentifiers(otherHash)\n if (otherPub.typeName === pub.typeName) {\n throw new Error(\n `Conflicting type names for definitions #${hash} and #${otherHash} in ${this.doc.id}`,\n )\n }\n }\n\n // Try to keep and identifier that resembles the original hash as identifier\n const safeIdentifier = asSafeDefinitionIdentifier(hash)\n\n // If the safe identifier is not conflicting with other definition names,\n // or reserved words, we can use it as-is. Otherwise, we need to generate\n // a unique safe identifier.\n const varName = safeIdentifier\n ? !hashes.some((otherHash) => {\n if (otherHash === hash) return false\n const otherIdentifier = asSafeDefinitionIdentifier(otherHash)\n return otherIdentifier === safeIdentifier\n })\n ? // Safe identifier can be used as-is as it does not conflict with\n // other definition names\n safeIdentifier\n : // In order to keep identifiers stable, we use the safe identifier\n // as base, and append a counter to avoid conflicts\n this.nextSafeDefinitionIdentifier(safeIdentifier)\n : // hash only contained unsafe characters, generate a safe one\n this.nextSafeDefinitionIdentifier('def')\n\n const typeName = ucFirst(varName)\n assert(varName !== typeName, 'Variable and type name should be different')\n\n return { varName, typeName }\n },\n )\n\n /**\n * @note Since this is a memoized function, and is used to generate the name\n * of local variables, we should avoid returning different results for\n * similar, but non strictly equal, inputs (eg. normalized / non-normalized).\n * @see {@link resolve}\n */\n private readonly resolveExternal = memoize(\n async (fullRef: string): Promise<ResolvedRef> => {\n const [nsid, hash] = fullRef.split('#')\n const moduleSpecifier = `${asRelativePath(\n this.file.getDirectoryPath(),\n join('/', ...nsid.split('.')),\n )}.defs${this.options.importExt ?? '.js'}`\n\n // Lets first make sure the referenced lexicon exists\n const srcDoc = await this.indexer.get(nsid)\n const srcDef = Object.hasOwn(srcDoc.defs, hash) ? srcDoc.defs[hash] : null\n if (!srcDef) {\n throw new Error(\n `Missing def \"${hash}\" in \"${nsid}\" (referenced from ${this.doc.id})`,\n )\n }\n\n // import * as <nsIdentifier> from './<moduleSpecifier>'\n const nsIdentifier = this.getNsIdentifier(nsid, moduleSpecifier)\n\n const publicIds = getPublicIdentifiers(hash)\n\n return {\n varName: isSafeIdentifier(publicIds.varName)\n ? `${nsIdentifier}.${publicIds.varName}`\n : `${nsIdentifier}[${JSON.stringify(publicIds.varName)}]`,\n typeName: `${nsIdentifier}.${publicIds.typeName}`,\n }\n },\n )\n\n private getNsIdentifier(nsid: string, moduleSpecifier: string) {\n const namespaceImportDeclaration =\n this.file.getImportDeclaration(\n (imp) =>\n !imp.isTypeOnly() &&\n imp.getModuleSpecifierValue() === moduleSpecifier &&\n imp.getNamespaceImport() != null,\n ) ||\n this.file.addImportDeclaration({\n moduleSpecifier,\n namespaceImport: this.computeSafeNamespaceIdentifierFor(nsid),\n })\n\n return namespaceImportDeclaration.getNamespaceImport()!.getText()\n }\n\n #nsIdentifiersCounters = new Map<string, number>()\n private computeSafeNamespaceIdentifierFor(nsid: string) {\n const baseName = nsidToIdentifier(nsid) || 'NS'\n\n let name = baseName\n while (this.isConflictingIdentifier(name)) {\n const count = this.#nsIdentifiersCounters.get(baseName) ?? 0\n this.#nsIdentifiersCounters.set(baseName, count + 1)\n name = `${baseName}$$${count}`\n }\n\n return name\n }\n\n private isConflictingIdentifier(name: string) {\n return (\n this.conflictsWithKeywords(name) ||\n this.conflictsWithUtils(name) ||\n this.conflictsWithLocalDefs(name) ||\n this.conflictsWithLocalDeclarations(name) ||\n this.conflictsWithImports(name)\n )\n }\n\n private conflictsWithKeywords(name: string) {\n return isReservedWord(name)\n }\n\n private conflictsWithUtils(name: string) {\n // Do not allow \"Main\" as imported ns identifier since it has a special\n // meaning in the context of lexicon definitions.\n if (name === 'Main') return true\n\n // When \"useRecordExport\" returns true, an export named \"Record\" will be\n // used in addition to the hash named export. So we need to make sure both\n // names are not conflicting with local variables.\n if (name === 'Record') return true\n\n // Utility functions generated for lexicon schemas are prefixed with \"$\"\n return name.startsWith('$')\n }\n\n private conflictsWithLocalDefs(name: string) {\n return Object.keys(this.doc.defs).some((hash) => {\n const identifier = toCamelCase(hash)\n\n // A safe identifier will be generated, no risk of conflict.\n if (!identifier) return false\n\n // The imported name conflicts with a local definition name\n if (identifier === name || `_${identifier}` === name) return true\n\n // The imported name conflicts with the type name of a local definition\n const typeName = ucFirst(identifier)\n if (typeName === name || `_${typeName}` === name) return true\n\n return false\n })\n }\n\n private conflictsWithLocalDeclarations(name: string) {\n return (\n this.file.getVariableDeclarations().some((v) => v.getName() === name) ||\n this.file\n .getVariableStatements()\n .some((vs) => vs.getDeclarations().some((d) => d.getName() === name)) ||\n this.file.getTypeAliases().some((t) => t.getName() === name) ||\n this.file.getInterfaces().some((i) => i.getName() === name) ||\n this.file.getClasses().some((c) => c.getName() === name) ||\n this.file.getFunctions().some((f) => f.getName() === name) ||\n this.file.getEnums().some((e) => e.getName() === name)\n )\n }\n\n private conflictsWithImports(name: string) {\n return this.file.getImportDeclarations().some(\n (imp) =>\n // import name from '...'\n imp.getDefaultImport()?.getText() === name ||\n // import * as name from '...'\n imp.getNamespaceImport()?.getText() === name ||\n imp.getNamedImports().some(\n (named) =>\n // import { name } from '...'\n // import { foo as name } from '...'\n (named.getAliasNode()?.getText() ?? named.getName()) === name,\n ),\n )\n }\n}\n\n/**\n * @see {@link https://atproto.com/specs/nsid NSID syntax spec}\n */\nfunction nsidToIdentifier(nsid: string) {\n const parts = nsid.split('.')\n\n // By default, try to keep only to the last two segments of the NSID as\n // contextual information. If those do not form a safe identifier (typically\n // because they start with a digit), try with more segments until we reach the\n // full NSID.\n for (let i = 2; i < parts.length; i++) {\n const identifier = toPascalCase(parts.slice(-i).join('.'))\n if (isSafeIdentifier(identifier)) return identifier\n }\n\n return undefined\n}\n\n/**\n * Generates predictable public identifiers for a given definition hash.\n *\n * @note The returned `typeName` is guaranteed to be a valid TypeScript\n * identifier. `varName` may not be a valid identifier (eg. if the hash contains\n * unsafe characters), and may need to be accessed using string indexing.\n */\nexport function getPublicIdentifiers(hash: string): ResolvedRef {\n const varName = hash\n // @NOTE Type names *must* be valid TypeScript identifiers (this is because,\n // unlike variable names, we cannot use string indexing to access exported\n // types).\n const typeName = toPascalCase(hash)\n if (!typeName || varName === typeName || !isSafeIdentifier(typeName)) {\n return { varName, typeName: `Def${typeName}` }\n }\n return { varName, typeName }\n}\n\nfunction asSafeDefinitionIdentifier(name: string) {\n if (\n startsWithLowerLetter(name) &&\n isSafeIdentifier(name) &&\n isSafeIdentifier(ucFirst(name))\n ) {\n return name\n }\n const camel = toCamelCase(name)\n if (isSafeIdentifier(camel) && isSafeIdentifier(ucFirst(camel))) {\n return camel\n }\n return undefined\n}\n"]}
1
+ {"version":3,"file":"ref-resolver.js","sourceRoot":"","sources":["../src/ref-resolver.ts"],"names":[],"mappings":";;;AA2UA,oDAkBC;;AA7VD,sEAAgC;AAChC,yCAAgC;AAGhC,6CAKqB;AACrB,uCAOkB;AAWlB;;;GAGG;AACH,MAAa,WAAW;IAEZ;IACA;IACA;IACA;IAJV,Y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BAAe,EAAC,IAAI,CAAC;QACrB,IAAA,kCAAqB,EAAC,IAAI,CAAC;QAC3B,IAAA,kCAAqB,EAAC,IAAA,iBAAO,EAAC,IAAI,CAAC,CAAC,EACpC,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;IACD,MAAM,KAAK,GAAG,IAAA,qBAAW,EAAC,IAAI,CAAC,CAAA;IAC/B,IAAI,IAAA,kCAAqB,EAAC,KAAK,CAAC,IAAI,IAAA,kCAAqB,EAAC,IAAA,iBAAO,EAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QAC1E,OAAO,KAAK,CAAA;IACd,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC","sourcesContent":["import assert from 'node:assert'\nimport { join } from 'node:path'\nimport { SourceFile } from 'ts-morph'\nimport { LexiconDocument, LexiconIndexer } from '@atproto/lex-document'\nimport {\n isGlobalIdentifier,\n isJsKeyword,\n isSafeLocalIdentifier,\n isValidJsIdentifier,\n} from './ts-lang.js'\nimport {\n asRelativePath,\n memoize,\n startsWithLower,\n toCamelCase,\n toPascalCase,\n ucFirst,\n} from './util.js'\n\nexport type RefResolverOptions = {\n importExt?: string\n}\n\nexport type ResolvedRef = {\n varName: string\n typeName: string\n}\n\n/**\n * Utility class to resolve lexicon references to TypeScript identifiers,\n * generating \"import\" statements as needed.\n */\nexport class RefResolver {\n constructor(\n private doc: LexiconDocument,\n private file: SourceFile,\n private indexer: LexiconIndexer,\n private options: RefResolverOptions,\n ) {}\n\n public readonly resolve = memoize(\n async (ref: string): Promise<ResolvedRef> => {\n const [nsid, hash = 'main'] = ref.split('#')\n\n if (nsid === '' || nsid === this.doc.id) {\n return this.resolveLocal(hash)\n } else {\n // @NOTE: Normalize (#main fragment) to ensure proper memoization\n const fullRef = `${nsid}#${hash}`\n return this.resolveExternal(fullRef)\n }\n },\n )\n\n #defCounters = new Map<string, number>()\n private nextSafeDefinitionIdentifier(name: string) {\n // use camelCase version of the hash as base name\n const nameSafe =\n startsWithLower(name) && isValidJsIdentifier(name)\n ? name\n : toCamelCase(name).replace(/^[0-9]+/g, '') || 'def'\n\n const count = this.#defCounters.get(nameSafe) ?? 0\n this.#defCounters.set(nameSafe, count + 1)\n\n // @NOTE We don't need to check against local declarations in the file here\n // since we are using a naming system that should guarantee no other\n // identifier has a <nameSafe>$<number> format (\"$\" cannot appear in\n // hashes so only *we* are generating such identifiers).\n\n const identifier = `${nameSafe}$${count}`\n\n assert(\n isValidJsIdentifier(identifier),\n `Unable to generate safe identifier for: \"${name}\"`,\n )\n\n return identifier\n }\n\n /**\n * @note The returned `typeName` and `varName` are *both* guaranteed to be\n * valid TypeScript identifiers.\n */\n public readonly resolveLocal = memoize(\n async (hash: string): Promise<ResolvedRef> => {\n const hashes = Object.keys(this.doc.defs)\n\n if (!hashes.includes(hash)) {\n throw new Error(`Definition ${hash} not found in ${this.doc.id}`)\n }\n\n // Because we are using predictable \"public\" identifiers for type names,\n // we need to ensure there are no conflicts between different definitions\n // in the same lexicon document.\n //\n // @NOTE It should be possible to implement a way to generate\n // non-conflicting type names for all public (type) identifiers in a\n // project. However, this would add a lot of complexity to the code\n // generation process, and the likelihood of such conflicts happening in\n // practice is very low, so we opt for a simpler approach of just throwing\n // an error if a conflict is detected.\n const pub = getPublicIdentifiers(hash)\n for (const otherHash of hashes) {\n if (otherHash === hash) continue\n const otherPub = getPublicIdentifiers(otherHash)\n if (otherPub.typeName === pub.typeName) {\n throw new Error(\n `Conflicting type names for definitions #${hash} and #${otherHash} in ${this.doc.id}`,\n )\n }\n }\n\n // Try to keep and identifier that resembles the original hash as identifier\n const safeIdentifier = asSafeDefinitionIdentifier(hash)\n\n // If the safe identifier is not conflicting with other definition names,\n // or reserved words, we can use it as-is. Otherwise, we need to generate\n // a unique safe identifier.\n const varName = safeIdentifier\n ? !hashes.some((otherHash) => {\n if (otherHash === hash) return false\n const otherIdentifier = asSafeDefinitionIdentifier(otherHash)\n return otherIdentifier === safeIdentifier\n })\n ? // Safe identifier can be used as-is as it does not conflict with\n // other definition names\n safeIdentifier\n : // In order to keep identifiers stable, we use the safe identifier\n // as base, and append a counter to avoid conflicts\n this.nextSafeDefinitionIdentifier(safeIdentifier)\n : // hash only contained unsafe characters, generate a safe one\n this.nextSafeDefinitionIdentifier(hash)\n\n const typeName = ucFirst(varName)\n assert(isSafeLocalIdentifier(typeName), 'Expected safe type identifier')\n assert(varName !== typeName, 'Variable and type name should be different')\n\n return { varName, typeName }\n },\n )\n\n /**\n * @note Since this is a memoized function, and is used to generate the name\n * of local variables, we should avoid returning different results for\n * similar, but non strictly equal, inputs (eg. normalized / non-normalized).\n * @see {@link resolve}\n */\n private readonly resolveExternal = memoize(\n async (fullRef: string): Promise<ResolvedRef> => {\n const [nsid, hash] = fullRef.split('#')\n const moduleSpecifier = `${asRelativePath(\n this.file.getDirectoryPath(),\n join('/', ...nsid.split('.')),\n )}.defs${this.options.importExt ?? '.js'}`\n\n // Lets first make sure the referenced lexicon exists\n const srcDoc = await this.indexer.get(nsid)\n const srcDef = Object.hasOwn(srcDoc.defs, hash) ? srcDoc.defs[hash] : null\n if (!srcDef) {\n throw new Error(\n `Missing def \"${hash}\" in \"${nsid}\" (referenced from ${this.doc.id})`,\n )\n }\n\n const publicIds = getPublicIdentifiers(hash)\n\n if (!isValidJsIdentifier(publicIds.typeName)) {\n // If <typeName> is not a valid identifier, we cannot access the type\n // using dot notation (<nsIdentifier>.<typeName>). Note that, unlike js\n // variables, types cannot be accessed using string indexing (like:\n // <nsIdentifier>['<typeName>']) because it generates TypeScript errors:\n //\n // > \"Cannot use namespace '<nsIdentifier>' as a type.\"\n\n // Instead the generated code should look like:\n // import { \"<unsafeTypeName>\" as <safeIdentifier> } from './<moduleSpecifier>'\n\n // Because it requires more complex management of local variables names,\n // and we don't expect this to actually happen with properly designed\n // lexicons documents, we do not support this for now.\n\n throw new Error(\n 'Import of definitions with unsafe type names is not supported',\n )\n }\n\n // import * as <nsIdentifier> from './<moduleSpecifier>'\n const nsIdentifier = this.getNsIdentifier(nsid, moduleSpecifier)\n\n return {\n varName: isValidJsIdentifier(publicIds.varName)\n ? `${nsIdentifier}.${publicIds.varName}`\n : `${nsIdentifier}[${JSON.stringify(publicIds.varName)}]`,\n typeName: `${nsIdentifier}.${publicIds.typeName}`,\n }\n },\n )\n\n private getNsIdentifier(nsid: string, moduleSpecifier: string) {\n const namespaceImportDeclaration =\n this.file.getImportDeclaration(\n (imp) =>\n !imp.isTypeOnly() &&\n imp.getModuleSpecifierValue() === moduleSpecifier &&\n imp.getNamespaceImport() != null,\n ) ||\n this.file.addImportDeclaration({\n moduleSpecifier,\n namespaceImport: this.computeSafeNamespaceIdentifierFor(nsid),\n })\n\n return namespaceImportDeclaration.getNamespaceImport()!.getText()\n }\n\n #nsIdentifiersCounters = new Map<string, number>()\n private computeSafeNamespaceIdentifierFor(nsid: string) {\n const baseName = nsidToIdentifier(nsid) || 'NS'\n\n let name = baseName\n while (this.isConflictingIdentifier(name)) {\n const count = this.#nsIdentifiersCounters.get(baseName) ?? 0\n this.#nsIdentifiersCounters.set(baseName, count + 1)\n name = `${baseName}$$${count}`\n }\n\n return name\n }\n\n private isConflictingIdentifier(name: string) {\n return (\n this.conflictsWithKeywords(name) ||\n this.conflictsWithUtils(name) ||\n this.conflictsWithLocalDefs(name) ||\n this.conflictsWithLocalDeclarations(name) ||\n this.conflictsWithImports(name)\n )\n }\n\n private conflictsWithKeywords(name: string) {\n return isJsKeyword(name) || isGlobalIdentifier(name)\n }\n\n private conflictsWithUtils(name: string) {\n // Do not allow \"Main\" as imported ns identifier since it has a special\n // meaning in the context of lexicon definitions.\n if (name === 'Main') return true\n\n // When \"useRecordExport\" returns true, an export named \"Record\" will be\n // used in addition to the hash named export. So we need to make sure both\n // names are not conflicting with local variables.\n if (name === 'Record') return true\n\n // Utility functions generated for lexicon schemas are prefixed with \"$\"\n return name.startsWith('$')\n }\n\n private conflictsWithLocalDefs(name: string) {\n return Object.keys(this.doc.defs).some((hash) => {\n const identifier = toCamelCase(hash)\n\n // A safe identifier will be generated, no risk of conflict.\n if (!identifier) return false\n\n // The imported name conflicts with a local definition name\n if (identifier === name || `_${identifier}` === name) return true\n\n // The imported name conflicts with the type name of a local definition\n const typeName = ucFirst(identifier)\n if (typeName === name || `_${typeName}` === name) return true\n\n return false\n })\n }\n\n private conflictsWithLocalDeclarations(name: string) {\n return (\n this.file.getVariableDeclarations().some((v) => v.getName() === name) ||\n this.file\n .getVariableStatements()\n .some((vs) => vs.getDeclarations().some((d) => d.getName() === name)) ||\n this.file.getTypeAliases().some((t) => t.getName() === name) ||\n this.file.getInterfaces().some((i) => i.getName() === name) ||\n this.file.getClasses().some((c) => c.getName() === name) ||\n this.file.getFunctions().some((f) => f.getName() === name) ||\n this.file.getEnums().some((e) => e.getName() === name)\n )\n }\n\n private conflictsWithImports(name: string) {\n return this.file.getImportDeclarations().some(\n (imp) =>\n // import name from '...'\n imp.getDefaultImport()?.getText() === name ||\n // import * as name from '...'\n imp.getNamespaceImport()?.getText() === name ||\n imp.getNamedImports().some(\n (named) =>\n // import { name } from '...'\n // import { foo as name } from '...'\n (named.getAliasNode()?.getText() ?? named.getName()) === name,\n ),\n )\n }\n}\n\n/**\n * @see {@link https://atproto.com/specs/nsid NSID syntax spec}\n */\nfunction nsidToIdentifier(nsid: string) {\n const parts = nsid.split('.')\n\n // By default, try to keep only to the last two segments of the NSID as\n // contextual information. If those do not form a safe identifier (typically\n // because they start with a digit), try with more segments until we reach the\n // full NSID.\n for (let i = 2; i < parts.length; i++) {\n const identifier = toPascalCase(parts.slice(-i).join('.'))\n if (isSafeLocalIdentifier(identifier)) return identifier\n }\n\n return undefined\n}\n\n/**\n * Generates predictable public identifiers for a given definition hash.\n *\n * @note The returned `typeName` is guaranteed to be a valid TypeScript\n * identifier. `varName` may not be a valid identifier (eg. if the hash contains\n * unsafe characters), and may need to be accessed using string indexing.\n */\nexport function getPublicIdentifiers(hash: string): ResolvedRef {\n const varName = hash\n\n // @NOTE we try to circumvent the issue of unsafe type names described in\n // `RefResolver.resolveExternal` by ensuring that type names are always safe\n // identifiers, even if it means changing them from the original hash.\n let typeName = toPascalCase(hash)\n\n if (varName === typeName || !isValidJsIdentifier(typeName)) {\n typeName = `TypeOf${typeName}`\n }\n\n assert(\n isValidJsIdentifier(typeName),\n `Unable to generate a predictable safe identifier for \"${hash}\"`,\n )\n\n return { varName, typeName }\n}\n\nfunction asSafeDefinitionIdentifier(name: string) {\n if (\n startsWithLower(name) &&\n isSafeLocalIdentifier(name) &&\n isSafeLocalIdentifier(ucFirst(name))\n ) {\n return name\n }\n const camel = toCamelCase(name)\n if (isSafeLocalIdentifier(camel) && isSafeLocalIdentifier(ucFirst(camel))) {\n return camel\n }\n return undefined\n}\n"]}
package/dist/ts-lang.d.ts CHANGED
@@ -1,11 +1,6 @@
1
1
  export declare function isJsKeyword(word: string): boolean;
2
2
  export declare function isGlobalIdentifier(word: string): boolean;
3
- export declare function isReservedWord(word: string): boolean;
4
- type SafeIdentifierOptions = {
5
- /** Defaults to `false` */
6
- allowGlobal?: boolean;
7
- };
8
- export declare function isSafeIdentifier(name: string, options?: SafeIdentifierOptions): boolean;
3
+ export declare function isSafeLocalIdentifier(name: string): boolean;
4
+ export declare function isValidJsIdentifier(name: string): boolean;
9
5
  export declare function asNamespaceExport(name: string): string;
10
- export {};
11
6
  //# sourceMappingURL=ts-lang.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ts-lang.d.ts","sourceRoot":"","sources":["../src/ts-lang.ts"],"names":[],"mappings":"AA+EA,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,WAEvC;AAwDD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,WAO9C;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,WAE1C;AAED,KAAK,qBAAqB,GAAG;IAC3B,0BAA0B;IAC1B,WAAW,CAAC,EAAE,OAAO,CAAA;CACtB,CAAA;AAED,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,qBAAqB,WAOhC;AAMD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,UAI7C"}
1
+ {"version":3,"file":"ts-lang.d.ts","sourceRoot":"","sources":["../src/ts-lang.ts"],"names":[],"mappings":"AA+EA,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,WAEvC;AAkDD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,WAE9C;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,WAEjD;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,WAM/C;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,UAE7C"}
package/dist/ts-lang.js CHANGED
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isJsKeyword = isJsKeyword;
4
4
  exports.isGlobalIdentifier = isGlobalIdentifier;
5
- exports.isReservedWord = isReservedWord;
6
- exports.isSafeIdentifier = isSafeIdentifier;
5
+ exports.isSafeLocalIdentifier = isSafeLocalIdentifier;
6
+ exports.isValidJsIdentifier = isValidJsIdentifier;
7
7
  exports.asNamespaceExport = asNamespaceExport;
8
8
  /**
9
9
  * JavaScript keywords
@@ -86,7 +86,14 @@ const JS_KEYWORDS = new Set([
86
86
  function isJsKeyword(word) {
87
87
  return JS_KEYWORDS.has(word);
88
88
  }
89
- const WELL_KNOWN_GLOBALS = new Set([
89
+ // Only important to list var/type names that are likely to be used in the
90
+ // generated code files.
91
+ const GLOBAL_IDENTIFIERS = new Set([
92
+ // import { l } from "@atproto/lex-schema"
93
+ 'l',
94
+ // JS Globals
95
+ 'self',
96
+ 'globalThis',
90
97
  // ESM
91
98
  'import',
92
99
  // CommonJS
@@ -95,19 +102,7 @@ const WELL_KNOWN_GLOBALS = new Set([
95
102
  'require',
96
103
  'module',
97
104
  'exports',
98
- // Jest
99
- 'afterAll',
100
- 'afterEach',
101
- 'assert',
102
- 'beforeAll',
103
- 'beforeEach',
104
- 'describe',
105
- 'expect',
106
- 'it',
107
- 'test',
108
- ]);
109
- const TYPE_SCRIPT_GLOBALS = new Set([
110
- // Primitives
105
+ // TS Primitives
111
106
  'any',
112
107
  'bigint',
113
108
  'boolean',
@@ -121,7 +116,7 @@ const TYPE_SCRIPT_GLOBALS = new Set([
121
116
  'undefined',
122
117
  'unknown',
123
118
  'void',
124
- // Utility types
119
+ // TS Utility types
125
120
  'Record',
126
121
  'Partial',
127
122
  'Readonly',
@@ -139,27 +134,17 @@ const TYPE_SCRIPT_GLOBALS = new Set([
139
134
  'Uncapitalize',
140
135
  ]);
141
136
  function isGlobalIdentifier(word) {
142
- return (
143
- // Should cover most common globals
144
- word in globalThis ||
145
- WELL_KNOWN_GLOBALS.has(word) ||
146
- TYPE_SCRIPT_GLOBALS.has(word));
147
- }
148
- function isReservedWord(word) {
149
- return isJsKeyword(word) || isGlobalIdentifier(word);
137
+ return GLOBAL_IDENTIFIERS.has(word);
150
138
  }
151
- function isSafeIdentifier(name, options) {
152
- if (!options?.allowGlobal && isGlobalIdentifier(name)) {
153
- return false;
154
- }
155
- return isValidJsIdentifier(name);
139
+ function isSafeLocalIdentifier(name) {
140
+ return !isGlobalIdentifier(name) && isValidJsIdentifier(name);
156
141
  }
157
142
  function isValidJsIdentifier(name) {
158
- return !isJsKeyword(name) && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
143
+ return (name.length > 0 &&
144
+ !isJsKeyword(name) &&
145
+ /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name));
159
146
  }
160
147
  function asNamespaceExport(name) {
161
- return isSafeIdentifier(name, { allowGlobal: true })
162
- ? name
163
- : JSON.stringify(name);
148
+ return isValidJsIdentifier(name) ? name : JSON.stringify(name);
164
149
  }
165
150
  //# sourceMappingURL=ts-lang.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ts-lang.js","sourceRoot":"","sources":["../src/ts-lang.ts"],"names":[],"mappings":";;AA+EA,k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I,EAAE,CAAC;QAClD,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;AAC1B,CAAC","sourcesContent":["/**\n * JavaScript keywords\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar}\n */\nconst JS_KEYWORDS = new Set([\n 'abstract',\n 'arguments',\n 'as',\n 'async',\n 'await',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'from',\n 'function',\n 'get',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'of',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'set',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'undefined',\n 'using',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n])\n\nexport function isJsKeyword(word: string) {\n return JS_KEYWORDS.has(word)\n}\n\nconst WELL_KNOWN_GLOBALS = new Set([\n // ESM\n 'import',\n // CommonJS\n '__dirname',\n '__filename',\n 'require',\n 'module',\n 'exports',\n // Jest\n 'afterAll',\n 'afterEach',\n 'assert',\n 'beforeAll',\n 'beforeEach',\n 'describe',\n 'expect',\n 'it',\n 'test',\n])\n\nconst TYPE_SCRIPT_GLOBALS = new Set([\n // Primitives\n 'any',\n 'bigint',\n 'boolean',\n 'declare',\n 'never',\n 'null',\n 'number',\n 'object',\n 'string',\n 'symbol',\n 'undefined',\n 'unknown',\n 'void',\n // Utility types\n 'Record',\n 'Partial',\n 'Readonly',\n 'Pick',\n 'Omit',\n 'Exclude',\n 'Extract',\n 'InstanceType',\n 'ReturnType',\n 'Required',\n 'ThisType',\n 'Uppercase',\n 'Lowercase',\n 'Capitalize',\n 'Uncapitalize',\n])\n\nexport function isGlobalIdentifier(word: string) {\n return (\n // Should cover most common globals\n word in globalThis ||\n WELL_KNOWN_GLOBALS.has(word) ||\n TYPE_SCRIPT_GLOBALS.has(word)\n )\n}\n\nexport function isReservedWord(word: string) {\n return isJsKeyword(word) || isGlobalIdentifier(word)\n}\n\ntype SafeIdentifierOptions = {\n /** Defaults to `false` */\n allowGlobal?: boolean\n}\n\nexport function isSafeIdentifier(\n name: string,\n options?: SafeIdentifierOptions,\n) {\n if (!options?.allowGlobal && isGlobalIdentifier(name)) {\n return false\n }\n\n return isValidJsIdentifier(name)\n}\n\nfunction isValidJsIdentifier(name: string) {\n return !isJsKeyword(name) && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n\nexport function asNamespaceExport(name: string) {\n return isSafeIdentifier(name, { allowGlobal: true })\n ? name\n : JSON.stringify(name)\n}\n"]}
1
+ {"version":3,"file":"ts-lang.js","sourceRoot":"","sources":["../src/ts-lang.ts"],"names":[],"mappings":";;AA+EA,kCAEC;AAkDD,gDAEC;AAED,sDAEC;AAED,kDAMC;AAED,8CAEC;AArJD;;;GAGG;AACH,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC;IAC1B,UAAU;IACV,WAAW;IACX,IAAI;IACJ,OAAO;IACP,OAAO;IACP,SAAS;IACT,OAAO;IACP,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,UAAU;IACV,UAAU;IACV,SAAS;IACT,QAAQ;IACR,IAAI;IACJ,QAAQ;IACR,MAAM;IACN,MAAM;IACN,MAAM;IACN,QAAQ;IACR,SAAS;IACT,OAAO;IACP,OAAO;IACP,SAAS;IACT,OAAO;IACP,KAAK;IACL,MAAM;IACN,UAAU;IACV,KAAK;IACL,MAAM;IACN,I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C;AAED,SAAgB,qBAAqB,CAAC,IAAY;IAChD,OAAO,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,mBAAmB,CAAC,IAAI,CAAC,CAAA;AAC/D,CAAC;AAED,SAAgB,mBAAmB,CAAC,IAAY;IAC9C,OAAO,CACL,IAAI,CAAC,MAAM,GAAG,CAAC;QACf,CAAC,WAAW,CAAC,IAAI,CAAC;QAClB,4BAA4B,CAAC,IAAI,CAAC,IAAI,CAAC,CACxC,CAAA;AACH,CAAC;AAED,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,OAAO,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;AAChE,CAAC","sourcesContent":["/**\n * JavaScript keywords\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar}\n */\nconst JS_KEYWORDS = new Set([\n 'abstract',\n 'arguments',\n 'as',\n 'async',\n 'await',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'from',\n 'function',\n 'get',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'of',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'set',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'undefined',\n 'using',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n])\n\nexport function isJsKeyword(word: string) {\n return JS_KEYWORDS.has(word)\n}\n\n// Only important to list var/type names that are likely to be used in the\n// generated code files.\nconst GLOBAL_IDENTIFIERS = new Set([\n // import { l } from \"@atproto/lex-schema\"\n 'l',\n // JS Globals\n 'self',\n 'globalThis',\n // ESM\n 'import',\n // CommonJS\n '__dirname',\n '__filename',\n 'require',\n 'module',\n 'exports',\n // TS Primitives\n 'any',\n 'bigint',\n 'boolean',\n 'declare',\n 'never',\n 'null',\n 'number',\n 'object',\n 'string',\n 'symbol',\n 'undefined',\n 'unknown',\n 'void',\n // TS Utility types\n 'Record',\n 'Partial',\n 'Readonly',\n 'Pick',\n 'Omit',\n 'Exclude',\n 'Extract',\n 'InstanceType',\n 'ReturnType',\n 'Required',\n 'ThisType',\n 'Uppercase',\n 'Lowercase',\n 'Capitalize',\n 'Uncapitalize',\n])\n\nexport function isGlobalIdentifier(word: string) {\n return GLOBAL_IDENTIFIERS.has(word)\n}\n\nexport function isSafeLocalIdentifier(name: string) {\n return !isGlobalIdentifier(name) && isValidJsIdentifier(name)\n}\n\nexport function isValidJsIdentifier(name: string) {\n return (\n name.length > 0 &&\n !isJsKeyword(name) &&\n /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n )\n}\n\nexport function asNamespaceExport(name: string) {\n return isValidJsIdentifier(name) ? name : JSON.stringify(name)\n}\n"]}
package/dist/util.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export declare function memoize<T extends (arg: string) => NonNullable<unknown> | null>(fn: T): T;
2
- export declare function startsWithLowerLetter(str: string): boolean;
2
+ export declare function startsWithLower(str: string): boolean;
3
3
  export declare function ucFirst(str: string): string;
4
4
  export declare function lcFirst(str: string): string;
5
5
  export declare function toPascalCase(str: string): string;
@@ -1 +1 @@
1
- {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAEA,wBAAgB,OAAO,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,MAAM,KAAK,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,EAC5E,EAAE,EAAE,CAAC,GACJ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W,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE/C;AAeD,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,UAKtD;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,WAG1C"}
package/dist/util.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.memoize = memoize;
4
- exports.startsWithLowerLetter = startsWithLowerLetter;
4
+ exports.startsWithLower = startsWithLower;
5
5
  exports.ucFirst = ucFirst;
6
6
  exports.lcFirst = lcFirst;
7
7
  exports.toPascalCase = toPascalCase;
@@ -23,7 +23,7 @@ function memoize(fn) {
23
23
  return result;
24
24
  });
25
25
  }
26
- function startsWithLowerLetter(str) {
26
+ function startsWithLower(str) {
27
27
  const code = str.charCodeAt(0);
28
28
  return code >= 97 && code <= 122; // 'a' to 'z'
29
29
  }
package/dist/util.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;AAEA,0BAWC;AAED,sDAGC;AAED,0BAEC;AAED,0BAEC;AAED,oCAEC;AAED,kCAEC;AAED,wCAEC;AAED,kCAEC;AAED,kCAEC;AAeD,wCAKC;AAED,0CAGC;AAvED,yCAAoC;AAEpC,SAAgB,OAAO,CACrB,EAAK;IAEL,MAAM,KAAK,GAAG,IAAI,GAAG,EAAuC,CAAA;IAC5D,OAAO,CAAC,CAAC,GAAW,EAAE,EAAE;QACtB,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAC7B,IAAI,MAAM,KAAK,SAAS;YAAE,OAAO,MAAM,CAAA;QACvC,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;QACtB,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;QACtB,OAAO,MAAM,CAAA;IACf,CAAC,CAA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D,OAAO,CAAC,sBAAsB,EAAE,OAAO,CAAC,CAAC,qBAAqB;SAC9D,OAAO,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC,kCAAkC;SACzE,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC,sCAAsC;SACrE,IAAI,EAAE,CAAA,CAAC,+BAA+B;IAEzC,OAAO,YAAY;QACjB,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,kBAAkB;QAC9C,CAAC,CAAC,EAAE,CAAA,CAAC,yCAAyC;AAClD,CAAC;AAED,SAAgB,cAAc,CAAC,IAAY,EAAE,EAAU;IACrD,MAAM,OAAO,GAAG,IAAA,oBAAQ,EAAC,IAAI,EAAE,EAAE,CAAC,CAAA;IAClC,OAAO,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC;QAC1D,CAAC,CAAC,OAAO;QACT,CAAC,CAAC,KAAK,OAAO,EAAE,CAAA;AACpB,CAAC;AAED,SAAgB,eAAe,CAAC,GAAW;IACzC,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;IAC9B,OAAO,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,CAAA,CAAC,aAAa;AAC/C,CAAC","sourcesContent":["import { relative } from 'node:path'\n\nexport function memoize<T extends (arg: string) => NonNullable<unknown> | null>(\n fn: T,\n): T {\n const cache = new Map<string, NonNullable<unknown> | null>()\n return ((arg: string) => {\n const cached = cache.get(arg)\n if (cached !== undefined) return cached\n const result = fn(arg)\n cache.set(arg, result)\n return result\n }) as T\n}\n\nexport function startsWithLowerLetter(str: string) {\n const code = str.charCodeAt(0)\n return code >= 97 && code <= 122 // 'a' to 'z'\n}\n\nexport function ucFirst(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1)\n}\n\nexport function lcFirst(str: string) {\n return str.charAt(0).toLowerCase() + str.slice(1)\n}\n\nexport function toPascalCase(str: string): string {\n return extractWords(str).map(toLowerCase).map(ucFirst).join('')\n}\n\nexport function toCamelCase(str: string): string {\n return lcFirst(toPascalCase(str))\n}\n\nexport function toConstantCase(str: string): string {\n return extractWords(str).map(toUpperCase).join('_')\n}\n\nexport function toLowerCase(str: string): string {\n return str.toLowerCase()\n}\n\nexport function toUpperCase(str: string): string {\n return str.toUpperCase()\n}\n\nfunction extractWords(str: string): string[] {\n const processedStr = str\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2') // split camelCase\n .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2') // split ALLCAPSWords\n .replace(/([0-9])([A-Za-z])/g, '$1 $2') // split number followed by letter\n .replace(/[^a-zA-Z0-9]+/g, ' ') // replace non-alphanumeric with space\n .trim() // trim leading/trailing spaces\n\n return processedStr\n ? processedStr.split(/\\s+/) // split by spaces\n : [] // Avoid returning [''] for empty strings\n}\n\nexport function asRelativePath(from: string, to: string) {\n const relPath = relative(from, to)\n return relPath.startsWith('./') || relPath.startsWith('../')\n ? relPath\n : `./${relPath}`\n}\n\nexport function startsWithDigit(str: string) {\n const code = str.charCodeAt(0)\n return code >= 48 && code <= 57 // '0' to '9'\n}\n"]}
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;AAEA,0BAWC;AAED,0CAGC;AAED,0BAEC;AAED,0BAEC;AAED,oCAEC;AAED,kCAEC;AAED,wCAEC;AAED,kCAEC;AAED,kCAEC;AAeD,wCAKC;AAED,0CAGC;AAvED,yCAAoC;AAEpC,SAAgB,OAAO,CACrB,EAAK;IAEL,MAAM,KAAK,GAAG,IAAI,GAAG,EAAuC,CAAA;IAC5D,OAAO,CAAC,CAAC,GAAW,EAAE,EAAE;QACtB,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAC7B,IAAI,MAAM,KAAK,SAAS;YAAE,OAAO,MAAM,CAAA;QACvC,MAAM,MAAM,GAAG,EA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AAED,SAAS,YAAY,CAAC,GAAW;IAC/B,MAAM,YAAY,GAAG,GAAG;SACrB,OAAO,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC,kBAAkB;SACzD,OAAO,CAAC,sBAAsB,EAAE,OAAO,CAAC,CAAC,qBAAqB;SAC9D,OAAO,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC,kCAAkC;SACzE,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC,sCAAsC;SACrE,IAAI,EAAE,CAAA,CAAC,+BAA+B;IAEzC,OAAO,YAAY;QACjB,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,kBAAkB;QAC9C,CAAC,CAAC,EAAE,CAAA,CAAC,yCAAyC;AAClD,CAAC;AAED,SAAgB,cAAc,CAAC,IAAY,EAAE,EAAU;IACrD,MAAM,OAAO,GAAG,IAAA,oBAAQ,EAAC,IAAI,EAAE,EAAE,CAAC,CAAA;IAClC,OAAO,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC;QAC1D,CAAC,CAAC,OAAO;QACT,CAAC,CAAC,KAAK,OAAO,EAAE,CAAA;AACpB,CAAC;AAED,SAAgB,eAAe,CAAC,GAAW;IACzC,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;IAC9B,OAAO,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,CAAA,CAAC,aAAa;AAC/C,CAAC","sourcesContent":["import { relative } from 'node:path'\n\nexport function memoize<T extends (arg: string) => NonNullable<unknown> | null>(\n fn: T,\n): T {\n const cache = new Map<string, NonNullable<unknown> | null>()\n return ((arg: string) => {\n const cached = cache.get(arg)\n if (cached !== undefined) return cached\n const result = fn(arg)\n cache.set(arg, result)\n return result\n }) as T\n}\n\nexport function startsWithLower(str: string) {\n const code = str.charCodeAt(0)\n return code >= 97 && code <= 122 // 'a' to 'z'\n}\n\nexport function ucFirst(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1)\n}\n\nexport function lcFirst(str: string) {\n return str.charAt(0).toLowerCase() + str.slice(1)\n}\n\nexport function toPascalCase(str: string): string {\n return extractWords(str).map(toLowerCase).map(ucFirst).join('')\n}\n\nexport function toCamelCase(str: string): string {\n return lcFirst(toPascalCase(str))\n}\n\nexport function toConstantCase(str: string): string {\n return extractWords(str).map(toUpperCase).join('_')\n}\n\nexport function toLowerCase(str: string): string {\n return str.toLowerCase()\n}\n\nexport function toUpperCase(str: string): string {\n return str.toUpperCase()\n}\n\nfunction extractWords(str: string): string[] {\n const processedStr = str\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2') // split camelCase\n .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2') // split ALLCAPSWords\n .replace(/([0-9])([A-Za-z])/g, '$1 $2') // split number followed by letter\n .replace(/[^a-zA-Z0-9]+/g, ' ') // replace non-alphanumeric with space\n .trim() // trim leading/trailing spaces\n\n return processedStr\n ? processedStr.split(/\\s+/) // split by spaces\n : [] // Avoid returning [''] for empty strings\n}\n\nexport function asRelativePath(from: string, to: string) {\n const relPath = relative(from, to)\n return relPath.startsWith('./') || relPath.startsWith('../')\n ? relPath\n : `./${relPath}`\n}\n\nexport function startsWithDigit(str: string) {\n const code = str.charCodeAt(0)\n return code >= 48 && code <= 57 // '0' to '9'\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/lex-builder",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "license": "MIT",
5
5
  "description": "TypeScript schema builder for AT Lexicons",
6
6
  "keywords": [
@@ -39,8 +39,8 @@
39
39
  "prettier": "^3.2.5",
40
40
  "ts-morph": "^27.0.0",
41
41
  "tslib": "^2.8.1",
42
- "@atproto/lex-document": "0.0.8",
43
- "@atproto/lex-schema": "0.0.7"
42
+ "@atproto/lex-document": "0.0.9",
43
+ "@atproto/lex-schema": "0.0.8"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@ts-morph/common": "^0.28.0",
@@ -1,4 +1,3 @@
1
- import assert from 'node:assert'
2
1
  import {
3
2
  JSDocStructure,
4
3
  OptionalKind,
@@ -37,7 +36,7 @@ import {
37
36
  ResolvedRef,
38
37
  getPublicIdentifiers,
39
38
  } from './ref-resolver.js'
40
- import { isSafeIdentifier } from './ts-lang.js'
39
+ import { asNamespaceExport } from './ts-lang.js'
41
40
 
42
41
  export type LexDefBuilderOptions = RefResolverOptions & {
43
42
  lib?: string
@@ -378,11 +377,6 @@ export class LexDefBuilder {
378
377
  const ref = await this.refResolver.resolveLocal(hash)
379
378
  const pub = getPublicIdentifiers(hash)
380
379
 
381
- // Fool-proofing
382
- assert(isSafeIdentifier(ref.varName), 'Expected safe type identifier')
383
- assert(isSafeIdentifier(ref.typeName), 'Expected safe type identifier')
384
- assert(isSafeIdentifier(pub.typeName), 'Expected safe type identifier')
385
-
386
380
  if (type) {
387
381
  this.file.addTypeAlias({
388
382
  name: ref.typeName,
@@ -395,7 +389,10 @@ export class LexDefBuilder {
395
389
  namedExports: [
396
390
  {
397
391
  name: ref.typeName,
398
- alias: ref.typeName === pub.typeName ? undefined : pub.typeName,
392
+ alias:
393
+ ref.typeName === pub.typeName
394
+ ? undefined
395
+ : asNamespaceExport(pub.typeName),
399
396
  },
400
397
  ],
401
398
  })
@@ -420,9 +417,7 @@ export class LexDefBuilder {
420
417
  alias:
421
418
  ref.varName === pub.varName
422
419
  ? undefined
423
- : isSafeIdentifier(pub.varName)
424
- ? pub.varName
425
- : JSON.stringify(pub.varName),
420
+ : asNamespaceExport(pub.varName),
426
421
  },
427
422
  ],
428
423
  })
@@ -2,11 +2,16 @@ import assert from 'node:assert'
2
2
  import { join } from 'node:path'
3
3
  import { SourceFile } from 'ts-morph'
4
4
  import { LexiconDocument, LexiconIndexer } from '@atproto/lex-document'
5
- import { isReservedWord, isSafeIdentifier } from './ts-lang.js'
5
+ import {
6
+ isGlobalIdentifier,
7
+ isJsKeyword,
8
+ isSafeLocalIdentifier,
9
+ isValidJsIdentifier,
10
+ } from './ts-lang.js'
6
11
  import {
7
12
  asRelativePath,
8
13
  memoize,
9
- startsWithLowerLetter,
14
+ startsWithLower,
10
15
  toCamelCase,
11
16
  toPascalCase,
12
17
  ucFirst,
@@ -48,13 +53,29 @@ export class RefResolver {
48
53
  )
49
54
 
50
55
  #defCounters = new Map<string, number>()
51
- private nextSafeDefinitionIdentifier(safeIdentifier: string) {
52
- const count = this.#defCounters.get(safeIdentifier) ?? 0
53
- this.#defCounters.set(safeIdentifier, count + 1)
56
+ private nextSafeDefinitionIdentifier(name: string) {
57
+ // use camelCase version of the hash as base name
58
+ const nameSafe =
59
+ startsWithLower(name) && isValidJsIdentifier(name)
60
+ ? name
61
+ : toCamelCase(name).replace(/^[0-9]+/g, '') || 'def'
62
+
63
+ const count = this.#defCounters.get(nameSafe) ?? 0
64
+ this.#defCounters.set(nameSafe, count + 1)
65
+
54
66
  // @NOTE We don't need to check against local declarations in the file here
55
67
  // since we are using a naming system that should guarantee no other
56
- // identifier has a <safeIdentifier>$<number> format.
57
- return `${safeIdentifier}$${count}`
68
+ // identifier has a <nameSafe>$<number> format ("$" cannot appear in
69
+ // hashes so only *we* are generating such identifiers).
70
+
71
+ const identifier = `${nameSafe}$${count}`
72
+
73
+ assert(
74
+ isValidJsIdentifier(identifier),
75
+ `Unable to generate safe identifier for: "${name}"`,
76
+ )
77
+
78
+ return identifier
58
79
  }
59
80
 
60
81
  /**
@@ -109,9 +130,10 @@ export class RefResolver {
109
130
  // as base, and append a counter to avoid conflicts
110
131
  this.nextSafeDefinitionIdentifier(safeIdentifier)
111
132
  : // hash only contained unsafe characters, generate a safe one
112
- this.nextSafeDefinitionIdentifier('def')
133
+ this.nextSafeDefinitionIdentifier(hash)
113
134
 
114
135
  const typeName = ucFirst(varName)
136
+ assert(isSafeLocalIdentifier(typeName), 'Expected safe type identifier')
115
137
  assert(varName !== typeName, 'Variable and type name should be different')
116
138
 
117
139
  return { varName, typeName }
@@ -141,13 +163,33 @@ export class RefResolver {
141
163
  )
142
164
  }
143
165
 
166
+ const publicIds = getPublicIdentifiers(hash)
167
+
168
+ if (!isValidJsIdentifier(publicIds.typeName)) {
169
+ // If <typeName> is not a valid identifier, we cannot access the type
170
+ // using dot notation (<nsIdentifier>.<typeName>). Note that, unlike js
171
+ // variables, types cannot be accessed using string indexing (like:
172
+ // <nsIdentifier>['<typeName>']) because it generates TypeScript errors:
173
+ //
174
+ // > "Cannot use namespace '<nsIdentifier>' as a type."
175
+
176
+ // Instead the generated code should look like:
177
+ // import { "<unsafeTypeName>" as <safeIdentifier> } from './<moduleSpecifier>'
178
+
179
+ // Because it requires more complex management of local variables names,
180
+ // and we don't expect this to actually happen with properly designed
181
+ // lexicons documents, we do not support this for now.
182
+
183
+ throw new Error(
184
+ 'Import of definitions with unsafe type names is not supported',
185
+ )
186
+ }
187
+
144
188
  // import * as <nsIdentifier> from './<moduleSpecifier>'
145
189
  const nsIdentifier = this.getNsIdentifier(nsid, moduleSpecifier)
146
190
 
147
- const publicIds = getPublicIdentifiers(hash)
148
-
149
191
  return {
150
- varName: isSafeIdentifier(publicIds.varName)
192
+ varName: isValidJsIdentifier(publicIds.varName)
151
193
  ? `${nsIdentifier}.${publicIds.varName}`
152
194
  : `${nsIdentifier}[${JSON.stringify(publicIds.varName)}]`,
153
195
  typeName: `${nsIdentifier}.${publicIds.typeName}`,
@@ -196,7 +238,7 @@ export class RefResolver {
196
238
  }
197
239
 
198
240
  private conflictsWithKeywords(name: string) {
199
- return isReservedWord(name)
241
+ return isJsKeyword(name) || isGlobalIdentifier(name)
200
242
  }
201
243
 
202
244
  private conflictsWithUtils(name: string) {
@@ -274,7 +316,7 @@ function nsidToIdentifier(nsid: string) {
274
316
  // full NSID.
275
317
  for (let i = 2; i < parts.length; i++) {
276
318
  const identifier = toPascalCase(parts.slice(-i).join('.'))
277
- if (isSafeIdentifier(identifier)) return identifier
319
+ if (isSafeLocalIdentifier(identifier)) return identifier
278
320
  }
279
321
 
280
322
  return undefined
@@ -289,26 +331,34 @@ function nsidToIdentifier(nsid: string) {
289
331
  */
290
332
  export function getPublicIdentifiers(hash: string): ResolvedRef {
291
333
  const varName = hash
292
- // @NOTE Type names *must* be valid TypeScript identifiers (this is because,
293
- // unlike variable names, we cannot use string indexing to access exported
294
- // types).
295
- const typeName = toPascalCase(hash)
296
- if (!typeName || varName === typeName || !isSafeIdentifier(typeName)) {
297
- return { varName, typeName: `Def${typeName}` }
334
+
335
+ // @NOTE we try to circumvent the issue of unsafe type names described in
336
+ // `RefResolver.resolveExternal` by ensuring that type names are always safe
337
+ // identifiers, even if it means changing them from the original hash.
338
+ let typeName = toPascalCase(hash)
339
+
340
+ if (varName === typeName || !isValidJsIdentifier(typeName)) {
341
+ typeName = `TypeOf${typeName}`
298
342
  }
343
+
344
+ assert(
345
+ isValidJsIdentifier(typeName),
346
+ `Unable to generate a predictable safe identifier for "${hash}"`,
347
+ )
348
+
299
349
  return { varName, typeName }
300
350
  }
301
351
 
302
352
  function asSafeDefinitionIdentifier(name: string) {
303
353
  if (
304
- startsWithLowerLetter(name) &&
305
- isSafeIdentifier(name) &&
306
- isSafeIdentifier(ucFirst(name))
354
+ startsWithLower(name) &&
355
+ isSafeLocalIdentifier(name) &&
356
+ isSafeLocalIdentifier(ucFirst(name))
307
357
  ) {
308
358
  return name
309
359
  }
310
360
  const camel = toCamelCase(name)
311
- if (isSafeIdentifier(camel) && isSafeIdentifier(ucFirst(camel))) {
361
+ if (isSafeLocalIdentifier(camel) && isSafeLocalIdentifier(ucFirst(camel))) {
312
362
  return camel
313
363
  }
314
364
  return undefined
package/src/ts-lang.ts CHANGED
@@ -81,7 +81,14 @@ export function isJsKeyword(word: string) {
81
81
  return JS_KEYWORDS.has(word)
82
82
  }
83
83
 
84
- const WELL_KNOWN_GLOBALS = new Set([
84
+ // Only important to list var/type names that are likely to be used in the
85
+ // generated code files.
86
+ const GLOBAL_IDENTIFIERS = new Set([
87
+ // import { l } from "@atproto/lex-schema"
88
+ 'l',
89
+ // JS Globals
90
+ 'self',
91
+ 'globalThis',
85
92
  // ESM
86
93
  'import',
87
94
  // CommonJS
@@ -90,20 +97,7 @@ const WELL_KNOWN_GLOBALS = new Set([
90
97
  'require',
91
98
  'module',
92
99
  'exports',
93
- // Jest
94
- 'afterAll',
95
- 'afterEach',
96
- 'assert',
97
- 'beforeAll',
98
- 'beforeEach',
99
- 'describe',
100
- 'expect',
101
- 'it',
102
- 'test',
103
- ])
104
-
105
- const TYPE_SCRIPT_GLOBALS = new Set([
106
- // Primitives
100
+ // TS Primitives
107
101
  'any',
108
102
  'bigint',
109
103
  'boolean',
@@ -117,7 +111,7 @@ const TYPE_SCRIPT_GLOBALS = new Set([
117
111
  'undefined',
118
112
  'unknown',
119
113
  'void',
120
- // Utility types
114
+ // TS Utility types
121
115
  'Record',
122
116
  'Partial',
123
117
  'Readonly',
@@ -136,40 +130,21 @@ const TYPE_SCRIPT_GLOBALS = new Set([
136
130
  ])
137
131
 
138
132
  export function isGlobalIdentifier(word: string) {
139
- return (
140
- // Should cover most common globals
141
- word in globalThis ||
142
- WELL_KNOWN_GLOBALS.has(word) ||
143
- TYPE_SCRIPT_GLOBALS.has(word)
144
- )
145
- }
146
-
147
- export function isReservedWord(word: string) {
148
- return isJsKeyword(word) || isGlobalIdentifier(word)
133
+ return GLOBAL_IDENTIFIERS.has(word)
149
134
  }
150
135
 
151
- type SafeIdentifierOptions = {
152
- /** Defaults to `false` */
153
- allowGlobal?: boolean
136
+ export function isSafeLocalIdentifier(name: string) {
137
+ return !isGlobalIdentifier(name) && isValidJsIdentifier(name)
154
138
  }
155
139
 
156
- export function isSafeIdentifier(
157
- name: string,
158
- options?: SafeIdentifierOptions,
159
- ) {
160
- if (!options?.allowGlobal && isGlobalIdentifier(name)) {
161
- return false
162
- }
163
-
164
- return isValidJsIdentifier(name)
165
- }
166
-
167
- function isValidJsIdentifier(name: string) {
168
- return !isJsKeyword(name) && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)
140
+ export function isValidJsIdentifier(name: string) {
141
+ return (
142
+ name.length > 0 &&
143
+ !isJsKeyword(name) &&
144
+ /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)
145
+ )
169
146
  }
170
147
 
171
148
  export function asNamespaceExport(name: string) {
172
- return isSafeIdentifier(name, { allowGlobal: true })
173
- ? name
174
- : JSON.stringify(name)
149
+ return isValidJsIdentifier(name) ? name : JSON.stringify(name)
175
150
  }
package/src/util.ts CHANGED
@@ -13,7 +13,7 @@ export function memoize<T extends (arg: string) => NonNullable<unknown> | null>(
13
13
  }) as T
14
14
  }
15
15
 
16
- export function startsWithLowerLetter(str: string) {
16
+ export function startsWithLower(str: string) {
17
17
  const code = str.charCodeAt(0)
18
18
  return code >= 97 && code <= 122 // 'a' to 'z'
19
19
  }