@modernrelay/orbit-omnigraph 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/codegen.ts","../src/codegen-cli.ts"],"names":[],"mappings":";;;;;;;AAoEA,IAAM,SAAA,GAA0C;AAAA,EAC9C,MAAA,EAAQ,QAAA;AAAA,EACR,IAAA,EAAM,QAAA;AAAA,EACN,IAAA,EAAM,SAAA;AAAA,EACN,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,GAAA,EAAK,QAAA;AAAA,EACL,IAAA,EAAM,QAAA;AAAA,EACN,QAAA,EAAU;AACZ,CAAA;AAGA,SAAS,gBAAgB,KAAA,EAAuB;AAC9C,EAAA,OAAO,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAA,EAAO,MAAM,EAAE,OAAA,CAAQ,IAAA,EAAM,KAAK,CAAA,CAAE,QAAQ,KAAA,EAAO,KAAK,EAAE,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAC,CAAA,CAAA,CAAA;AAC1G;AAEA,SAAS,OAAO,IAAA,EAAsB;AACpC,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,EAAU,OAAO,UAAU,IAAI,CAAA;AACnD,EAAA,QAAQ,KAAK,IAAA;AAAM,IACjB,KAAK,QAAA;AACH,MAAA,OAAO,UAAA;AAAA,IACT,KAAK,MAAA;AACH,MAAA,OAAO,IAAA,CAAK,MAAA,CAAO,MAAA,KAAW,CAAA,GAAI,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,eAAe,CAAA,CAAE,IAAA,CAAK,KAAK,CAAA;AAAA,IAC1F,KAAK,MAAA;AACH,MAAA,OAAO,CAAA,EAAG,SAAA,CAAU,IAAA,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AAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAE,IAAA;AAAA,EAC1B,CAAC,IAAA,KAAS;AACR,IAAA,OAAA,CAAQ,QAAA,GAAW,IAAA;AAAA,EACrB,CAAA;AAAA,EACA,CAAC,GAAA,KAAiB;AAChB,IAAA,MAAM,UAAU,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC/D,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,yBAAA,EAA4B,OAAO;AAAA,CAAI,CAAA;AAC5D,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF,CAAA","file":"codegen-cli.js","sourcesContent":["/**\n * `.pg` → TypeScript code generation.\n *\n * The `.pg` scalar set is closed, so typed attrs for the `N`/`E` generics\n * generate mechanically: one interface per node/edge type, a `NodeAttrs` /\n * `EdgeAttrs` discriminated union on the adapter-injected `'orbit:type'`\n * field (namespaced so a schema's own `type` property emits as an ordinary\n * member), and a `TypeMap` lookup interface.\n *\n * Generated shapes describe attrs **after** the adapter's wire normalization\n * (the v1 loader rewrites export-path wire values to the query-path string\n * forms before populating attrs — see `normalize.ts`), so one encoding holds\n * regardless of read path:\n *\n * `Date` → `string` (`'YYYY-MM-DD'`)\n * `DateTime` → `string` (ISO 8601, `'YYYY-MM-DDTHH:MM:SS.mmmZ'`)\n * `enum(...)` → string-literal union\n * `I64`/`U64` → `number` (beware silent rounding past ±2^53)\n * `F32`/`F64` → `number`\n * `Vector(n)` → `number[]`\n * `Blob` → `string` (`data:` URI for inline blobs, stored URI refs verbatim)\n * `T?` → `T | null`\n *\n * Output is a self-contained module (no imports), safe under the strictest\n * tsconfig (`strict`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`,\n * `isolatedModules`). The file carries a DO-NOT-EDIT header with the\n * schema fingerprint. Generation is deterministic — no timestamps — so the\n * output is committable and diff-stable.\n *\n * Browser-safe: no `node:` imports (the CLI wrapper in `codegen-cli.ts` owns\n * file I/O).\n */\n\nimport { ORBIT_TYPE_KEY } from './normalize';\nimport {\n parsePgSchema,\n schemaFingerprint,\n type PgProperty,\n type PgScalarName,\n type PgSchema,\n type PgType,\n} from './pgSchema';\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface GenerateTypesOptions {\n /**\n * Extra provenance lines for the DO-NOT-EDIT banner (e.g. the schema file\n * path or server URL). May be multi-line; lines are comment-prefixed as\n * needed.\n */\n header?: string;\n /**\n * The schema fingerprint of the `.pg` **source** (from\n * {@link schemaFingerprint}). When omitted, a fingerprint of the canonical\n * parsed model is used instead and labelled as such — prefer\n * {@link generateTypesFromPgSource}, which always stamps the source\n * fingerprint.\n */\n fingerprint?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Wire value → TypeScript mapping (post-normalization)\n// ---------------------------------------------------------------------------\n\nconst SCALAR_TS: Record<PgScalarName, string> = {\n String: 'string',\n Blob: 'string',\n Bool: 'boolean',\n I32: 'number',\n I64: 'number',\n U32: 'number',\n U64: 'number',\n F32: 'number',\n F64: 'number',\n Date: 'string',\n DateTime: 'string',\n};\n\n/** Single-quoted TS string literal with escapes. */\nfunction tsStringLiteral(value: string): string {\n return `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\r/g, '\\\\r').replace(/\\n/g, '\\\\n')}'`;\n}\n\nfunction tsType(type: PgType): string {\n if (typeof type === 'string') return SCALAR_TS[type];\n switch (type.kind) {\n case 'vector':\n return 'number[]';\n case 'enum':\n return type.values.length === 0 ? 'string' : type.values.map(tsStringLiteral).join(' | ');\n case 'list':\n return `${SCALAR_TS[type.element]}[]`;\n case 'unknown':\n return 'unknown';\n }\n}\n\n/** One-line doc note for types whose TS shape hides a wire subtlety. */\nfunction wireNote(type: PgType): string | null {\n if (typeof type === 'string') {\n switch (type) {\n case 'Date':\n return \"`Date` — normalized to 'YYYY-MM-DD' (UTC) on load.\";\n case 'DateTime':\n return '`DateTime` — normalized to ISO 8601 UTC on load.';\n case 'Blob':\n return \"`Blob` — `data:` URI for inline blobs, stored URI refs verbatim.\";\n case 'I64':\n case 'U64':\n return `\\`${type}\\` — JSON numbers round silently past ±2^53.`;\n default:\n return null;\n }\n }\n switch (type.kind) {\n case 'vector':\n return `\\`Vector(${type.dim})\\`.`;\n case 'unknown':\n return `Unrecognized \\`.pg\\` type \\`${type.raw}\\` — value passes through verbatim.`;\n default:\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Emission helpers\n// ---------------------------------------------------------------------------\n\nconst IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nfunction propertyKey(name: string): string {\n return IDENT_RE.test(name) ? name : tsStringLiteral(name);\n}\n\nfunction emitProperty(lines: string[], prop: PgProperty): void {\n const note = wireNote(prop.type);\n if (note !== null) lines.push(` /** ${note} */`);\n const base = tsType(prop.type);\n lines.push(` ${propertyKey(prop.name)}: ${prop.optional ? `${base} | null` : base};`);\n}\n\nfunction emitPropsInterface(\n lines: string[],\n interfaceName: string,\n kindLabel: 'node' | 'edge',\n typeName: string,\n properties: readonly PgProperty[],\n): void {\n lines.push(`/** Normalized attrs for ${kindLabel} type \\`${typeName}\\`. */`);\n lines.push(`export interface ${interfaceName} {`);\n if (!properties.some((p) => p.name === 'id')) {\n lines.push(\n ` /** Physical Omnigraph id — injected into every export line's \\`data\\`; unique per ${kindLabel} type only. */`,\n );\n lines.push(' id: string;');\n }\n for (const prop of properties) {\n if (prop.name === 'id') {\n // Export normalization requires `data.id` to be a string regardless of\n // a schema declaration. Emitting the declared wire scalar here (for\n // example I64 -> number) would make generated attrs unsound.\n lines.push(\n ` /** Physical Omnigraph id — normalized as a required string regardless of its schema wire type. */`,\n );\n lines.push(' id: string;');\n continue;\n }\n // Every schema property emits normally — including one named `type`: the\n // adapter's discriminator lives at the namespaced ORBIT_TYPE_KEY, so\n // there is nothing to shadow.\n emitProperty(lines, prop);\n }\n lines.push('}');\n lines.push('');\n}\n\nfunction emitAttrsUnion(\n lines: string[],\n unionName: string,\n doc: string,\n members: ReadonlyArray<{ typeName: string; interfaceName: string }>,\n): void {\n lines.push(`/** ${doc} */`);\n if (members.length === 0) {\n lines.push(`export type ${unionName} = never;`);\n } else {\n lines.push(`export type ${unionName} =`);\n members.forEach(({ typeName, interfaceName }, i) => {\n const tail = i === members.length - 1 ? ';' : '';\n lines.push(\n ` | ({ ${tsStringLiteral(ORBIT_TYPE_KEY)}: ${tsStringLiteral(typeName)} } & ${interfaceName})${tail}`,\n );\n });\n }\n lines.push('');\n}\n\nfunction headerBanner(fingerprintLine: string, extra: string | undefined): string[] {\n const lines = [\n '// AUTO-GENERATED — DO NOT EDIT.',\n '//',\n '// .pg → TypeScript typed attrs (wire-normalized), generated by',\n '// @modernrelay/orbit-omnigraph (`orbit-omnigraph-codegen`).',\n `// ${fingerprintLine}`,\n ];\n if (extra !== undefined && extra.length > 0) {\n for (const raw of extra.split('\\n')) {\n lines.push(raw.startsWith('//') ? raw : `// ${raw}`.trimEnd());\n }\n }\n lines.push(\n '//',\n \"// Shapes describe attrs AFTER the adapter's wire normalization (both read\",\n '// paths converge on the query-path string encodings):',\n \"// Date → 'YYYY-MM-DD' · DateTime → ISO 8601 · enum(...) → literal union\",\n '// I64/U64/F32/F64 → number · Vector(n) → number[] · T? → T | null',\n \"// Blob → string ('data:' URI for inline blobs, stored URI for external)\",\n '',\n );\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a self-contained TypeScript module of typed attrs from a parsed\n * `.pg` schema: one `<Name>Props` interface per node type, one\n * `<Name>EdgeProps` per edge type (suffixed so a node and an edge sharing a\n * name cannot collide), `NodeAttrs`/`EdgeAttrs` discriminated unions on the\n * adapter-injected `'orbit:type'` field, and a `TypeMap` lookup interface with\n * `NodeTypeName`/`EdgeTypeName` key unions.\n *\n * Deterministic: identical input (schema + options) yields identical output.\n */\nexport function generateTypes(schema: PgSchema, opts?: GenerateTypesOptions): string {\n const fingerprintLine =\n opts?.fingerprint !== undefined\n ? `Schema fingerprint: ${opts.fingerprint}.`\n : `Schema fingerprint: ${schemaFingerprint(JSON.stringify(schema))} (parsed model — regenerate from .pg source for the source fingerprint).`;\n const lines = headerBanner(fingerprintLine, opts?.header);\n\n const nodeMembers = schema.nodes.map((n) => ({\n typeName: n.name,\n interfaceName: `${n.name}Props`,\n }));\n const edgeMembers = schema.edges.map((e) => ({\n typeName: e.name,\n interfaceName: `${e.name}EdgeProps`,\n }));\n\n schema.nodes.forEach((n, i) => {\n const member = nodeMembers[i];\n if (member) emitPropsInterface(lines, member.interfaceName, 'node', n.name, n.properties);\n });\n schema.edges.forEach((e, i) => {\n const member = edgeMembers[i];\n if (member) emitPropsInterface(lines, member.interfaceName, 'edge', e.name, e.properties);\n });\n\n emitAttrsUnion(\n lines,\n 'NodeAttrs',\n \"Discriminated union over every node type's normalized attrs — `'orbit:type'` is injected by the adapter.\",\n nodeMembers,\n );\n emitAttrsUnion(\n lines,\n 'EdgeAttrs',\n \"Discriminated union over every edge type's normalized attrs — `'orbit:type'` is the edge name.\",\n edgeMembers,\n );\n\n lines.push('/** Type-name → props lookup for both kinds (closed sets from the schema — the wire contract). */');\n lines.push('export interface TypeMap {');\n lines.push(' nodes: {');\n for (const m of nodeMembers) lines.push(` ${propertyKey(m.typeName)}: ${m.interfaceName};`);\n lines.push(' };');\n lines.push(' edges: {');\n for (const m of edgeMembers) lines.push(` ${propertyKey(m.typeName)}: ${m.interfaceName};`);\n lines.push(' };');\n lines.push('}');\n lines.push('');\n lines.push(\"export type NodeTypeName = keyof TypeMap['nodes'];\");\n lines.push(\"export type EdgeTypeName = keyof TypeMap['edges'];\");\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Parse `.pg` source and generate typed attrs (see {@link generateTypes}),\n * stamping the header with the source fingerprint\n * ({@link schemaFingerprint} over the verbatim source).\n */\nexport function generateTypesFromPgSource(\n source: string,\n opts?: Omit<GenerateTypesOptions, 'fingerprint'>,\n): string {\n const schema = parsePgSchema(source);\n const options: GenerateTypesOptions = { fingerprint: schemaFingerprint(source) };\n if (opts?.header !== undefined) options.header = opts.header;\n return generateTypes(schema, options);\n}\n","#!/usr/bin/env node\n/**\n * `orbit-omnigraph-codegen` — minimal `.pg` → TypeScript codegen CLI.\n *\n * orbit-omnigraph-codegen <schema.pg> [-o out.ts]\n * orbit-omnigraph-codegen --from-server <baseUrl> --graph <id> [-o out.ts]\n *\n * The first form reads a `.pg` file; the second fetches the active schema\n * from a running omnigraph-server via a plain **unauthenticated** SDK client\n * (`og.schema.get()` returns the raw `.pg` source). Authenticated client\n * construction stays exclusively in the `/server` entry; point\n * this tool at an `--unauthenticated` server or a same-origin proxy.\n *\n * Without `-o`, the generated module goes to stdout.\n */\n\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport process from 'node:process';\nimport { Omnigraph } from '@modernrelay/omnigraph';\nimport { generateTypesFromPgSource } from './codegen';\n\nconst USAGE = `Usage:\n orbit-omnigraph-codegen <schema.pg> [-o <out.ts>]\n orbit-omnigraph-codegen --from-server <baseUrl> --graph <id> [-o <out.ts>]\n\nGenerates TypeScript typed attrs from a .pg schema — read from a\nfile, or fetched from a running omnigraph-server (unauthenticated client).\nWrites to stdout unless -o is given.\n`;\n\ninterface CliArgs {\n schemaPath?: string;\n out?: string;\n fromServer?: string;\n graph?: string;\n}\n\nfunction parseArgs(argv: readonly string[]): CliArgs | string {\n const args: CliArgs = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === undefined) continue;\n switch (arg) {\n case '-h':\n case '--help':\n return 'help';\n case '-o':\n case '--out': {\n const v = argv[++i];\n if (v === undefined) return `missing value for ${arg}`;\n args.out = v;\n break;\n }\n case '--from-server': {\n const v = argv[++i];\n if (v === undefined) return 'missing value for --from-server';\n args.fromServer = v;\n break;\n }\n case '--graph': {\n const v = argv[++i];\n if (v === undefined) return 'missing value for --graph';\n args.graph = v;\n break;\n }\n default:\n if (arg.startsWith('-')) return `unknown option '${arg}'`;\n if (args.schemaPath !== undefined) return `unexpected argument '${arg}'`;\n args.schemaPath = arg;\n }\n }\n if (args.fromServer !== undefined && args.schemaPath !== undefined) {\n return 'pass a schema file OR --from-server, not both';\n }\n if (args.fromServer !== undefined && args.graph === undefined) {\n return '--from-server requires --graph <id> (schema reads are graph-scoped)';\n }\n if (args.fromServer === undefined && args.schemaPath === undefined) {\n return 'no schema given';\n }\n return args;\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n const parsed = parseArgs(argv);\n if (parsed === 'help') {\n process.stdout.write(USAGE);\n return 0;\n }\n if (typeof parsed === 'string') {\n process.stderr.write(`orbit-omnigraph-codegen: ${parsed}\\n\\n${USAGE}`);\n return 2;\n }\n\n let source: string;\n let provenance: string;\n if (parsed.fromServer !== undefined && parsed.graph !== undefined) {\n const og = new Omnigraph({ baseUrl: parsed.fromServer, graphId: parsed.graph });\n const schema = await og.schema.get();\n source = schema.schemaSource;\n provenance = `Source: ${parsed.fromServer} (graph '${parsed.graph}', GET /schema)`;\n } else if (parsed.schemaPath !== undefined) {\n source = readFileSync(parsed.schemaPath, 'utf8');\n provenance = `Source: ${parsed.schemaPath}`;\n } else {\n // Unreachable: parseArgs guarantees one of the two.\n return 2;\n }\n\n const output = generateTypesFromPgSource(source, { header: provenance });\n if (parsed.out !== undefined) {\n writeFileSync(parsed.out, output);\n process.stderr.write(`orbit-omnigraph-codegen: wrote ${parsed.out}\\n`);\n } else {\n process.stdout.write(output);\n }\n return 0;\n}\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`orbit-omnigraph-codegen: ${message}\\n`);\n process.exitCode = 1;\n },\n);\n"]}
1
+ {"version":3,"sources":["../src/codegen.ts","../src/codegen-cli.ts"],"names":[],"mappings":";;;;;;;AAoEA,IAAM,SAAA,GAA0C;AAAA,E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EAAA,MAAM,SAAS,yBAAA,CAA0B,MAAA,EAAQ,EAAE,MAAA,EAAQ,YAAY,CAAA;AACvE,EAAA,IAAI,MAAA,CAAO,QAAQ,MAAA,EAAW;AAC5B,IAAA,aAAA,CAAc,MAAA,CAAO,KAAK,MAAM,CAAA;AAChC,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,+BAAA,EAAkC,MAAA,CAAO,GAAG;AAAA,CAAI,CAAA;AAAA,EACvE,CAAA,MAAO;AACL,IAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,MAAM,CAAA;AAAA,EAC7B;AACA,EAAA,OAAO,CAAA;AACT;AAEA,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAE,IAAA;AAAA,EAC1B,CAAC,IAAA,KAAS;AACR,IAAA,OAAA,CAAQ,QAAA,GAAW,IAAA;AAAA,EACrB,CAAA;AAAA,EACA,CAAC,GAAA,KAAiB;AAChB,IAAA,MAAM,UAAU,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC/D,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,yBAAA,EAA4B,OAAO;AAAA,CAAI,CAAA;AAC5D,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF,CAAA","file":"codegen-cli.js","sourcesContent":["/**\n * `.pg` → TypeScript code generation.\n *\n * The `.pg` scalar set is closed, so typed attrs for the `N`/`E` generics\n * generate mechanically: one props type per node/edge type, a `NodeAttrs` /\n * `EdgeAttrs` discriminated union on the adapter-injected `'orbit:type'`\n * field (namespaced so a schema's own `type` property emits as an ordinary\n * member), and a `TypeMap` lookup interface.\n *\n * Generated shapes describe export-loaded attrs **after** the adapter's\n * wire normalization (see `normalize.ts`). Physical ids live on GraphNode\n * and GraphEdge, outside these attrs; a schema's own id property is ordinary data:\n *\n * `Date` → `string` (`'YYYY-MM-DD'`)\n * `DateTime` → `string` (ISO 8601, `'YYYY-MM-DDTHH:MM:SS.mmmZ'`)\n * `enum(...)` → string-literal union\n * `I64`/`U64` → `number` (beware silent rounding past ±2^53)\n * `F32`/`F64` → `number`\n * `Vector(n)` → `number[]`\n * `[T]` → `(T | null)[]` (stored list elements can be null)\n * `Blob` → `string` (`data:` URI for inline blobs, stored URI refs verbatim)\n * `T?` → `T | null`\n *\n * Output is a self-contained module (no imports), safe under the strictest\n * tsconfig (`strict`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`,\n * `isolatedModules`). The file carries a DO-NOT-EDIT header with the\n * schema fingerprint. Generation is deterministic — no timestamps — so the\n * output is committable and diff-stable.\n *\n * Browser-safe: no `node:` imports (the CLI wrapper in `codegen-cli.ts` owns\n * file I/O).\n */\n\nimport { ORBIT_TYPE_KEY } from './normalize';\nimport {\n parsePgSchema,\n schemaFingerprint,\n type PgProperty,\n type PgScalarName,\n type PgSchema,\n type PgType,\n} from './pgSchema';\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface GenerateTypesOptions {\n /**\n * Extra provenance lines for the DO-NOT-EDIT banner (e.g. the schema file\n * path or server URL). May be multi-line; lines are comment-prefixed as\n * needed.\n */\n header?: string;\n /**\n * The schema fingerprint of the `.pg` **source** (from\n * {@link schemaFingerprint}). When omitted, a fingerprint of the canonical\n * parsed model is used instead and labelled as such — prefer\n * {@link generateTypesFromPgSource}, which always stamps the source\n * fingerprint.\n */\n fingerprint?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Wire value → TypeScript mapping (post-normalization)\n// ---------------------------------------------------------------------------\n\nconst SCALAR_TS: Record<PgScalarName, string> = {\n String: 'string',\n Blob: 'string',\n Bool: 'boolean',\n I32: 'number',\n I64: 'number',\n U32: 'number',\n U64: 'number',\n F32: 'number',\n F64: 'number',\n Date: 'string',\n DateTime: 'string',\n};\n\n/** Single-quoted TS string literal with escapes. */\nfunction tsStringLiteral(value: string): string {\n return `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\r/g, '\\\\r').replace(/\\n/g, '\\\\n')}'`;\n}\n\nfunction tsType(type: PgType): string {\n if (typeof type === 'string') return SCALAR_TS[type];\n switch (type.kind) {\n case 'vector':\n return 'number[]';\n case 'enum':\n return type.values.length === 0 ? 'string' : type.values.map(tsStringLiteral).join(' | ');\n case 'list':\n return `(${SCALAR_TS[type.element]} | null)[]`;\n case 'unknown':\n return 'unknown';\n }\n}\n\n/** One-line doc note for types whose TS shape hides a wire subtlety. */\nfunction wireNote(type: PgType): string | null {\n if (typeof type === 'string') {\n switch (type) {\n case 'Date':\n return \"`Date` — normalized to 'YYYY-MM-DD' (UTC) on load.\";\n case 'DateTime':\n return '`DateTime` — normalized to ISO 8601 UTC on load.';\n case 'Blob':\n return \"`Blob` — `data:` URI for inline blobs, stored URI refs verbatim.\";\n case 'I64':\n case 'U64':\n return `\\`${type}\\` — JSON numbers round silently past ±2^53.`;\n default:\n return null;\n }\n }\n switch (type.kind) {\n case 'vector':\n return `\\`Vector(${type.dim})\\`.`;\n case 'unknown':\n return `Unrecognized \\`.pg\\` type \\`${type.raw}\\` — value passes through verbatim.`;\n default:\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Emission helpers\n// ---------------------------------------------------------------------------\n\nconst IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nfunction propertyKey(name: string): string {\n return IDENT_RE.test(name) ? name : tsStringLiteral(name);\n}\n\nfunction emitProperty(lines: string[], prop: PgProperty): void {\n const note = wireNote(prop.type);\n if (note !== null) lines.push(` /** ${note} */`);\n const base = tsType(prop.type);\n lines.push(` ${propertyKey(prop.name)}: ${prop.optional ? `${base} | null` : base};`);\n}\n\nfunction emitPropsInterface(\n lines: string[],\n interfaceName: string,\n kindLabel: 'node' | 'edge',\n typeName: string,\n properties: readonly PgProperty[],\n): void {\n lines.push(`/** Normalized attrs for ${kindLabel} type \\`${typeName}\\`. */`);\n if (properties.length === 0) {\n lines.push(`export type ${interfaceName} = object;`, '');\n return;\n }\n lines.push(`export interface ${interfaceName} {`);\n for (const prop of properties) {\n // Physical identity belongs to GraphNode/GraphEdge.id, outside attrs.\n // Schema properties named `id` and `type` retain their declared types.\n emitProperty(lines, prop);\n }\n lines.push('}');\n lines.push('');\n}\n\nfunction emitAttrsUnion(\n lines: string[],\n unionName: string,\n doc: string,\n members: ReadonlyArray<{ typeName: string; interfaceName: string }>,\n): void {\n lines.push(`/** ${doc} */`);\n if (members.length === 0) {\n lines.push(`export type ${unionName} = never;`);\n } else {\n lines.push(`export type ${unionName} =`);\n members.forEach(({ typeName, interfaceName }, i) => {\n const tail = i === members.length - 1 ? ';' : '';\n lines.push(\n ` | ({ ${tsStringLiteral(ORBIT_TYPE_KEY)}: ${tsStringLiteral(typeName)} } & ${interfaceName})${tail}`,\n );\n });\n }\n lines.push('');\n}\n\nfunction headerBanner(fingerprintLine: string, extra: string | undefined): string[] {\n const lines = [\n '// AUTO-GENERATED — DO NOT EDIT.',\n '//',\n '// .pg → TypeScript typed attrs (wire-normalized), generated by',\n '// @modernrelay/orbit-omnigraph (`orbit-omnigraph-codegen`).',\n `// ${fingerprintLine}`,\n ];\n if (extra !== undefined && extra.length > 0) {\n for (const raw of extra.split('\\n')) {\n lines.push(raw.startsWith('//') ? raw : `// ${raw}`.trimEnd());\n }\n }\n lines.push(\n '//',\n \"// Shapes describe export-loaded attrs AFTER the adapter's wire normalization:\",\n '// Physical entity ids live on GraphNode/GraphEdge, outside attrs.',\n \"// Date → 'YYYY-MM-DD' · DateTime → ISO 8601 UTC · enum(...) → literal union\",\n '// I64/U64/F32/F64 → number · Vector(n) → number[] · T? → T | null',\n '// [T] → (T | null)[] (null list elements are retained)',\n \"// Blob → string ('data:' URI for inline blobs, stored URI for external)\",\n '',\n );\n return lines;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a self-contained TypeScript module of typed attrs from a parsed\n * `.pg` schema: one `<Name>Props` type per node type, one\n * `<Name>EdgeProps` per edge type (with an additional numeric suffix when\n * either preferred name is already used), `NodeAttrs`/`EdgeAttrs` discriminated unions on the\n * adapter-injected `'orbit:type'` field, and a `TypeMap` lookup interface with\n * `NodeTypeName`/`EdgeTypeName` key unions.\n * Props with declared properties are interfaces; property-free props use `object`.\n *\n * Deterministic: identical input (schema + options) yields identical output.\n */\nexport function generateTypes(schema: PgSchema, opts?: GenerateTypesOptions): string {\n const fingerprintLine =\n opts?.fingerprint !== undefined\n ? `Schema fingerprint: ${opts.fingerprint}.`\n : `Schema fingerprint: ${schemaFingerprint(JSON.stringify(schema))} (parsed model — regenerate from .pg source for the source fingerprint).`;\n const lines = headerBanner(fingerprintLine, opts?.header);\n\n // Reserve every preferred name before allocating collision suffixes, so\n // disambiguating one member cannot steal a later member's public name.\n const reserved = new Set([\n 'NodeAttrs', 'EdgeAttrs', 'TypeMap', 'NodeTypeName', 'EdgeTypeName',\n ...schema.nodes.map((n) => `${n.name}Props`),\n ...schema.edges.map((e) => `${e.name}EdgeProps`),\n ]);\n const used = new Set<string>();\n function allocateName(preferred: string): string {\n let name = preferred;\n let suffix = 2;\n while (used.has(name)) {\n do {\n name = `${preferred}_${suffix++}`;\n } while (reserved.has(name));\n }\n used.add(name);\n return name;\n }\n const nodeMembers = schema.nodes.map((n) => ({\n typeName: n.name,\n interfaceName: allocateName(`${n.name}Props`),\n }));\n const edgeMembers = schema.edges.map((e) => ({\n typeName: e.name,\n interfaceName: allocateName(`${e.name}EdgeProps`),\n }));\n\n schema.nodes.forEach((n, i) => {\n const member = nodeMembers[i];\n if (member) emitPropsInterface(lines, member.interfaceName, 'node', n.name, n.properties);\n });\n schema.edges.forEach((e, i) => {\n const member = edgeMembers[i];\n if (member) emitPropsInterface(lines, member.interfaceName, 'edge', e.name, e.properties);\n });\n\n emitAttrsUnion(\n lines,\n 'NodeAttrs',\n \"Discriminated union over every node type's normalized attrs — `'orbit:type'` is injected by the adapter.\",\n nodeMembers,\n );\n emitAttrsUnion(\n lines,\n 'EdgeAttrs',\n \"Discriminated union over every edge type's normalized attrs — `'orbit:type'` is the edge name.\",\n edgeMembers,\n );\n\n lines.push('/** Type-name → props lookup for both kinds (closed sets from the schema — the wire contract). */');\n lines.push('export interface TypeMap {');\n lines.push(' nodes: {');\n for (const m of nodeMembers) lines.push(` ${propertyKey(m.typeName)}: ${m.interfaceName};`);\n lines.push(' };');\n lines.push(' edges: {');\n for (const m of edgeMembers) lines.push(` ${propertyKey(m.typeName)}: ${m.interfaceName};`);\n lines.push(' };');\n lines.push('}');\n lines.push('');\n lines.push(\"export type NodeTypeName = keyof TypeMap['nodes'];\");\n lines.push(\"export type EdgeTypeName = keyof TypeMap['edges'];\");\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Parse `.pg` source and generate typed attrs (see {@link generateTypes}),\n * stamping the header with the source fingerprint\n * ({@link schemaFingerprint} over the verbatim source).\n */\nexport function generateTypesFromPgSource(\n source: string,\n opts?: Omit<GenerateTypesOptions, 'fingerprint'>,\n): string {\n const schema = parsePgSchema(source);\n const options: GenerateTypesOptions = { fingerprint: schemaFingerprint(source) };\n if (opts?.header !== undefined) options.header = opts.header;\n return generateTypes(schema, options);\n}\n","#!/usr/bin/env node\n/**\n * `orbit-omnigraph-codegen` — minimal `.pg` → TypeScript codegen CLI.\n *\n * orbit-omnigraph-codegen <schema.pg> [-o out.ts]\n * orbit-omnigraph-codegen --from-server <baseUrl> --graph <id> [-o out.ts]\n *\n * The first form reads a `.pg` file; the second fetches the active schema\n * from a running omnigraph-server via a plain **unauthenticated** SDK client\n * (`og.schema.get()` returns the raw `.pg` source). Authenticated client\n * construction stays exclusively in the `/server` entry; point\n * this tool at an `--unauthenticated` server or a same-origin proxy.\n *\n * Without `-o`, the generated module goes to stdout.\n */\n\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport process from 'node:process';\nimport { Omnigraph } from '@modernrelay/omnigraph';\nimport { generateTypesFromPgSource } from './codegen';\n\nconst USAGE = `Usage:\n orbit-omnigraph-codegen <schema.pg> [-o <out.ts>]\n orbit-omnigraph-codegen --from-server <baseUrl> --graph <id> [-o <out.ts>]\n\nGenerates TypeScript typed attrs from a .pg schema — read from a\nfile, or fetched from a running omnigraph-server (unauthenticated client).\nWrites to stdout unless -o is given.\n`;\n\ninterface CliArgs {\n schemaPath?: string;\n out?: string;\n fromServer?: string;\n graph?: string;\n}\n\nfunction parseArgs(argv: readonly string[]): CliArgs | string {\n const args: CliArgs = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === undefined) continue;\n switch (arg) {\n case '-h':\n case '--help':\n return 'help';\n case '-o':\n case '--out': {\n const v = argv[++i];\n if (v === undefined) return `missing value for ${arg}`;\n args.out = v;\n break;\n }\n case '--from-server': {\n const v = argv[++i];\n if (v === undefined) return 'missing value for --from-server';\n args.fromServer = v;\n break;\n }\n case '--graph': {\n const v = argv[++i];\n if (v === undefined) return 'missing value for --graph';\n args.graph = v;\n break;\n }\n default:\n if (arg.startsWith('-')) return `unknown option '${arg}'`;\n if (args.schemaPath !== undefined) return `unexpected argument '${arg}'`;\n args.schemaPath = arg;\n }\n }\n if (args.fromServer !== undefined && args.schemaPath !== undefined) {\n return 'pass a schema file OR --from-server, not both';\n }\n if (args.fromServer !== undefined && args.graph === undefined) {\n return '--from-server requires --graph <id> (schema reads are graph-scoped)';\n }\n if (args.fromServer === undefined && args.schemaPath === undefined) {\n return 'no schema given';\n }\n return args;\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n const parsed = parseArgs(argv);\n if (parsed === 'help') {\n process.stdout.write(USAGE);\n return 0;\n }\n if (typeof parsed === 'string') {\n process.stderr.write(`orbit-omnigraph-codegen: ${parsed}\\n\\n${USAGE}`);\n return 2;\n }\n\n let source: string;\n let provenance: string;\n if (parsed.fromServer !== undefined && parsed.graph !== undefined) {\n const og = new Omnigraph({ baseUrl: parsed.fromServer, graphId: parsed.graph });\n const schema = await og.schema.get();\n source = schema.schemaSource;\n provenance = `Source: ${parsed.fromServer} (graph '${parsed.graph}', GET /schema)`;\n } else if (parsed.schemaPath !== undefined) {\n source = readFileSync(parsed.schemaPath, 'utf8');\n provenance = `Source: ${parsed.schemaPath}`;\n } else {\n // Unreachable: parseArgs guarantees one of the two.\n return 2;\n }\n\n const output = generateTypesFromPgSource(source, { header: provenance });\n if (parsed.out !== undefined) {\n writeFileSync(parsed.out, output);\n process.stderr.write(`orbit-omnigraph-codegen: wrote ${parsed.out}\\n`);\n } else {\n process.stdout.write(output);\n }\n return 0;\n}\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`orbit-omnigraph-codegen: ${message}\\n`);\n process.exitCode = 1;\n },\n);\n"]}
package/dist/index.d.ts CHANGED
@@ -24,8 +24,8 @@ interface DecodedSourceId {
24
24
  /**
25
25
  * Encode a `(kind, sourceId)` pair as a collision-proof orbit id.
26
26
  *
27
- * - Nodes: `encodeSourceId(NodeType, data.id)`
28
- * - Edges: `encodeSourceId(EdgeName, data.id)`; endpoints use
27
+ * - Nodes: `encodeSourceId(NodeType, id)` using the top-level export id
28
+ * - Edges: `encodeSourceId(EdgeName, id)` using the top-level export id; endpoints use
29
29
  * `encodeSourceId(endpointType, from|to)`.
30
30
  */
31
31
  declare function encodeSourceId(kind: string, sourceId: string): string;
@@ -166,10 +166,10 @@ interface BigIntKeyWarning {
166
166
  property: string;
167
167
  }
168
168
  /**
169
- * Find `I64`/`U64` properties used as identity (`@key` or named `id`). The
169
+ * Find `I64`/`U64` properties used as schema keys (`@key`). The
170
170
  * HTTP path emits native JSON numbers even past ±2^53, where `JSON.parse`
171
- * silently rounds them, so two distinct big-int ids can collapse. Surface
172
- * these hazards before loading.
171
+ * silently rounds them. Physical entity ids are separate strings and stay
172
+ * exact; warn that key attributes themselves may lose precision.
173
173
  */
174
174
  declare function bigIntKeyWarnings(schema: PgSchema): BigIntKeyWarning[];
175
175
 
@@ -185,22 +185,19 @@ declare function bigIntKeyWarnings(schema: PgSchema): BigIntKeyWarning[];
185
185
  * a schema's own `type` property passes through as ordinary data,
186
186
  * - edge endpoint types are resolved from the `.pg` schema because edge lines
187
187
  * carry bare `from`/`to` ids,
188
- * - attr values are normalized to the query-path string forms so
189
- * generated types and temporal dimensions see one encoding
190
- * regardless of read path:
191
- * * `Date` — export sends **days since Unix epoch** (number) →
192
- * `'YYYY-MM-DD'` (UTC)
193
- * * `DateTime` — export sends **epoch milliseconds** (number) →
194
- * ISO 8601 (`'YYYY-MM-DDTHH:MM:SS.mmmZ'`)
188
+ * - attr values are normalized for generated types and temporal dimensions:
189
+ * * `Date` — export sends `'YYYY-MM-DD'`; signed years use ISO's six digits
190
+ * * `DateTime` — export sends a UTC string without a timezone suffix →
191
+ * ISO 8601 with explicit UTC (`'YYYY-MM-DDTHH:MM:SS.mmmZ'`)
195
192
  * * `Blob` — inline internal blobs arrive as `'base64:<data>'` →
196
193
  * `'data:application/octet-stream;base64,<data>'`;
197
194
  * external-URI refs pass through verbatim
198
- * * everything else — verbatim.
195
+ * * missing nullable schema properties — explicit `null`
196
+ * * everything else — verbatim. Physical identity is top-level `id`;
197
+ * `data.id`, when present, is an ordinary user property.
199
198
  *
200
- * Non-finite float sentinels (`'NaN'`/`'Infinity'`/`'-Infinity'`) are a
201
- * **query-path-only** encoding: a non-finite stored float aborts `/export`
202
- * server-side, so export-loaded data never contains the sentinels.
203
- * This module therefore does NOT special-case them.
199
+ * The server rejects non-finite stored floats during export. Computed
200
+ * non-finite query values render as null; neither path uses string sentinels.
204
201
  */
205
202
 
206
203
  /** An edge line names an edge type the `.pg` schema does not declare. */
@@ -209,7 +206,7 @@ declare class UnknownEdgeTypeError extends Error {
209
206
  readonly edgeName: string;
210
207
  constructor(edgeName: string);
211
208
  }
212
- /** An export line is structurally unusable (e.g. missing/non-string `data.id`). */
209
+ /** An export line is structurally unusable (e.g. missing/non-string `id`). */
213
210
  declare class InvalidExportLineError extends Error {
214
211
  readonly name = "InvalidExportLineError";
215
212
  constructor(message: string);
@@ -217,11 +214,13 @@ declare class InvalidExportLineError extends Error {
217
214
  interface NodeExportLine {
218
215
  kind: 'node';
219
216
  type: string;
217
+ id: string;
220
218
  data: Record<string, unknown>;
221
219
  }
222
220
  interface EdgeExportLine {
223
221
  kind: 'edge';
224
222
  edge: string;
223
+ id: string;
225
224
  from: string;
226
225
  to: string;
227
226
  data: Record<string, unknown>;
@@ -231,9 +230,10 @@ type ClassifiedExportLine = NodeExportLine | EdgeExportLine | {
231
230
  };
232
231
  /**
233
232
  * Classify one parsed export line using the adapter's wire shapes:
234
- * - node line: `{"type": "<NodeType>", "data": {"id", …props}}`
235
- * - edge line: `{"edge": "<EdgeName>", "from": <src id>, "to": <dst id>, "data": {"id", …props}}`
236
- * Anything else is `{ kind: 'unknown' }`.
233
+ * - node line: `{"type": "<NodeType>", "id": <id>, "data": {…props}}`
234
+ * - edge line: `{"edge": "<EdgeName>", "id": <id>, "from": <src id>, "to": <dst id>, "data": {…props}}`
235
+ * Unknown envelopes return `{ kind: 'unknown' }`. Recognized entities without
236
+ * a physical identity reject instead of falling back to a user property.
237
237
  */
238
238
  declare function classifyExportLine(line: unknown): ClassifiedExportLine;
239
239
  /**
@@ -251,24 +251,26 @@ declare function classifyExportLine(line: unknown): ClassifiedExportLine;
251
251
  declare const ORBIT_TYPE_KEY = "orbit:type";
252
252
  /**
253
253
  * Normalize a node export line to a `GraphNode`:
254
- * `id = encodeSourceId(type, data.id)`, `attrs = { …data, 'orbit:type' }`
254
+ * `id = encodeSourceId(type, id)`, `attrs = { …data, 'orbit:type' }`
255
255
  * with value normalization driven by the schema's property types. A node type
256
256
  * absent from the schema is tolerated — its attrs pass through verbatim
257
257
  * (identity never needs the schema on the node path).
258
258
  */
259
259
  declare function normalizeNode(line: {
260
260
  type: string;
261
+ id: string;
261
262
  data: Record<string, unknown>;
262
263
  }, schema: PgSchema): GraphNode;
263
264
  /**
264
265
  * Normalize an edge export line to a `GraphEdge`:
265
- * `id = encodeSourceId(edge, data.id)`; `source`/`target` namespace the bare
266
+ * `id = encodeSourceId(edge, id)`; `source`/`target` namespace the bare
266
267
  * `from`/`to` ids with the endpoint node types resolved from the schema.
267
268
  * Throws {@link UnknownEdgeTypeError} when the schema does not declare
268
269
  * the edge — endpoint identity cannot be constructed without it.
269
270
  */
270
271
  declare function normalizeEdge(line: {
271
272
  edge: string;
273
+ id: string;
272
274
  from: string;
273
275
  to: string;
274
276
  data: Record<string, unknown>;
@@ -381,8 +383,9 @@ interface OmnigraphLoadResult {
381
383
  serverVersion: string;
382
384
  /**
383
385
  * Non-fatal observations: SDK/server major.minor mismatch, accepted
384
- * drift, big-int identity hazards, and skipped unknown lines. Never
385
- * hides a retry or accepted-drift decision.
386
+ * drift, big-int key attribute precision hazards, and skipped unknown
387
+ * lines. Never hides a retry or accepted-drift decision. HTTP API contract
388
+ * mismatches are fatal errors, not warnings.
386
389
  */
387
390
  warnings: string[];
388
391
  }
@@ -500,12 +503,12 @@ declare function createOmnigraphSource(options: OmnigraphSourceOptions): Omnigra
500
503
  */
501
504
 
502
505
  /** One stored-query result row: projection column → value. Bare-variable
503
- * projections (`return { $s }`) hold whole-node structs including `id`. */
506
+ * projections (`return { $s }`) hold whole-node structs including `@id`. */
504
507
  type OmnigraphSearchRow = Record<string, unknown>;
505
508
  /**
506
509
  * The required column→node-type mapping:
507
510
  *
508
- * - a record `{ '$s': 'Signal' }` — the FIRST listed column present in a row
511
+ * - a record `{ s: 'Signal' }` — the FIRST listed column present in a row
509
512
  * with a node struct supplies the physical id, encoded under the mapped
510
513
  * type name;
511
514
  * - or a per-row function returning the node type name — the row's first
@@ -544,4 +547,5 @@ interface OmnigraphSearchServiceOptions<N = Record<string, unknown>> {
544
547
  */
545
548
  declare function createOmnigraphSearchService<N = Record<string, unknown>>(options: OmnigraphSearchServiceOptions<N>): SearchService<N>;
546
549
 
547
- export { type BigIntKeyWarning, type ClassifiedExportLine, type DecodedSourceId, type EdgeExportLine, type IngestTarget, InvalidExportLineError, type NodeExportLine, ORBIT_TYPE_KEY, type OmnigraphDataRef, OmnigraphDriftError, type OmnigraphDriftPolicy, type OmnigraphLoadCounts, type OmnigraphLoadProgress, type OmnigraphLoadResult, type OmnigraphSearchRow, type OmnigraphSearchServiceOptions, type OmnigraphSearchTypeOf, type OmnigraphSource, type OmnigraphSourceOptions, type PgEdgeType, type PgInterfaceType, type PgNodeType, type PgProperty, type PgScalarName, type PgSchema, type PgType, UnknownEdgeTypeError, bigIntKeyWarnings, classifyExportLine, createOmnigraphSearchService, createOmnigraphSource, decodeSourceId, edgeEndpointTypes, encodeSourceId, encodeSyntheticEdgeId, normalizeEdge, normalizeNode, parsePgSchema, schemaFingerprint };
550
+ export { InvalidExportLineError, ORBIT_TYPE_KEY, OmnigraphDriftError, UnknownEdgeTypeError, bigIntKeyWarnings, classifyExportLine, createOmnigraphSearchService, createOmnigraphSource, decodeSourceId, edgeEndpointTypes, encodeSourceId, encodeSyntheticEdgeId, normalizeEdge, normalizeNode, parsePgSchema, schemaFingerprint };
551
+ export type { BigIntKeyWarning, ClassifiedExportLine, DecodedSourceId, EdgeExportLine, IngestTarget, NodeExportLine, OmnigraphDataRef, OmnigraphDriftPolicy, OmnigraphLoadCounts, OmnigraphLoadProgress, OmnigraphLoadResult, OmnigraphSearchRow, OmnigraphSearchServiceOptions, OmnigraphSearchTypeOf, OmnigraphSource, OmnigraphSourceOptions, PgEdgeType, PgInterfaceType, PgNodeType, PgProperty, PgScalarName, PgSchema, PgType };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { encodeSourceId, parsePgSchema, schemaFingerprint, bigIntKeyWarnings, classifyExportLine, normalizeNode, normalizeEdge } from './chunk-WMBDYPK2.js';
2
- export { InvalidExportLineError, ORBIT_TYPE_KEY, UnknownEdgeTypeError, bigIntKeyWarnings, classifyExportLine, decodeSourceId, edgeEndpointTypes, encodeSourceId, encodeSyntheticEdgeId, normalizeEdge, normalizeNode, parsePgSchema, schemaFingerprint } from './chunk-WMBDYPK2.js';
1
+ import { encodeSourceId, parsePgSchema, schemaFingerprint, bigIntKeyWarnings, classifyExportLine, normalizeNode, normalizeEdge } from './chunk-TFBKN675.js';
2
+ export { InvalidExportLineError, ORBIT_TYPE_KEY, UnknownEdgeTypeError, bigIntKeyWarnings, classifyExportLine, decodeSourceId, edgeEndpointTypes, encodeSourceId, encodeSyntheticEdgeId, normalizeEdge, normalizeNode, parsePgSchema, schemaFingerprint } from './chunk-TFBKN675.js';
3
3
  import { SERVER_VERSION, OmnigraphError } from '@modernrelay/omnigraph';
4
4
  import { OrbitOperationError } from '@modernrelay/orbit-core';
5
5
 
@@ -57,7 +57,8 @@ function throwIfAborted(signal) {
57
57
  function isAbortError(err) {
58
58
  return err instanceof Error && err.name === "AbortError";
59
59
  }
60
- function mapError(err) {
60
+ function mapError(err, signal) {
61
+ throwIfAborted(signal);
61
62
  if (err instanceof OmnigraphError && !isAbortError(err)) {
62
63
  return new Error(`omnigraph: ${err.name} (status ${err.status}): ${err.message}`);
63
64
  }
@@ -85,14 +86,13 @@ function createOmnigraphSource(options) {
85
86
  const client = options.client.graph(graphId);
86
87
  const datasetKey = typeNames === void 0 ? `og:${graphId}:${branch}` : `og:${graphId}:${branch}:types=${typeNames.join(",")}`;
87
88
  async function newestHead(signal) {
88
- const commits = await client.commits.list({ branch }, callOpts(signal));
89
- const newest = commits[0];
90
- if (newest === void 0) {
89
+ const { headCommitId } = await client.commits.list({ branch, limit: 1 }, callOpts(signal));
90
+ if (headCommitId == null) {
91
91
  throw new Error(
92
92
  `omnigraph: branch '${branch}' of graph '${graphId}' has no commits \u2014 nothing to export`
93
93
  );
94
94
  }
95
- return newest.graphCommitId;
95
+ return headCommitId;
96
96
  }
97
97
  async function runAttempt(target, signal, warnings, attempt) {
98
98
  throwIfAborted(signal);
@@ -104,7 +104,7 @@ function createOmnigraphSource(options) {
104
104
  for (const hazard of bigIntKeyWarnings(schema)) {
105
105
  pushUnique(
106
106
  warnings,
107
- `omnigraph: ${hazard.type}.${hazard.property} is a 64-bit integer used as identity \u2014 JSON parsing silently rounds values past \xB12^53, which can collapse distinct ids`
107
+ `omnigraph: ${hazard.type}.${hazard.property} is a 64-bit integer schema key \u2014 JSON parsing silently rounds attribute values past \xB12^53; physical ids remain exact strings`
108
108
  );
109
109
  }
110
110
  const provisionalRef = {
@@ -205,6 +205,7 @@ function createOmnigraphSource(options) {
205
205
  onProgress?.(buffered.progress);
206
206
  }
207
207
  bufferedBatches.length = 0;
208
+ throwIfAborted(signal);
208
209
  await finalSession.commit();
209
210
  }
210
211
  const exportInput = { branch, ...typeNames !== void 0 ? { typeNames } : {} };
@@ -240,6 +241,7 @@ function createOmnigraphSource(options) {
240
241
  }
241
242
  throwIfAborted(signal);
242
243
  const headAfter = await newestHead(signal);
244
+ throwIfAborted(signal);
243
245
  const counts = { lines, nodes: nodeCount, edges: edgeCount, bytes };
244
246
  if (driftPolicy === "accept-warn") {
245
247
  const finalRef = { ...provisionalRef, headAfter };
@@ -277,7 +279,7 @@ function createOmnigraphSource(options) {
277
279
  } catch {
278
280
  }
279
281
  }
280
- throw mapError(err);
282
+ throw mapError(err, signal);
281
283
  } finally {
282
284
  try {
283
285
  await iterator.return?.();
@@ -291,7 +293,7 @@ function createOmnigraphSource(options) {
291
293
  try {
292
294
  serverVersion = (await client.health(callOpts(signal))).version;
293
295
  } catch (err) {
294
- throw mapError(err);
296
+ throw mapError(err, signal);
295
297
  }
296
298
  const server = majorMinor(serverVersion);
297
299
  const sdk = majorMinor(SERVER_VERSION);
@@ -305,7 +307,7 @@ function createOmnigraphSource(options) {
305
307
  try {
306
308
  outcome = await runAttempt(target, signal, warnings, attempt);
307
309
  } catch (err) {
308
- throw mapError(err);
310
+ throw mapError(err, signal);
309
311
  }
310
312
  if (outcome.kind === "retry") continue;
311
313
  return {
@@ -340,7 +342,7 @@ function mapError2(err) {
340
342
  return err;
341
343
  }
342
344
  function isNodeStruct(value) {
343
- return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.id === "string";
345
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value["@id"] === "string";
344
346
  }
345
347
  function extractRows(response, queryName) {
346
348
  const rows = response.rows;
@@ -368,15 +370,15 @@ function resolveIdentity(row, typeOf, queryName) {
368
370
  }
369
371
  for (const key of Object.keys(row)) {
370
372
  const value = row[key];
371
- if (isNodeStruct(value)) return { kind, sourceId: value.id };
373
+ if (isNodeStruct(value)) return { kind, sourceId: value["@id"] };
372
374
  }
373
375
  throw new Error(
374
- `omnigraph: '${queryName}' search row has no node-struct column (an object with a string 'id') \u2014 project the matched entity bare (return { $s }) so its physical id is available`
376
+ `omnigraph: '${queryName}' search row has no node-struct column (an object with a string '@id') \u2014 project the matched entity bare (return { $s }) so its physical id is available`
375
377
  );
376
378
  }
377
379
  for (const [column, kind] of Object.entries(typeOf)) {
378
380
  const value = row[column];
379
- if (isNodeStruct(value)) return { kind, sourceId: value.id };
381
+ if (isNodeStruct(value)) return { kind, sourceId: value["@id"] };
380
382
  }
381
383
  throw new Error(
382
384
  `omnigraph: '${queryName}' search row has no node struct under the mapped column(s) ${JSON.stringify(Object.keys(typeOf))} \u2014 the typeOf record must key the columns that contain bare-variable node projections`
@@ -418,6 +420,7 @@ function createOmnigraphSearchService(options) {
418
420
  try {
419
421
  response = await client.queries.invoke(queryName, input, { signal: ctx.signal });
420
422
  } catch (err) {
423
+ throwIfAborted2(ctx.signal, queryName);
421
424
  throw mapError2(err);
422
425
  }
423
426
  throwIfAborted2(ctx.signal, queryName);