@rocicorp/zero 1.9.0-canary.0 → 1.9.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/out/z2s/src/compiler.d.ts.map +1 -1
  2. package/out/z2s/src/compiler.js +1 -22
  3. package/out/z2s/src/compiler.js.map +1 -1
  4. package/out/zero/package.js +1 -1
  5. package/out/zero/package.js.map +1 -1
  6. package/out/zero-cache/src/custom/fetch.js +1 -1
  7. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  8. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  9. package/out/zero-cache/src/services/litestream/commands.js +12 -26
  10. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  11. package/out/zero-cache/src/services/litestream/config.yml +3 -2
  12. package/out/zero-cache/src/services/replicator/change-processor.js +1 -1
  13. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  14. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  15. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  16. package/out/zero-client/src/client/version.js +1 -1
  17. package/out/zero-client/src/client/zero.d.ts +6 -7
  18. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  19. package/out/zero-client/src/client/zero.js +125 -85
  20. package/out/zero-client/src/client/zero.js.map +1 -1
  21. package/out/zero-server/src/custom.js +8 -2
  22. package/out/zero-server/src/custom.js.map +1 -1
  23. package/out/zero-server/src/schema.d.ts +8 -0
  24. package/out/zero-server/src/schema.d.ts.map +1 -1
  25. package/out/zero-server/src/schema.js +63 -24
  26. package/out/zero-server/src/schema.js.map +1 -1
  27. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  28. package/out/zql/src/query/query-delegate-base.js +5 -1
  29. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  30. package/out/zqlite/src/resolve-scalar-subqueries.d.ts.map +1 -1
  31. package/out/zqlite/src/resolve-scalar-subqueries.js +13 -1
  32. package/out/zqlite/src/resolve-scalar-subqueries.js.map +1 -1
  33. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"compiler.d.ts","sourceRoot":"","sources":["../../../../z2s/src/compiler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AAQ7C,OAAO,EAAC,KAAK,SAAS,EAAC,MAAM,0BAA0B,CAAC;AAExD,OAAO,KAAK,EACV,GAAG,EACH,KAAK,EAEL,kBAAkB,EAElB,WAAW,EAEX,QAAQ,EACR,eAAe,EAEhB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAEL,KAAK,UAAU,EAChB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,gCAAgC,CAAC;AAC3D,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,uCAAuC,CAAC;AACxE,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,2BAA2B,CAAC;AAUtD,KAAK,KAAK,GAAG;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,KAAK,eAAe,GAAG;IACrB,KAAK,EAAE,KAAK,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF,KAAK,UAAU,GAAG;IAChB,MAAM,EAAE,YAAY,CAAC;IAErB,MAAM,EAAE,UAAU,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,IAAI,GAAG;IACjB,MAAM,EAAE,UAAU,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAQF,wBAAgB,OAAO,CACrB,YAAY,EAAE,YAAY,EAC1B,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,GAAG,EACR,MAAM,CAAC,EAAE,MAAM,GACd,QAAQ,CAgBV;AAiDD,wBAAgB,KAAK,CACnB,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AAI,EAAE,IAAI,EACV,YAAY,EAAE,kBAAkB,GAC/B;IACD;QACE,KAAK,EAAE,KAAK,CAAC;QACb,WAAW,EAAE,WAAW,CAAC;QACzB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;KAC3B;IACD;QAAC,KAAK,EAAE,KAAK,CAAC;QAAC,WAAW,EAAE,WAAW,CAAC;QAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAA;KAAC;CACpE,CAsBA;AAyED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAMhE"}
@@ -125,9 +125,7 @@ function where(spec, condition, table) {
125
125
  switch (condition.type) {
126
126
  case "and": return sql`(${sql.join(condition.conditions.map((c) => where(spec, c, table)), " AND ")})`;
127
127
  case "or": return sql`(${sql.join(condition.conditions.map((c) => where(spec, c, table)), " OR ")})`;
128
- case "correlatedSubquery":
129
- if (condition.scalar) return scalarSubquery(spec, condition, table);
130
- return exists(spec, condition, table);
128
+ case "correlatedSubquery": return exists(spec, condition, table);
131
129
  case "simple": return simple(spec, condition, table);
132
130
  }
133
131
  }
@@ -143,25 +141,6 @@ function exists(spec, condition, parentTable) {
143
141
  })), condition.related.correlation.childField))})`;
144
142
  }
145
143
  }
146
- function scalarSubquery(spec, condition, parentTable) {
147
- const parentField = condition.related.correlation.parentField[0];
148
- const childField = condition.related.correlation.childField[0];
149
- const subqueryAST = condition.related.subquery;
150
- const parentCol = colIdent(spec.server, {
151
- table: parentTable,
152
- zql: parentField
153
- });
154
- const subqueryTable = makeTable(spec, subqueryAST.table);
155
- const childCol = colIdent(spec.server, {
156
- table: subqueryTable,
157
- zql: childField
158
- });
159
- const op = sql.__dangerous__rawValue(condition.op === "EXISTS" ? "=" : "IS NOT");
160
- const subqueryConditions = subqueryAST.where ? [where(spec, subqueryAST.where, subqueryTable)] : [];
161
- if (subqueryAST.start) subqueryConditions.push(start(spec, subqueryAST.start, subqueryAST.orderBy, subqueryTable));
162
- const subqueryOrderBy = orderBy(spec, subqueryAST.orderBy, subqueryTable);
163
- return sql`${parentCol} ${op} (SELECT ${childCol} FROM ${fromIdent(spec.server, subqueryTable)} ${subqueryConditions.length > 0 ? sql`WHERE ${sql.join(subqueryConditions, " AND ")}` : sql``} ${subqueryOrderBy} LIMIT 1)`;
164
- }
165
144
  function makeCorrelator(spec, parentFields, childZqlFields) {
166
145
  return (childTable) => {
167
146
  const childFields = childZqlFields.map((zqlField) => ({
@@ -1 +1 @@
1
- {"version":3,"file":"compiler.js","names":[],"sources":["../../../../z2s/src/compiler.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport {last, zip} from '../../shared/src/arrays.ts';\nimport {assert, unreachable} from '../../shared/src/asserts.ts';\nimport {\n parse as parseBigIntJson,\n type JSONValue as BigIntJSONValue,\n} from '../../shared/src/bigint-json.ts';\nimport {hasOwn} from '../../shared/src/has-own.ts';\nimport {type JSONValue} from '../../shared/src/json.ts';\nimport {must} from '../../shared/src/must.ts';\nimport type {\n AST,\n Bound,\n Condition,\n CorrelatedSubquery,\n CorrelatedSubqueryCondition,\n Correlation,\n LiteralReference,\n Ordering,\n SimpleCondition,\n ValuePosition,\n} from '../../zero-protocol/src/ast.ts';\nimport {\n clientToServer,\n type NameMapper,\n} from '../../zero-schema/src/name-mapper.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {ServerSchema} from '../../zero-types/src/server-schema.ts';\nimport type {Format} from '../../zql/src/ivm/view.ts';\nimport {completeOrdering} from '../../zql/src/query/complete-ordering.ts';\nimport {\n sql,\n sqlConvertColumnArg,\n sqlConvertPluralLiteralArg,\n sqlConvertSingularLiteralArg,\n type PluralLiteralType,\n} from './sql.ts';\n\ntype Table = {\n zql: string;\n alias: string;\n};\n\ntype QualifiedColumn = {\n table: Table;\n zql: string;\n};\n\ntype ServerSpec = {\n schema: ServerSchema;\n // maps zql names to server names\n mapper: NameMapper;\n};\n\nexport type Spec = {\n server: ServerSpec;\n zql: Schema['tables'];\n aliasCount: number;\n};\n\nconst ZQL_RESULT_KEY = 'zql_result';\nconst ZQL_RESULT_KEY_IDENT = sql.ident(ZQL_RESULT_KEY);\n\nconst ZQL_RESULT_TABLE_KEY = 'zql_root';\nconst ZQL_RESULT_TABLE_IDENT = sql.ident(ZQL_RESULT_TABLE_KEY);\n\nexport function compile(\n serverSchema: ServerSchema,\n zqlSchema: Schema,\n ast: AST,\n format?: Format,\n): SQLQuery {\n ast = completeOrdering(\n ast,\n tableName => zqlSchema.tables[tableName].primaryKey,\n );\n const spec: Spec = {\n aliasCount: 0,\n server: {\n schema: serverSchema,\n mapper: clientToServer(zqlSchema.tables),\n },\n zql: zqlSchema.tables,\n };\n return sql`SELECT \n ${toJSON(ZQL_RESULT_TABLE_KEY, format?.singular)}::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${select(spec, ast, format)}) ${ZQL_RESULT_TABLE_IDENT}`;\n}\n\nfunction select(\n spec: Spec,\n ast: AST,\n format: Format | undefined,\n correlate?: (childTable: Table) => SQLQuery,\n): SQLQuery {\n const table = makeTable(spec, ast.table);\n const selectionSet = related(spec, ast.related ?? [], format, table);\n const tableSchema = spec.zql[ast.table];\n const usedAliases = new Set<string>(\n ast.related?.map(r => r.subquery.alias ?? ''),\n );\n for (const column of Object.keys(tableSchema.columns)) {\n if (!usedAliases.has(column)) {\n selectionSet.push(\n selectIdent(spec.server, {\n table,\n zql: column,\n }),\n );\n }\n }\n\n let appliedWhere = false;\n function maybeWhere(test: unknown) {\n if (!test) {\n return sql``;\n }\n\n const ret = appliedWhere ? sql`AND` : sql`WHERE`;\n appliedWhere = true;\n return ret;\n }\n\n return sql`SELECT ${sql.join(selectionSet, ',')}\n FROM ${fromIdent(spec.server, table)}\n ${maybeWhere(ast.where)} ${where(spec, ast.where, table)}${\n ast.start\n ? sql`\n ${maybeWhere(ast.start)} ${start(spec, ast.start, ast.orderBy, table)}`\n : sql``\n }\n ${maybeWhere(correlate)} ${correlate ? correlate(table) : sql``}\n ${orderBy(spec, ast.orderBy, table)}\n ${limit(ast.limit, format?.singular)}`;\n}\n\nexport function limit(\n limit: number | undefined,\n singular: boolean | undefined,\n): SQLQuery {\n if (limit === 0) {\n return sql`LIMIT 0`;\n }\n if (singular) {\n return sql`LIMIT 1`;\n }\n if (limit === undefined) {\n return sql``;\n }\n return sql`LIMIT ${sqlConvertSingularLiteralArg(limit)}`;\n}\n\nfunction makeTable(spec: Spec, zql: string, alias?: string): Table {\n alias = alias ?? zql + '_' + spec.aliasCount++;\n return {\n zql,\n alias,\n };\n}\n\nexport function orderBy(\n spec: Spec,\n orderBy: Ordering | undefined,\n table: Table,\n): SQLQuery {\n if (!orderBy) {\n return sql``;\n }\n return sql`ORDER BY ${sql.join(\n orderBy.map(([col, dir]) =>\n dir === 'asc'\n ? // Oh postgres. The table must be referred to by client name but the column by server name.\n // E.g., `SELECT server_col as client_col FROM server_table as client_table ORDER BY client_Table.server_col`\n sql`${colIdent(spec.server, {\n table,\n zql: col,\n })} ASC NULLS FIRST`\n : sql`${colIdent(spec.server, {\n table,\n zql: col,\n })} DESC NULLS LAST`,\n ),\n ', ',\n )}`;\n}\n\nexport function start(\n spec: Spec,\n bound: Bound | undefined,\n orderBy: Ordering | undefined,\n table: Table,\n): SQLQuery {\n if (!bound) {\n return sql``;\n }\n assert(\n orderBy !== undefined && orderBy.length > 0,\n 'start requires ordering',\n );\n\n const constraints: SQLQuery[] = [];\n for (let i = 0; i < orderBy.length; i++) {\n const group: SQLQuery[] = [];\n const [iField, iDirection] = orderBy[i];\n for (let j = 0; j <= i; j++) {\n const [field] = orderBy[j];\n if (j === i) {\n group.push(\n startRangeComparison(\n spec,\n table,\n iField,\n bound.row[iField] ?? null,\n iDirection === 'asc' ? '>' : '<',\n ),\n );\n } else {\n group.push(startEquality(spec, table, field, bound.row[field] ?? null));\n }\n }\n constraints.push(sql`(${sql.join(group, ' AND ')})`);\n }\n\n if (!bound.exclusive) {\n constraints.push(\n sql`(${sql.join(\n orderBy.map(([field]) =>\n startEquality(spec, table, field, bound.row[field] ?? null),\n ),\n ' AND ',\n )})`,\n );\n }\n\n return sql`(${sql.join(constraints, ' OR ')})`;\n}\n\nfunction related(\n spec: Spec,\n relationships: readonly CorrelatedSubquery[],\n format: Format | undefined,\n parentTable: Table,\n): SQLQuery[] {\n return relationships.map(relationship =>\n relationshipSubquery(\n spec,\n relationship,\n format?.relationships[must(relationship.subquery.alias)],\n parentTable,\n ),\n );\n}\n\nfunction relationshipSubquery(\n spec: Spec,\n relationship: CorrelatedSubquery,\n format: Format | undefined,\n parentTable: Table,\n): SQLQuery {\n const innerAlias = `inner_${relationship.subquery.alias}`;\n if (relationship.hidden) {\n const {join, participatingTables} = makeJunctionJoin(spec, relationship);\n const lastTable = must(last(participatingTables)).table;\n\n assert(\n relationship.subquery.related,\n 'hidden relationship must be a junction',\n );\n const nestedAst = relationship.subquery.related[0].subquery;\n const selectionSet = related(\n spec,\n nestedAst.related ?? [],\n format,\n lastTable,\n );\n const tableSchema = spec.zql[nestedAst.table];\n for (const column of Object.keys(tableSchema.columns)) {\n selectionSet.push(\n selectIdent(spec.server, {\n table: lastTable,\n zql: column,\n }),\n );\n }\n\n return sql`(\n SELECT ${toJSON(innerAlias, format?.singular)} FROM (SELECT ${sql.join(\n selectionSet,\n ',',\n )} FROM ${join} WHERE (${makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n )(participatingTables[0].table)}) ${\n nestedAst.where\n ? sql`AND ${where(spec, nestedAst.where, lastTable)}`\n : sql``\n }${\n nestedAst.start\n ? sql` AND ${start(\n spec,\n nestedAst.start,\n nestedAst.orderBy,\n lastTable,\n )}`\n : sql``\n } ${orderBy(spec, nestedAst.orderBy, lastTable)} ${limit(\n last(participatingTables)?.limit,\n format?.singular,\n )} ) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n }\n\n return sql`(\n SELECT ${toJSON(innerAlias, format?.singular)} FROM (${select(\n spec,\n relationship.subquery,\n format,\n makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n ),\n )}) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n}\n\nfunction where(\n spec: Spec,\n condition: Condition | undefined,\n table: Table,\n): SQLQuery {\n if (!condition) {\n return sql``;\n }\n\n switch (condition.type) {\n case 'and':\n return sql`(${sql.join(\n condition.conditions.map(c => where(spec, c, table)),\n ' AND ',\n )})`;\n case 'or':\n return sql`(${sql.join(\n condition.conditions.map(c => where(spec, c, table)),\n ' OR ',\n )})`;\n case 'correlatedSubquery':\n if (condition.scalar) {\n return scalarSubquery(spec, condition, table);\n }\n return exists(spec, condition, table);\n case 'simple':\n return simple(spec, condition, table);\n }\n}\n\nfunction exists(\n spec: Spec,\n condition: CorrelatedSubqueryCondition,\n parentTable: Table,\n): SQLQuery {\n switch (condition.op) {\n case 'EXISTS':\n return sql`EXISTS (${select(\n spec,\n condition.related.subquery,\n undefined,\n makeCorrelator(\n spec,\n condition.related.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n condition.related.correlation.childField,\n ),\n )})`;\n case 'NOT EXISTS':\n return sql`NOT EXISTS (${select(\n spec,\n condition.related.subquery,\n undefined,\n makeCorrelator(\n spec,\n condition.related.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n condition.related.correlation.childField,\n ),\n )})`;\n }\n}\n\nfunction scalarSubquery(\n spec: Spec,\n condition: CorrelatedSubqueryCondition,\n parentTable: Table,\n): SQLQuery {\n const parentField = condition.related.correlation.parentField[0];\n const childField = condition.related.correlation.childField[0];\n const subqueryAST = condition.related.subquery;\n\n const parentCol = colIdent(spec.server, {\n table: parentTable,\n zql: parentField,\n });\n\n const subqueryTable = makeTable(spec, subqueryAST.table);\n const childCol = colIdent(spec.server, {\n table: subqueryTable,\n zql: childField,\n });\n\n const op = sql.__dangerous__rawValue(\n condition.op === 'EXISTS' ? '=' : 'IS NOT',\n );\n\n const subqueryConditions = subqueryAST.where\n ? [where(spec, subqueryAST.where, subqueryTable)]\n : [];\n if (subqueryAST.start) {\n subqueryConditions.push(\n start(spec, subqueryAST.start, subqueryAST.orderBy, subqueryTable),\n );\n }\n const subqueryOrderBy = orderBy(spec, subqueryAST.orderBy, subqueryTable);\n\n return sql`${parentCol} ${op} (SELECT ${childCol} FROM ${fromIdent(spec.server, subqueryTable)} ${\n subqueryConditions.length > 0\n ? sql`WHERE ${sql.join(subqueryConditions, ' AND ')}`\n : sql``\n } ${subqueryOrderBy} LIMIT 1)`;\n}\n\nexport function makeCorrelator(\n spec: Spec,\n parentFields: readonly QualifiedColumn[],\n childZqlFields: readonly string[],\n): (childTable: Table) => SQLQuery {\n return (childTable: Table) => {\n const childFields = childZqlFields.map(zqlField => ({\n table: childTable,\n zql: zqlField,\n }));\n return sql.join(\n zip(parentFields, childFields).map(\n ([parentColumn, childColumn]) =>\n sql`${colIdent(spec.server, parentColumn)} = ${colIdent(\n spec.server,\n childColumn,\n )}`,\n ),\n ' AND ',\n );\n };\n}\n\nexport function simple(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n switch (condition.op) {\n case '!=':\n case '<':\n case '<=':\n case '=':\n case '>':\n case '>=':\n case 'ILIKE':\n case 'LIKE':\n case 'NOT ILIKE':\n case 'NOT LIKE':\n return sql`${valueComparison(\n spec,\n condition.left,\n table,\n condition.right,\n false,\n )} ${sql.__dangerous__rawValue(condition.op)} ${valueComparison(\n spec,\n condition.right,\n table,\n condition.left,\n false,\n )}`;\n case 'NOT IN':\n case 'IN':\n return any(spec, condition, table);\n case 'IS':\n case 'IS NOT':\n return distinctFrom(spec, condition, table);\n }\n}\n\nexport function any(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n return sql`${condition.op === 'NOT IN' ? sql`NOT` : sql``}\n (\n ${valueComparison(spec, condition.left, table, condition.right, false)} = ANY \n (${valueComparison(spec, condition.right, table, condition.left, true)})\n )`;\n}\n\nexport function distinctFrom(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n return sql`${valueComparison(spec, condition.left, table, condition.right, false)} ${\n condition.op === 'IS' ? sql`IS NOT DISTINCT FROM` : sql`IS DISTINCT FROM`\n } ${valueComparison(spec, condition.right, table, condition.left, false)}`;\n}\n\nfunction startEquality(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n): SQLQuery {\n return sql`${colIdent(spec.server, {\n table,\n zql: field,\n })} IS NOT DISTINCT FROM ${startValue(spec, table, field, value)}`;\n}\n\nfunction startRangeComparison(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n operator: '>' | '<',\n): SQLQuery {\n const column = colIdent(spec.server, {table, zql: field});\n if (value === null) {\n return operator === '>' ? sql`${column} IS NOT NULL` : sql`FALSE`;\n }\n const typedValue = startValue(spec, table, field, value);\n return operator === '>'\n ? sql`${column} > ${typedValue}`\n : sql`(${column} IS NULL OR ${column} < ${typedValue})`;\n}\n\nfunction startValue(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n): SQLQuery {\n return sqlConvertColumnArg(\n getServerColumn(spec.server, table, field),\n value,\n false,\n true,\n );\n}\n\nfunction valueComparison(\n spec: Spec,\n valuePos: ValuePosition,\n table: Table,\n otherValuePos: ValuePosition,\n plural: boolean,\n): SQLQuery {\n const valuePosType = valuePos.type;\n switch (valuePosType) {\n case 'column': {\n const qualified: QualifiedColumn = {\n table,\n zql: valuePos.name,\n };\n return colIdent(spec.server, qualified);\n }\n case 'literal':\n return literalValueComparison(\n spec,\n valuePos,\n table,\n otherValuePos,\n plural,\n );\n case 'static':\n throw new Error(\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n default:\n unreachable(valuePosType);\n break;\n }\n}\n\nfunction literalValueComparison(\n spec: Spec,\n valuePos: LiteralReference,\n table: Table,\n otherValuePos: ValuePosition,\n plural: boolean,\n): SQLQuery {\n const otherType = otherValuePos.type;\n switch (otherType) {\n case 'column':\n return sqlConvertColumnArg(\n getServerColumn(spec.server, table, otherValuePos.name),\n valuePos.value,\n plural,\n true,\n );\n case 'literal': {\n assert(\n plural === Array.isArray(valuePos.value),\n 'Expected plural flag to match whether value is an array',\n );\n if (Array.isArray(valuePos.value)) {\n if (valuePos.value.length > 0) {\n // If the array is non-empty base its type on its first\n // element\n return sqlConvertPluralLiteralArg(\n typeof valuePos.value[0] as PluralLiteralType,\n valuePos.value as PluralLiteralType[],\n );\n }\n // If the array is empty, base its type on the other value\n // position's type (as long as the other value position is non-null,\n // cannot have a null[]).\n if (otherValuePos.value !== null) {\n return sqlConvertPluralLiteralArg(\n typeof otherValuePos.value as PluralLiteralType,\n [],\n );\n }\n // If the other value position is null, it can be compared to any\n // type of empty array, chose 'string' arbitrarily.\n return sqlConvertPluralLiteralArg('string', []);\n }\n if (\n typeof valuePos.value === 'string' ||\n typeof valuePos.value === 'number' ||\n typeof valuePos.value === 'boolean'\n ) {\n return sqlConvertSingularLiteralArg(valuePos.value);\n }\n throw new Error(\n `Literal of unexpected type. ${valuePos.value} of type ${typeof valuePos.value}`,\n );\n }\n case 'static':\n throw new Error(\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n default:\n unreachable(otherType);\n }\n}\n\nexport function makeJunctionJoin(\n spec: Spec,\n relationship: CorrelatedSubquery,\n): {\n join: SQLQuery;\n participatingTables: ReturnType<typeof pullTablesForJunction>;\n} {\n const participatingTables = pullTablesForJunction(spec, relationship);\n const joins: SQLQuery[] = [];\n\n for (const {table} of participatingTables) {\n if (joins.length === 0) {\n joins.push(fromIdent(spec.server, table));\n continue;\n }\n joins.push(\n sql` JOIN ${fromIdent(spec.server, table)} ON ${makeCorrelator(\n spec,\n participatingTables[joins.length].correlation.parentField.map(f => ({\n table: participatingTables[joins.length - 1].table,\n zql: f,\n })),\n participatingTables[joins.length].correlation.childField,\n )(participatingTables[joins.length].table)}`,\n );\n }\n\n return {\n join: sql`${sql.join(joins, '')}`,\n participatingTables,\n // lastTable: participatingTables[participatingTables.length - 1].table,\n // lastLimit: participatingTables[participatingTables.length - 1].limit,\n };\n}\n\nexport function pullTablesForJunction(\n spec: Spec,\n relationship: CorrelatedSubquery,\n): [\n {\n table: Table;\n correlation: Correlation;\n limit: number | undefined;\n },\n {table: Table; correlation: Correlation; limit: number | undefined},\n] {\n assert(\n relationship.subquery.related?.length === 1,\n 'Too many related tables for a junction edge',\n );\n const otherRelationship = relationship.subquery.related[0];\n assert(\n !otherRelationship.hidden,\n 'Expected junction edge relationship to not be hidden',\n );\n return [\n {\n table: makeTable(spec, relationship.subquery.table),\n correlation: relationship.correlation,\n limit: relationship.subquery.limit,\n },\n {\n table: makeTable(spec, otherRelationship.subquery.table),\n correlation: otherRelationship.correlation,\n limit: otherRelationship.subquery.limit,\n },\n ];\n}\n\nfunction toJSON(table: string, singular = false): SQLQuery {\n return sql`${\n singular ? sql`` : sql`COALESCE(json_agg`\n }(row_to_json(${sql.ident(table)}))${singular ? sql`` : sql`, '[]'::json)`}`;\n}\n\nfunction selectIdent(server: ServerSpec, column: QualifiedColumn): SQLQuery {\n const serverColumnSchema =\n server.schema[server.mapper.tableName(column.table.zql)][\n server.mapper.columnName(column.table.zql, column.zql)\n ];\n const serverType = serverColumnSchema.type;\n if (!serverColumnSchema.isEnum) {\n let needsNormalization = false;\n switch (serverType) {\n case 'timestamptz':\n // @ts-expect-error Fallthrough intended\n case 'timetz':\n needsNormalization = true;\n // fallthrough\n\n case 'date':\n case 'time':\n case 'time without time zone':\n case 'time with time zone':\n case 'timestamp':\n case 'timestamp without time zone':\n case 'timestamp with time zone': {\n // EXTRACT(EPOCH FROM timetz) can be negative when the UTC offset is\n // positive (e.g. 01:00+02 = 23:00 UTC prev day = -3600s). Wrap with\n // modular arithmetic to normalize to 0..86400000.\n const toMs = (epochExpr: SQLQuery): SQLQuery =>\n needsNormalization\n ? sql`((${epochExpr})::bigint + 86400000) % 86400000`\n : epochExpr;\n\n if (serverColumnSchema.isArray) {\n const col = colIdent(server, column);\n return sql`CASE WHEN ${col} IS NULL THEN NULL ELSE ARRAY(SELECT ${toMs(\n sql`EXTRACT(EPOCH FROM unnest(${col})) * 1000`,\n )}) END as ${sql.ident(column.zql)}`;\n }\n\n return sql`${toMs(\n sql`EXTRACT(EPOCH FROM ${colIdent(server, column)}) * 1000`,\n )} as ${sql.ident(column.zql)}`;\n }\n }\n }\n\n return sql`${colIdent(server, column)} as ${sql.ident(column.zql)}`;\n}\n\nfunction colIdent(server: ServerSpec, column: QualifiedColumn) {\n return sql.ident(\n column.table.alias,\n server.mapper.columnName(column.table.zql, column.zql),\n );\n}\n\nfunction fromIdent(server: ServerSpec, table: Table) {\n return sql`${sql.ident(server.mapper.tableName(table.zql))} AS ${sql.ident(table.alias)}`;\n}\n\nfunction getServerColumn(spec: ServerSpec, table: Table, zqlColumn: string) {\n return spec.schema[spec.mapper.tableName(table.zql)][\n spec.mapper.columnName(table.zql, zqlColumn)\n ];\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function extractZqlResult(pgResult: Array<any>): JSONValue {\n const bigIntJson: BigIntJSONValue = parseBigIntJson(\n pgResult[0][ZQL_RESULT_KEY],\n );\n assertJSONValue(bigIntJson);\n return bigIntJson;\n}\n\nfunction assertJSONValue(v: BigIntJSONValue): asserts v is JSONValue {\n const path = findPathToBigInt(v);\n if (path) {\n throw new Error(`Value exceeds safe Number range. ${path}`);\n }\n}\n\nfunction findPathToBigInt(v: BigIntJSONValue): string | undefined {\n const typeOfV = typeof v;\n switch (typeOfV) {\n case 'bigint':\n return ` = ${v}`;\n case 'object': {\n if (v === null) {\n return;\n }\n if (Array.isArray(v)) {\n for (let i = 0; i < v.length; i++) {\n const path = findPathToBigInt(v[i]);\n if (path) {\n return `[${i}]${path}`;\n }\n }\n return undefined;\n }\n\n const o = v as Record<string, BigIntJSONValue>;\n for (const k in o) {\n if (hasOwn(o, k)) {\n const path = findPathToBigInt(o[k]);\n if (path) {\n return `['${k}']${path}`;\n }\n }\n }\n return undefined;\n }\n case 'number':\n return undefined;\n case 'boolean':\n return undefined;\n default:\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;AA4DA,IAAM,iBAAiB;AACvB,IAAM,uBAAuB,IAAI,MAAM,cAAc;AAErD,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB,IAAI,MAAM,oBAAoB;AAE7D,SAAgB,QACd,cACA,WACA,KACA,QACU;CACV,MAAM,iBACJ,MACA,cAAa,UAAU,OAAO,WAAW,UAC3C;CACA,MAAM,OAAa;EACjB,YAAY;EACZ,QAAQ;GACN,QAAQ;GACR,QAAQ,eAAe,UAAU,MAAM;EACzC;EACA,KAAK,UAAU;CACjB;CACA,OAAO,GAAG;MACN,OAAO,sBAAsB,QAAQ,QAAQ,EAAE,YAAY,qBAAqB;YAC1E,OAAO,MAAM,KAAK,MAAM,EAAE,IAAI;AAC1C;AAEA,SAAS,OACP,MACA,KACA,QACA,WACU;CACV,MAAM,QAAQ,UAAU,MAAM,IAAI,KAAK;CACvC,MAAM,eAAe,QAAQ,MAAM,IAAI,WAAW,CAAC,GAAG,QAAQ,KAAK;CACnE,MAAM,cAAc,KAAK,IAAI,IAAI;CACjC,MAAM,cAAc,IAAI,IACtB,IAAI,SAAS,KAAI,MAAK,EAAE,SAAS,SAAS,EAAE,CAC9C;CACA,KAAK,MAAM,UAAU,OAAO,KAAK,YAAY,OAAO,GAClD,IAAI,CAAC,YAAY,IAAI,MAAM,GACzB,aAAa,KACX,YAAY,KAAK,QAAQ;EACvB;EACA,KAAK;CACP,CAAC,CACH;CAIJ,IAAI,eAAe;CACnB,SAAS,WAAW,MAAe;EACjC,IAAI,CAAC,MACH,OAAO,GAAG;EAGZ,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG;EACzC,eAAe;EACf,OAAO;CACT;CAEA,OAAO,GAAG,UAAU,IAAI,KAAK,cAAc,GAAG,EAAE;WACvC,UAAU,KAAK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Content":["import type {SQLQuery} from '@databases/sql';\nimport {last, zip} from '../../shared/src/arrays.ts';\nimport {assert, unreachable} from '../../shared/src/asserts.ts';\nimport {\n parse as parseBigIntJson,\n type JSONValue as BigIntJSONValue,\n} from '../../shared/src/bigint-json.ts';\nimport {hasOwn} from '../../shared/src/has-own.ts';\nimport {type JSONValue} from '../../shared/src/json.ts';\nimport {must} from '../../shared/src/must.ts';\nimport type {\n AST,\n Bound,\n Condition,\n CorrelatedSubquery,\n CorrelatedSubqueryCondition,\n Correlation,\n LiteralReference,\n Ordering,\n SimpleCondition,\n ValuePosition,\n} from '../../zero-protocol/src/ast.ts';\nimport {\n clientToServer,\n type NameMapper,\n} from '../../zero-schema/src/name-mapper.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {ServerSchema} from '../../zero-types/src/server-schema.ts';\nimport type {Format} from '../../zql/src/ivm/view.ts';\nimport {completeOrdering} from '../../zql/src/query/complete-ordering.ts';\nimport {\n sql,\n sqlConvertColumnArg,\n sqlConvertPluralLiteralArg,\n sqlConvertSingularLiteralArg,\n type PluralLiteralType,\n} from './sql.ts';\n\ntype Table = {\n zql: string;\n alias: string;\n};\n\ntype QualifiedColumn = {\n table: Table;\n zql: string;\n};\n\ntype ServerSpec = {\n schema: ServerSchema;\n // maps zql names to server names\n mapper: NameMapper;\n};\n\nexport type Spec = {\n server: ServerSpec;\n zql: Schema['tables'];\n aliasCount: number;\n};\n\nconst ZQL_RESULT_KEY = 'zql_result';\nconst ZQL_RESULT_KEY_IDENT = sql.ident(ZQL_RESULT_KEY);\n\nconst ZQL_RESULT_TABLE_KEY = 'zql_root';\nconst ZQL_RESULT_TABLE_IDENT = sql.ident(ZQL_RESULT_TABLE_KEY);\n\nexport function compile(\n serverSchema: ServerSchema,\n zqlSchema: Schema,\n ast: AST,\n format?: Format,\n): SQLQuery {\n ast = completeOrdering(\n ast,\n tableName => zqlSchema.tables[tableName].primaryKey,\n );\n const spec: Spec = {\n aliasCount: 0,\n server: {\n schema: serverSchema,\n mapper: clientToServer(zqlSchema.tables),\n },\n zql: zqlSchema.tables,\n };\n return sql`SELECT \n ${toJSON(ZQL_RESULT_TABLE_KEY, format?.singular)}::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${select(spec, ast, format)}) ${ZQL_RESULT_TABLE_IDENT}`;\n}\n\nfunction select(\n spec: Spec,\n ast: AST,\n format: Format | undefined,\n correlate?: (childTable: Table) => SQLQuery,\n): SQLQuery {\n const table = makeTable(spec, ast.table);\n const selectionSet = related(spec, ast.related ?? [], format, table);\n const tableSchema = spec.zql[ast.table];\n const usedAliases = new Set<string>(\n ast.related?.map(r => r.subquery.alias ?? ''),\n );\n for (const column of Object.keys(tableSchema.columns)) {\n if (!usedAliases.has(column)) {\n selectionSet.push(\n selectIdent(spec.server, {\n table,\n zql: column,\n }),\n );\n }\n }\n\n let appliedWhere = false;\n function maybeWhere(test: unknown) {\n if (!test) {\n return sql``;\n }\n\n const ret = appliedWhere ? sql`AND` : sql`WHERE`;\n appliedWhere = true;\n return ret;\n }\n\n return sql`SELECT ${sql.join(selectionSet, ',')}\n FROM ${fromIdent(spec.server, table)}\n ${maybeWhere(ast.where)} ${where(spec, ast.where, table)}${\n ast.start\n ? sql`\n ${maybeWhere(ast.start)} ${start(spec, ast.start, ast.orderBy, table)}`\n : sql``\n }\n ${maybeWhere(correlate)} ${correlate ? correlate(table) : sql``}\n ${orderBy(spec, ast.orderBy, table)}\n ${limit(ast.limit, format?.singular)}`;\n}\n\nexport function limit(\n limit: number | undefined,\n singular: boolean | undefined,\n): SQLQuery {\n if (limit === 0) {\n return sql`LIMIT 0`;\n }\n if (singular) {\n return sql`LIMIT 1`;\n }\n if (limit === undefined) {\n return sql``;\n }\n return sql`LIMIT ${sqlConvertSingularLiteralArg(limit)}`;\n}\n\nfunction makeTable(spec: Spec, zql: string, alias?: string): Table {\n alias = alias ?? zql + '_' + spec.aliasCount++;\n return {\n zql,\n alias,\n };\n}\n\nexport function orderBy(\n spec: Spec,\n orderBy: Ordering | undefined,\n table: Table,\n): SQLQuery {\n if (!orderBy) {\n return sql``;\n }\n return sql`ORDER BY ${sql.join(\n orderBy.map(([col, dir]) =>\n dir === 'asc'\n ? // Oh postgres. The table must be referred to by client name but the column by server name.\n // E.g., `SELECT server_col as client_col FROM server_table as client_table ORDER BY client_Table.server_col`\n sql`${colIdent(spec.server, {\n table,\n zql: col,\n })} ASC NULLS FIRST`\n : sql`${colIdent(spec.server, {\n table,\n zql: col,\n })} DESC NULLS LAST`,\n ),\n ', ',\n )}`;\n}\n\nexport function start(\n spec: Spec,\n bound: Bound | undefined,\n orderBy: Ordering | undefined,\n table: Table,\n): SQLQuery {\n if (!bound) {\n return sql``;\n }\n assert(\n orderBy !== undefined && orderBy.length > 0,\n 'start requires ordering',\n );\n\n const constraints: SQLQuery[] = [];\n for (let i = 0; i < orderBy.length; i++) {\n const group: SQLQuery[] = [];\n const [iField, iDirection] = orderBy[i];\n for (let j = 0; j <= i; j++) {\n const [field] = orderBy[j];\n if (j === i) {\n group.push(\n startRangeComparison(\n spec,\n table,\n iField,\n bound.row[iField] ?? null,\n iDirection === 'asc' ? '>' : '<',\n ),\n );\n } else {\n group.push(startEquality(spec, table, field, bound.row[field] ?? null));\n }\n }\n constraints.push(sql`(${sql.join(group, ' AND ')})`);\n }\n\n if (!bound.exclusive) {\n constraints.push(\n sql`(${sql.join(\n orderBy.map(([field]) =>\n startEquality(spec, table, field, bound.row[field] ?? null),\n ),\n ' AND ',\n )})`,\n );\n }\n\n return sql`(${sql.join(constraints, ' OR ')})`;\n}\n\nfunction related(\n spec: Spec,\n relationships: readonly CorrelatedSubquery[],\n format: Format | undefined,\n parentTable: Table,\n): SQLQuery[] {\n return relationships.map(relationship =>\n relationshipSubquery(\n spec,\n relationship,\n format?.relationships[must(relationship.subquery.alias)],\n parentTable,\n ),\n );\n}\n\nfunction relationshipSubquery(\n spec: Spec,\n relationship: CorrelatedSubquery,\n format: Format | undefined,\n parentTable: Table,\n): SQLQuery {\n const innerAlias = `inner_${relationship.subquery.alias}`;\n if (relationship.hidden) {\n const {join, participatingTables} = makeJunctionJoin(spec, relationship);\n const lastTable = must(last(participatingTables)).table;\n\n assert(\n relationship.subquery.related,\n 'hidden relationship must be a junction',\n );\n const nestedAst = relationship.subquery.related[0].subquery;\n const selectionSet = related(\n spec,\n nestedAst.related ?? [],\n format,\n lastTable,\n );\n const tableSchema = spec.zql[nestedAst.table];\n for (const column of Object.keys(tableSchema.columns)) {\n selectionSet.push(\n selectIdent(spec.server, {\n table: lastTable,\n zql: column,\n }),\n );\n }\n\n return sql`(\n SELECT ${toJSON(innerAlias, format?.singular)} FROM (SELECT ${sql.join(\n selectionSet,\n ',',\n )} FROM ${join} WHERE (${makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n )(participatingTables[0].table)}) ${\n nestedAst.where\n ? sql`AND ${where(spec, nestedAst.where, lastTable)}`\n : sql``\n }${\n nestedAst.start\n ? sql` AND ${start(\n spec,\n nestedAst.start,\n nestedAst.orderBy,\n lastTable,\n )}`\n : sql``\n } ${orderBy(spec, nestedAst.orderBy, lastTable)} ${limit(\n last(participatingTables)?.limit,\n format?.singular,\n )} ) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n }\n\n return sql`(\n SELECT ${toJSON(innerAlias, format?.singular)} FROM (${select(\n spec,\n relationship.subquery,\n format,\n makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n ),\n )}) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n}\n\nfunction where(\n spec: Spec,\n condition: Condition | undefined,\n table: Table,\n): SQLQuery {\n if (!condition) {\n return sql``;\n }\n\n switch (condition.type) {\n case 'and':\n return sql`(${sql.join(\n condition.conditions.map(c => where(spec, c, table)),\n ' AND ',\n )})`;\n case 'or':\n return sql`(${sql.join(\n condition.conditions.map(c => where(spec, c, table)),\n ' OR ',\n )})`;\n case 'correlatedSubquery':\n // `scalar` is deliberately ignored here. It is a planner hint for the\n // IVM engines, which have no cost-based planner and benefit from\n // pre-resolving an at-most-one-row subquery to a literal comparison\n // (see zqlite's `resolveSimpleScalarSubqueries`). Postgres decorrelates\n // EXISTS into a semi-join on its own, so the hint buys nothing here —\n // and honoring it as `parentField = (SELECT childField … LIMIT 1)` is\n // only sound when the subquery matches at most one row *globally*.\n // Applying it unconditionally silently dropped rows whenever the\n // subquery was not pinned to a unique key.\n return exists(spec, condition, table);\n case 'simple':\n return simple(spec, condition, table);\n }\n}\n\nfunction exists(\n spec: Spec,\n condition: CorrelatedSubqueryCondition,\n parentTable: Table,\n): SQLQuery {\n switch (condition.op) {\n case 'EXISTS':\n return sql`EXISTS (${select(\n spec,\n condition.related.subquery,\n undefined,\n makeCorrelator(\n spec,\n condition.related.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n condition.related.correlation.childField,\n ),\n )})`;\n case 'NOT EXISTS':\n return sql`NOT EXISTS (${select(\n spec,\n condition.related.subquery,\n undefined,\n makeCorrelator(\n spec,\n condition.related.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n condition.related.correlation.childField,\n ),\n )})`;\n }\n}\n\nexport function makeCorrelator(\n spec: Spec,\n parentFields: readonly QualifiedColumn[],\n childZqlFields: readonly string[],\n): (childTable: Table) => SQLQuery {\n return (childTable: Table) => {\n const childFields = childZqlFields.map(zqlField => ({\n table: childTable,\n zql: zqlField,\n }));\n return sql.join(\n zip(parentFields, childFields).map(\n ([parentColumn, childColumn]) =>\n sql`${colIdent(spec.server, parentColumn)} = ${colIdent(\n spec.server,\n childColumn,\n )}`,\n ),\n ' AND ',\n );\n };\n}\n\nexport function simple(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n switch (condition.op) {\n case '!=':\n case '<':\n case '<=':\n case '=':\n case '>':\n case '>=':\n case 'ILIKE':\n case 'LIKE':\n case 'NOT ILIKE':\n case 'NOT LIKE':\n return sql`${valueComparison(\n spec,\n condition.left,\n table,\n condition.right,\n false,\n )} ${sql.__dangerous__rawValue(condition.op)} ${valueComparison(\n spec,\n condition.right,\n table,\n condition.left,\n false,\n )}`;\n case 'NOT IN':\n case 'IN':\n return any(spec, condition, table);\n case 'IS':\n case 'IS NOT':\n return distinctFrom(spec, condition, table);\n }\n}\n\nexport function any(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n return sql`${condition.op === 'NOT IN' ? sql`NOT` : sql``}\n (\n ${valueComparison(spec, condition.left, table, condition.right, false)} = ANY \n (${valueComparison(spec, condition.right, table, condition.left, true)})\n )`;\n}\n\nexport function distinctFrom(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n return sql`${valueComparison(spec, condition.left, table, condition.right, false)} ${\n condition.op === 'IS' ? sql`IS NOT DISTINCT FROM` : sql`IS DISTINCT FROM`\n } ${valueComparison(spec, condition.right, table, condition.left, false)}`;\n}\n\nfunction startEquality(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n): SQLQuery {\n return sql`${colIdent(spec.server, {\n table,\n zql: field,\n })} IS NOT DISTINCT FROM ${startValue(spec, table, field, value)}`;\n}\n\nfunction startRangeComparison(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n operator: '>' | '<',\n): SQLQuery {\n const column = colIdent(spec.server, {table, zql: field});\n if (value === null) {\n return operator === '>' ? sql`${column} IS NOT NULL` : sql`FALSE`;\n }\n const typedValue = startValue(spec, table, field, value);\n return operator === '>'\n ? sql`${column} > ${typedValue}`\n : sql`(${column} IS NULL OR ${column} < ${typedValue})`;\n}\n\nfunction startValue(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n): SQLQuery {\n return sqlConvertColumnArg(\n getServerColumn(spec.server, table, field),\n value,\n false,\n true,\n );\n}\n\nfunction valueComparison(\n spec: Spec,\n valuePos: ValuePosition,\n table: Table,\n otherValuePos: ValuePosition,\n plural: boolean,\n): SQLQuery {\n const valuePosType = valuePos.type;\n switch (valuePosType) {\n case 'column': {\n const qualified: QualifiedColumn = {\n table,\n zql: valuePos.name,\n };\n return colIdent(spec.server, qualified);\n }\n case 'literal':\n return literalValueComparison(\n spec,\n valuePos,\n table,\n otherValuePos,\n plural,\n );\n case 'static':\n throw new Error(\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n default:\n unreachable(valuePosType);\n break;\n }\n}\n\nfunction literalValueComparison(\n spec: Spec,\n valuePos: LiteralReference,\n table: Table,\n otherValuePos: ValuePosition,\n plural: boolean,\n): SQLQuery {\n const otherType = otherValuePos.type;\n switch (otherType) {\n case 'column':\n return sqlConvertColumnArg(\n getServerColumn(spec.server, table, otherValuePos.name),\n valuePos.value,\n plural,\n true,\n );\n case 'literal': {\n assert(\n plural === Array.isArray(valuePos.value),\n 'Expected plural flag to match whether value is an array',\n );\n if (Array.isArray(valuePos.value)) {\n if (valuePos.value.length > 0) {\n // If the array is non-empty base its type on its first\n // element\n return sqlConvertPluralLiteralArg(\n typeof valuePos.value[0] as PluralLiteralType,\n valuePos.value as PluralLiteralType[],\n );\n }\n // If the array is empty, base its type on the other value\n // position's type (as long as the other value position is non-null,\n // cannot have a null[]).\n if (otherValuePos.value !== null) {\n return sqlConvertPluralLiteralArg(\n typeof otherValuePos.value as PluralLiteralType,\n [],\n );\n }\n // If the other value position is null, it can be compared to any\n // type of empty array, chose 'string' arbitrarily.\n return sqlConvertPluralLiteralArg('string', []);\n }\n if (\n typeof valuePos.value === 'string' ||\n typeof valuePos.value === 'number' ||\n typeof valuePos.value === 'boolean'\n ) {\n return sqlConvertSingularLiteralArg(valuePos.value);\n }\n throw new Error(\n `Literal of unexpected type. ${valuePos.value} of type ${typeof valuePos.value}`,\n );\n }\n case 'static':\n throw new Error(\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n default:\n unreachable(otherType);\n }\n}\n\nexport function makeJunctionJoin(\n spec: Spec,\n relationship: CorrelatedSubquery,\n): {\n join: SQLQuery;\n participatingTables: ReturnType<typeof pullTablesForJunction>;\n} {\n const participatingTables = pullTablesForJunction(spec, relationship);\n const joins: SQLQuery[] = [];\n\n for (const {table} of participatingTables) {\n if (joins.length === 0) {\n joins.push(fromIdent(spec.server, table));\n continue;\n }\n joins.push(\n sql` JOIN ${fromIdent(spec.server, table)} ON ${makeCorrelator(\n spec,\n participatingTables[joins.length].correlation.parentField.map(f => ({\n table: participatingTables[joins.length - 1].table,\n zql: f,\n })),\n participatingTables[joins.length].correlation.childField,\n )(participatingTables[joins.length].table)}`,\n );\n }\n\n return {\n join: sql`${sql.join(joins, '')}`,\n participatingTables,\n // lastTable: participatingTables[participatingTables.length - 1].table,\n // lastLimit: participatingTables[participatingTables.length - 1].limit,\n };\n}\n\nexport function pullTablesForJunction(\n spec: Spec,\n relationship: CorrelatedSubquery,\n): [\n {\n table: Table;\n correlation: Correlation;\n limit: number | undefined;\n },\n {table: Table; correlation: Correlation; limit: number | undefined},\n] {\n assert(\n relationship.subquery.related?.length === 1,\n 'Too many related tables for a junction edge',\n );\n const otherRelationship = relationship.subquery.related[0];\n assert(\n !otherRelationship.hidden,\n 'Expected junction edge relationship to not be hidden',\n );\n return [\n {\n table: makeTable(spec, relationship.subquery.table),\n correlation: relationship.correlation,\n limit: relationship.subquery.limit,\n },\n {\n table: makeTable(spec, otherRelationship.subquery.table),\n correlation: otherRelationship.correlation,\n limit: otherRelationship.subquery.limit,\n },\n ];\n}\n\nfunction toJSON(table: string, singular = false): SQLQuery {\n return sql`${\n singular ? sql`` : sql`COALESCE(json_agg`\n }(row_to_json(${sql.ident(table)}))${singular ? sql`` : sql`, '[]'::json)`}`;\n}\n\nfunction selectIdent(server: ServerSpec, column: QualifiedColumn): SQLQuery {\n const serverColumnSchema =\n server.schema[server.mapper.tableName(column.table.zql)][\n server.mapper.columnName(column.table.zql, column.zql)\n ];\n const serverType = serverColumnSchema.type;\n if (!serverColumnSchema.isEnum) {\n let needsNormalization = false;\n switch (serverType) {\n case 'timestamptz':\n // @ts-expect-error Fallthrough intended\n case 'timetz':\n needsNormalization = true;\n // fallthrough\n\n case 'date':\n case 'time':\n case 'time without time zone':\n case 'time with time zone':\n case 'timestamp':\n case 'timestamp without time zone':\n case 'timestamp with time zone': {\n // EXTRACT(EPOCH FROM timetz) can be negative when the UTC offset is\n // positive (e.g. 01:00+02 = 23:00 UTC prev day = -3600s). Wrap with\n // modular arithmetic to normalize to 0..86400000.\n const toMs = (epochExpr: SQLQuery): SQLQuery =>\n needsNormalization\n ? sql`((${epochExpr})::bigint + 86400000) % 86400000`\n : epochExpr;\n\n if (serverColumnSchema.isArray) {\n const col = colIdent(server, column);\n return sql`CASE WHEN ${col} IS NULL THEN NULL ELSE ARRAY(SELECT ${toMs(\n sql`EXTRACT(EPOCH FROM unnest(${col})) * 1000`,\n )}) END as ${sql.ident(column.zql)}`;\n }\n\n return sql`${toMs(\n sql`EXTRACT(EPOCH FROM ${colIdent(server, column)}) * 1000`,\n )} as ${sql.ident(column.zql)}`;\n }\n }\n }\n\n return sql`${colIdent(server, column)} as ${sql.ident(column.zql)}`;\n}\n\nfunction colIdent(server: ServerSpec, column: QualifiedColumn) {\n return sql.ident(\n column.table.alias,\n server.mapper.columnName(column.table.zql, column.zql),\n );\n}\n\nfunction fromIdent(server: ServerSpec, table: Table) {\n return sql`${sql.ident(server.mapper.tableName(table.zql))} AS ${sql.ident(table.alias)}`;\n}\n\nfunction getServerColumn(spec: ServerSpec, table: Table, zqlColumn: string) {\n return spec.schema[spec.mapper.tableName(table.zql)][\n spec.mapper.columnName(table.zql, zqlColumn)\n ];\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function extractZqlResult(pgResult: Array<any>): JSONValue {\n const bigIntJson: BigIntJSONValue = parseBigIntJson(\n pgResult[0][ZQL_RESULT_KEY],\n );\n assertJSONValue(bigIntJson);\n return bigIntJson;\n}\n\nfunction assertJSONValue(v: BigIntJSONValue): asserts v is JSONValue {\n const path = findPathToBigInt(v);\n if (path) {\n throw new Error(`Value exceeds safe Number range. ${path}`);\n }\n}\n\nfunction findPathToBigInt(v: BigIntJSONValue): string | undefined {\n const typeOfV = typeof v;\n switch (typeOfV) {\n case 'bigint':\n return ` = ${v}`;\n case 'object': {\n if (v === null) {\n return;\n }\n if (Array.isArray(v)) {\n for (let i = 0; i < v.length; i++) {\n const path = findPathToBigInt(v[i]);\n if (path) {\n return `[${i}]${path}`;\n }\n }\n return undefined;\n }\n\n const o = v as Record<string, BigIntJSONValue>;\n for (const k in o) {\n if (hasOwn(o, k)) {\n const path = findPathToBigInt(o[k]);\n if (path) {\n return `['${k}']${path}`;\n }\n }\n }\n return undefined;\n }\n case 'number':\n return undefined;\n case 'boolean':\n return undefined;\n default:\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;AA4DA,IAAM,iBAAiB;AACvB,IAAM,uBAAuB,IAAI,MAAM,cAAc;AAErD,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB,IAAI,MAAM,oBAAoB;AAE7D,SAAgB,QACd,cACA,WACA,KACA,QACU;CACV,MAAM,iBACJ,MACA,cAAa,UAAU,OAAO,WAAW,UAC3C;CACA,MAAM,OAAa;EACjB,YAAY;EACZ,QAAQ;GACN,QAAQ;GACR,QAAQ,eAAe,UAAU,MAAM;EACzC;EACA,KAAK,UAAU;CACjB;CACA,OAAO,GAAG;MACN,OAAO,sBAAsB,QAAQ,QAAQ,EAAE,YAAY,qBAAqB;YAC1E,OAAO,MAAM,KAAK,MAAM,EAAE,IAAI;AAC1C;AAEA,SAAS,OACP,MACA,KACA,QACA,WACU;CACV,MAAM,QAAQ,UAAU,MAAM,IAAI,KAAK;CACvC,MAAM,eAAe,QAAQ,MAAM,IAAI,WAAW,CAAC,GAAG,QAAQ,KAAK;CACnE,MAAM,cAAc,KAAK,IAAI,IAAI;CACjC,MAAM,cAAc,IAAI,IACtB,IAAI,SAAS,KAAI,MAAK,EA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,GAAG,eACd;CACA,gBAAgB,UAAU;CAC1B,OAAO;AACT;AAEA,SAAS,gBAAgB,GAA4C;CACnE,MAAM,OAAO,iBAAiB,CAAC;CAC/B,IAAI,MACF,MAAM,IAAI,MAAM,oCAAoC,MAAM;AAE9D;AAEA,SAAS,iBAAiB,GAAwC;CAEhE,QAAQ,OADe,GACvB;EACE,KAAK,UACH,OAAO,MAAM;EACf,KAAK,UAAU;GACb,IAAI,MAAM,MACR;GAEF,IAAI,MAAM,QAAQ,CAAC,GAAG;IACpB,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;KACjC,MAAM,OAAO,iBAAiB,EAAE,EAAE;KAClC,IAAI,MACF,OAAO,IAAI,EAAE,GAAG;IAEpB;IACA;GACF;GAEA,MAAM,IAAI;GACV,KAAK,MAAM,KAAK,GACd,IAAI,OAAO,GAAG,CAAC,GAAG;IAChB,MAAM,OAAO,iBAAiB,EAAE,EAAE;IAClC,IAAI,MACF,OAAO,KAAK,EAAE,IAAI;GAEtB;GAEF;EACF;EACA,KAAK,UACH;EACF,KAAK,WACH;EACF,SACE;CACJ;AACF"}
@@ -1,6 +1,6 @@
1
1
  var package_default = {
2
2
  name: "@rocicorp/zero",
3
- version: "1.9.0-canary.0",
3
+ version: "1.9.0-canary.1",
4
4
  description: "Zero is a web framework for serverless web development.",
5
5
  homepage: "https://zero.rocicorp.dev",
6
6
  bugs: { "url": "https://bugs.rocicorp.dev" },
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.9.0-canary.0\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"analyze-query\": \"./out/zero/src/analyze-query.js\",\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/kysely\": {\n \"types\": \"./out/zero/src/adapters/kysely.d.ts\",\n \"default\": \"./out/zero/src/adapters/kysely.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --quiet --config ../../oxlint.config.ts src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.3.11\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.39.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.0.0\",\n \"@fastify/websocket\": \"^11.0.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"^0.218.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"^0.76.0\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"^0.218.0\",\n \"@opentelemetry/resources\": \"^2.7.1\",\n \"@opentelemetry/sdk-metrics\": \"^2.7.1\",\n \"@opentelemetry/sdk-node\": \"^0.218.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.7.1\",\n \"@opentelemetry/semantic-conventions\": \"^1.41.1\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^1.0.4\",\n \"@rocicorp/logger\": \"^6.1.0\",\n \"@rocicorp/resolver\": \"^1.0.2\",\n \"@rocicorp/zero-sqlite3\": \"^1.1.2\",\n \"@standard-schema/spec\": \"^1.0.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.5.12\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.0\",\n \"chokidar\": \"^4.0.1\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.1\",\n \"command-line-usage\": \"^7.0.3\",\n \"compare-utf8\": \"^0.2.0\",\n \"defu\": \"^6.1.4\",\n \"eventemitter3\": \"^5.0.1\",\n \"fastify\": \"^5.0.0\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.9.3\",\n \"js-xxhash\": \"^4.0.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.0\",\n \"nanoid\": \"^5.1.2\",\n \"oxfmt\": \"^0.45.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.5.4\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.18.1\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"@vitest/runner\": \"^4.1.6\",\n \"analyze-query\": \"workspace:*\",\n \"ast-to-zql\": \"workspace:*\",\n \"expo-sqlite\": \">=15\",\n \"oxc-parser\": \"^0.129.0\",\n \"replicache\": \"workspace:*\",\n \"shared\": \"workspace:*\",\n \"syncpack\": \"^14.3.0\",\n \"typedoc\": \"^0.28.17\",\n \"typedoc-plugin-markdown\": \"^4.10.0\",\n \"typescript\": \"~6.0.2\",\n \"vite\": \"^8.0.13\",\n \"vitest\": \"^4.1.6\",\n \"zero-cache\": \"workspace:*\",\n \"zero-client\": \"workspace:*\",\n \"zero-pg\": \"workspace:*\",\n \"zero-react\": \"workspace:*\",\n \"zero-server\": \"workspace:*\",\n \"zero-solid\": \"workspace:*\",\n \"zqlite\": \"workspace:*\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"packageManager\": \"pnpm@11.5.3\"\n}\n"],"mappings":""}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.9.0-canary.1\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"analyze-query\": \"./out/zero/src/analyze-query.js\",\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/kysely\": {\n \"types\": \"./out/zero/src/adapters/kysely.d.ts\",\n \"default\": \"./out/zero/src/adapters/kysely.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --quiet --config ../../oxlint.config.ts src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.3.11\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.39.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.0.0\",\n \"@fastify/websocket\": \"^11.0.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"^0.218.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"^0.76.0\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"^0.218.0\",\n \"@opentelemetry/resources\": \"^2.7.1\",\n \"@opentelemetry/sdk-metrics\": \"^2.7.1\",\n \"@opentelemetry/sdk-node\": \"^0.218.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.7.1\",\n \"@opentelemetry/semantic-conventions\": \"^1.41.1\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^1.0.4\",\n \"@rocicorp/logger\": \"^6.1.0\",\n \"@rocicorp/resolver\": \"^1.0.2\",\n \"@rocicorp/zero-sqlite3\": \"^1.1.2\",\n \"@standard-schema/spec\": \"^1.0.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.5.12\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.0\",\n \"chokidar\": \"^4.0.1\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.1\",\n \"command-line-usage\": \"^7.0.3\",\n \"compare-utf8\": \"^0.2.0\",\n \"defu\": \"^6.1.4\",\n \"eventemitter3\": \"^5.0.1\",\n \"fastify\": \"^5.0.0\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.9.3\",\n \"js-xxhash\": \"^4.0.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.0\",\n \"nanoid\": \"^5.1.2\",\n \"oxfmt\": \"^0.45.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.5.4\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.18.1\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"@vitest/runner\": \"^4.1.6\",\n \"analyze-query\": \"workspace:*\",\n \"ast-to-zql\": \"workspace:*\",\n \"expo-sqlite\": \">=15\",\n \"oxc-parser\": \"^0.129.0\",\n \"replicache\": \"workspace:*\",\n \"shared\": \"workspace:*\",\n \"syncpack\": \"^14.3.0\",\n \"typedoc\": \"^0.28.17\",\n \"typedoc-plugin-markdown\": \"^4.10.0\",\n \"typescript\": \"~6.0.2\",\n \"vite\": \"^8.0.13\",\n \"vitest\": \"^4.1.6\",\n \"zero-cache\": \"workspace:*\",\n \"zero-client\": \"workspace:*\",\n \"zero-pg\": \"workspace:*\",\n \"zero-react\": \"workspace:*\",\n \"zero-server\": \"workspace:*\",\n \"zero-solid\": \"workspace:*\",\n \"zqlite\": \"workspace:*\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"packageManager\": \"pnpm@11.5.3\"\n}\n"],"mappings":""}
@@ -115,7 +115,7 @@ async function fetchFromAPIServer(validator, source, lc, ctx, shard, body, metri
115
115
  status: response.status,
116
116
  bodyPreview
117
117
  });
118
- const willRetry = (response.status === 502 || response.status === 504) && attempt < MAX_ATTEMPTS;
118
+ const willRetry = response.status >= 500 && response.status < 600 && attempt < MAX_ATTEMPTS;
119
119
  recordApiAttempt(performance.now() - attemptStart, metricAttrs, {
120
120
  attempt,
121
121
  result: "http_error",
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","names":[],"sources":["../../../../../zero-cache/src/custom/fetch.ts"],"sourcesContent":["import {context, propagation} from '@opentelemetry/api';\nimport type {LogContext, LogLevel} from '@rocicorp/logger';\nimport 'urlpattern-polyfill';\nimport {unreachable} from '../../../shared/src/asserts.ts';\nimport {getErrorMessage} from '../../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport {type Type} from '../../../shared/src/valita.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {\n errorBodySchema,\n isProtocolError,\n type ErrorBody,\n} from '../../../zero-protocol/src/error.ts';\nimport {\n pushErrorSchema,\n type PushError,\n} from '../../../zero-protocol/src/push.ts';\nimport type {ConnectionContext} from '../services/view-syncer/connection-context-manager.ts';\nimport {ProtocolErrorWithLevel} from '../types/error-with-level.ts';\nimport {upstreamSchema, type ShardID} from '../types/shards.ts';\nimport {\n apiAttemptDuration,\n apiAttempts,\n apiInFlight,\n apiRequestDuration,\n apiRequests,\n type ApiAttemptMetricAttrs,\n type ApiAttemptResult,\n type ApiCleanupType,\n type ApiMetricBaseAttrs,\n type ApiOperation,\n type ApiRequestMetricAttrs,\n type ApiRequestResult,\n} from './metrics.ts';\n\nconst reservedParams = ['schema', 'appID'];\n\n/**\n * Compiles and validates a URLPattern from configuration.\n *\n * Patterns must be full URLs (e.g., \"https://api.example.com/endpoint\").\n * URLPattern automatically sets search and hash to wildcard ('*'),\n * which means query parameters and fragments are ignored during matching.\n *\n * @throws Error if the pattern is an invalid URLPattern\n */\nexport function compileUrlPattern(pattern: string): URLPattern {\n try {\n return new URLPattern(pattern);\n } catch (e) {\n throw new Error(\n `Invalid URLPattern in URL configuration: \"${pattern}\". Error: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\nexport const getBodyPreview = async (\n res: Response,\n lc: LogContext,\n): Promise<string | undefined> => {\n try {\n const body = await res.clone().text();\n if (body.length > 512) {\n return body.slice(0, 512) + '...';\n }\n return body;\n } catch (e) {\n lc.warn?.(\n 'failed to get body preview',\n {\n url: res.url,\n },\n e,\n );\n }\n\n return undefined;\n};\n\nconst MAX_ATTEMPTS = 4;\n\ntype ApiFailedReason =\n | typeof ErrorReason.HTTP\n | typeof ErrorReason.Parse\n | typeof ErrorReason.Internal;\n\nexport type FetchMetricsOptions = {\n operation: ApiOperation;\n cleanupType?: ApiCleanupType | undefined;\n};\n\nexport async function fetchFromAPIServer<TValidator extends Type>(\n validator: TValidator,\n source: 'push' | 'transform',\n lc: LogContext,\n ctx: ConnectionContext,\n shard: ShardID,\n body: ReadonlyJSONValue,\n metricsOpts: FetchMetricsOptions,\n) {\n const metricAttrs: ApiMetricBaseAttrs =\n metricsOpts.operation === 'cleanup' && metricsOpts.cleanupType !== undefined\n ? {\n operation: metricsOpts.operation,\n cleanup_type: metricsOpts.cleanupType,\n }\n : {operation: metricsOpts.operation};\n const requestStart = performance.now();\n let requestMetricAttrs: ApiRequestMetricAttrs | undefined;\n let attemptCount = 0;\n apiInFlight().add(1, metricAttrs);\n\n try {\n const fetchFromAPIServerID = randInt(1, Number.MAX_SAFE_INTEGER).toString(\n 36,\n );\n lc = lc\n .withContext('fetchFromAPIServerID', fetchFromAPIServerID)\n .withContext('source', source);\n\n const fetchConfig =\n source === 'push' ? ctx.mutateContext : ctx.queryContext;\n const url = must(\n fetchConfig.url,\n `Fetch config for ${source} is missing URL`,\n );\n const headerOptions = fetchConfig.headerOptions;\n\n lc.debug?.('fetchFromAPIServer called', {\n url,\n });\n\n if (!urlMatch(url, fetchConfig.allowedUrlPatterns ?? [])) {\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Internal,\n source === 'push'\n ? `URL \"${url}\" is not allowed by the ZERO_MUTATE_URL configuration`\n : `URL \"${url}\" is not allowed by the ZERO_QUERY_URL configuration`,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'url_not_allowed',\n attemptCount,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn');\n }\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (headerOptions.apiKey) {\n headers['X-Api-Key'] = headerOptions.apiKey;\n }\n Object.assign(\n headers,\n headerOptions.customHeaders,\n headerOptions.requestHeaders,\n );\n if (ctx.auth?.raw) {\n headers['Authorization'] = `Bearer ${ctx.auth.raw}`;\n }\n if (headerOptions.cookie) {\n headers['Cookie'] = headerOptions.cookie;\n }\n if (headerOptions.origin) {\n headers['Origin'] = headerOptions.origin;\n }\n propagation.inject(context.active(), headers);\n\n const urlObj = new URL(url);\n const params = new URLSearchParams(urlObj.search);\n\n for (const reserved of reservedParams) {\n if (params.has(reserved)) {\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'config_error',\n attemptCount,\n });\n throw new Error(\n `The push URL cannot contain the reserved query param \"${reserved}\"`,\n );\n }\n }\n\n params.append('schema', upstreamSchema(shard));\n params.append('appID', shard.appID);\n\n urlObj.search = params.toString();\n\n const finalUrl = urlObj.toString();\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n attemptCount = attempt;\n lc = lc.withContext('fetchFromAPIServerAttempt', attempt);\n lc.debug?.('fetch from API server attempt');\n const sleepBeforeRetry = async () => {\n if (attempt < MAX_ATTEMPTS) {\n const delayMs = getBackoffDelayMs(attempt);\n lc.debug?.(`fetch from API server retrying in ${delayMs} ms`);\n await sleep(delayMs);\n return true;\n }\n lc.debug?.('fetch from API server reached max attempts, not retrying');\n return false;\n };\n const attemptStart = performance.now();\n try {\n const response = await fetch(finalUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const bodyPreview = await getBodyPreview(response, lc);\n lc.warn?.('fetch from API server returned non-OK status', {\n url: finalUrl,\n status: response.status,\n bodyPreview,\n });\n // Bad Gateway or Gateway Timeout indicate the server was not reached\n // We retry these if we have retries remaining.\n const willRetry =\n (response.status === 502 || response.status === 504) &&\n attempt < MAX_ATTEMPTS;\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'http_error',\n willRetry,\n response,\n });\n if (willRetry && (await sleepBeforeRetry())) {\n continue;\n }\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.HTTP,\n `Fetch from API server returned non-OK status ${response.status}`,\n response,\n bodyPreview,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'http_error',\n attemptCount,\n response,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn');\n }\n\n try {\n const json = await response.json();\n const result = validator.parse(json, {\n mode: 'passthrough',\n });\n const apiError = apiErrorFromResult(result);\n if (apiError) {\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'api_error',\n willRetry: false,\n response,\n errorBody: apiError,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'api_error',\n attemptCount,\n response,\n errorBody: apiError,\n });\n } else {\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'success',\n willRetry: false,\n response,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'success',\n attemptCount,\n response,\n });\n }\n lc.debug?.('fetch from API server succeeded');\n return result;\n } catch (error) {\n lc.warn?.(\n 'failed to parse response',\n {\n url: finalUrl,\n },\n error,\n );\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Parse,\n `Failed to parse response from API server: ${getErrorMessage(error)}`,\n );\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'parse_error',\n willRetry: false,\n response,\n errorBody,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'parse_error',\n attemptCount,\n response,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn', {cause: error});\n }\n } catch (error) {\n if (isProtocolError(error)) {\n throw error;\n }\n\n const isFetchFailed =\n error instanceof TypeError && error.message === 'fetch failed';\n // unexpected/unknown errors should be logged at 'error' level so they\n // are investigated\n let logLevel: LogLevel = isFetchFailed ? 'warn' : 'error';\n lc[logLevel]?.(\n 'fetch from API server threw error',\n {url: finalUrl},\n error,\n );\n\n const willRetry = isFetchFailed && attempt < MAX_ATTEMPTS;\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'fetch_error',\n willRetry,\n });\n\n if (willRetry && (await sleepBeforeRetry())) {\n continue;\n }\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Internal,\n `Fetch from API server threw error: ${getErrorMessage(error)}`,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'fetch_error',\n attemptCount,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, logLevel, {cause: error});\n }\n }\n unreachable();\n } finally {\n const attrs =\n requestMetricAttrs ??\n apiRequestMetricAttrs(metricAttrs, {\n result: attemptCount === 0 ? 'config_error' : 'fetch_error',\n attemptCount,\n });\n apiRequests().add(1, attrs);\n apiRequestDuration().recordMs(performance.now() - requestStart, attrs);\n apiInFlight().add(-1, metricAttrs);\n }\n}\n\n/**\n * Returns true if the url matches one of the allowedUrlPatterns.\n *\n * URLPattern automatically ignores query parameters and hash fragments during matching\n * because it sets search and hash to wildcard ('*') by default.\n *\n * Example URLPattern patterns:\n * - \"https://api.example.com/endpoint\" - Exact match for a specific URL\n * - \"https://*.example.com/endpoint\" - Matches any single subdomain (e.g., \"https://api.example.com/endpoint\")\n * - \"https://*.*.example.com/endpoint\" - Matches two subdomains (e.g., \"https://api.v1.example.com/endpoint\")\n * - \"https://api.example.com/*\" - Matches any path under /\n * - \"https://api.example.com/:version/endpoint\" - Matches with named parameter (e.g., \"https://api.example.com/v1/endpoint\")\n */\nexport function urlMatch(\n url: string,\n allowedUrlPatterns: readonly URLPattern[],\n): boolean {\n for (const pattern of allowedUrlPatterns) {\n if (pattern.test(url)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns the delay in milliseconds for the next retry attempt using exponential backoff with jitter.\n *\n * The delay assumes the first retry is attempt 1.\n * The formula is: `min(1000, 100 * 2^(attempt - 1) + jitter)` where jitter is between 0 and 100ms.\n */\nfunction getBackoffDelayMs(attempt: number): number {\n return Math.min(1000, 100 * Math.pow(2, attempt - 1) + Math.random() * 100);\n}\n\nfunction apiFailedBody(\n source: 'push' | 'transform',\n reason: ApiFailedReason,\n message: string,\n response?: Response | undefined,\n bodyPreview?: string | undefined,\n): ErrorBody {\n if (source === 'push') {\n return reason === ErrorReason.HTTP\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n status: response?.status ?? 0,\n ...(bodyPreview !== undefined ? {bodyPreview} : {}),\n message,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n message,\n mutationIDs: [],\n };\n }\n\n return reason === ErrorReason.HTTP\n ? {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n status: response?.status ?? 0,\n ...(bodyPreview !== undefined ? {bodyPreview} : {}),\n message,\n queryIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n message,\n queryIDs: [],\n };\n}\n\ntype ApiErrorMetricBody = {\n kind: ErrorBody['kind'];\n reason?: string | undefined;\n};\n\nfunction apiErrorFromResult(result: unknown): ApiErrorMetricBody | undefined {\n const parsed = errorBodySchema.try(result, {mode: 'passthrough'});\n if (parsed.ok) {\n return parsed.value;\n }\n\n if (Array.isArray(result) && result[0] === 'transformFailed') {\n const legacyTransformFailed = errorBodySchema.try(result[1], {\n mode: 'passthrough',\n });\n return legacyTransformFailed.ok ? legacyTransformFailed.value : undefined;\n }\n\n const legacyPushError = pushErrorSchema.try(result, {mode: 'passthrough'});\n return legacyPushError.ok\n ? {\n kind: ErrorKind.PushFailed,\n reason: legacyPushErrorReason(legacyPushError.value.error),\n }\n : undefined;\n}\n\nfunction legacyPushErrorReason(error: PushError['error']): string {\n switch (error) {\n case 'http':\n return ErrorReason.HTTP;\n case 'unsupportedPushVersion':\n return ErrorReason.UnsupportedPushVersion;\n case 'unsupportedSchemaVersion':\n case 'zeroPusher':\n return ErrorReason.Internal;\n }\n}\n\ntype ApiResponseErrorMetricAttrs = Pick<\n ApiRequestMetricAttrs,\n 'http_status_code' | 'http_status_class' | 'error_kind' | 'error_reason'\n>;\n\ntype ApiRequestMetricAttrsOptions = {\n result: ApiRequestResult;\n attemptCount: number;\n response?: Response | undefined;\n errorBody?: ApiErrorMetricBody | undefined;\n};\n\ntype ApiAttemptMetricAttrsOptions = {\n attempt: number;\n result: ApiAttemptResult;\n willRetry: boolean;\n response?: Response | undefined;\n errorBody?: ApiErrorMetricBody | undefined;\n};\n\nfunction apiRequestMetricAttrs(\n baseAttrs: ApiMetricBaseAttrs,\n {result, attemptCount, response, errorBody}: ApiRequestMetricAttrsOptions,\n): ApiRequestMetricAttrs {\n return {\n ...baseAttrs,\n result,\n attempt_count: attemptCount,\n ...apiResponseErrorMetricAttrs(response, errorBody),\n };\n}\n\nfunction apiResponseErrorMetricAttrs(\n response: Response | undefined,\n errorBody: ApiErrorMetricBody | undefined,\n): ApiResponseErrorMetricAttrs {\n const attrs: ApiResponseErrorMetricAttrs = {};\n\n if (response) {\n attrs.http_status_code = response.status;\n attrs.http_status_class = `${Math.floor(response.status / 100)}xx`;\n }\n\n if (errorBody) {\n attrs.error_kind = errorBody.kind;\n if (errorBody.reason !== undefined) {\n attrs.error_reason = errorBody.reason;\n }\n }\n\n return attrs;\n}\n\nfunction recordApiAttempt(\n durationMs: number,\n baseAttrs: ApiMetricBaseAttrs,\n {\n attempt,\n result,\n willRetry,\n response,\n errorBody,\n }: ApiAttemptMetricAttrsOptions,\n) {\n const attrs: ApiAttemptMetricAttrs = {\n ...baseAttrs,\n attempt,\n result,\n will_retry: willRetry,\n ...apiResponseErrorMetricAttrs(response, errorBody),\n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OAAO;EACT,KAAK;EACL,KAAK,cACH,OAAO;CACX;AACF;AAsBA,SAAS,sBACP,WACA,EAAC,QAAQ,cAAc,UAAU,aACV;CACvB,OAAO;EACL,GAAG;EACH;EACA,eAAe;EACf,GAAG,4BAA4B,UAAU,SAAS;CACpD;AACF;AAEA,SAAS,4BACP,UACA,WAC6B;CAC7B,MAAM,QAAqC,CAAC;CAE5C,IAAI,UAAU;EACZ,MAAM,mBAAmB,SAAS;EAClC,MAAM,oBAAoB,GAAG,KAAK,MAAM,SAAS,SAAS,GAAG,EAAE;CACjE;CAEA,IAAI,WAAW;EACb,MAAM,aAAa,UAAU;EAC7B,IAAI,UAAU,WAAW,KAAA,GACvB,MAAM,eAAe,UAAU;CAEnC;CAEA,OAAO;AACT;AAEA,SAAS,iBACP,YACA,WACA,EACE,SACA,QACA,WACA,UACA,aAEF;CACA,MAAM,QAA+B;EACnC,GAAG;EACH;EACA;EACA,YAAY;EACZ,GAAG,4BAA4B,UAAU,SAAS;CACpD;CACA,YAAY,EAAE,IAAI,GAAG,KAAK;CAC1B,mBAAmB,EAAE,SAAS,YAAY,KAAK;AACjD"}
1
+ {"version":3,"file":"fetch.js","names":[],"sources":["../../../../../zero-cache/src/custom/fetch.ts"],"sourcesContent":["import {context, propagation} from '@opentelemetry/api';\nimport type {LogContext, LogLevel} from '@rocicorp/logger';\nimport 'urlpattern-polyfill';\nimport {unreachable} from '../../../shared/src/asserts.ts';\nimport {getErrorMessage} from '../../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {randInt} from '../../../shared/src/rand.ts';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport {type Type} from '../../../shared/src/valita.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {\n errorBodySchema,\n isProtocolError,\n type ErrorBody,\n} from '../../../zero-protocol/src/error.ts';\nimport {\n pushErrorSchema,\n type PushError,\n} from '../../../zero-protocol/src/push.ts';\nimport type {ConnectionContext} from '../services/view-syncer/connection-context-manager.ts';\nimport {ProtocolErrorWithLevel} from '../types/error-with-level.ts';\nimport {upstreamSchema, type ShardID} from '../types/shards.ts';\nimport {\n apiAttemptDuration,\n apiAttempts,\n apiInFlight,\n apiRequestDuration,\n apiRequests,\n type ApiAttemptMetricAttrs,\n type ApiAttemptResult,\n type ApiCleanupType,\n type ApiMetricBaseAttrs,\n type ApiOperation,\n type ApiRequestMetricAttrs,\n type ApiRequestResult,\n} from './metrics.ts';\n\nconst reservedParams = ['schema', 'appID'];\n\n/**\n * Compiles and validates a URLPattern from configuration.\n *\n * Patterns must be full URLs (e.g., \"https://api.example.com/endpoint\").\n * URLPattern automatically sets search and hash to wildcard ('*'),\n * which means query parameters and fragments are ignored during matching.\n *\n * @throws Error if the pattern is an invalid URLPattern\n */\nexport function compileUrlPattern(pattern: string): URLPattern {\n try {\n return new URLPattern(pattern);\n } catch (e) {\n throw new Error(\n `Invalid URLPattern in URL configuration: \"${pattern}\". Error: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\nexport const getBodyPreview = async (\n res: Response,\n lc: LogContext,\n): Promise<string | undefined> => {\n try {\n const body = await res.clone().text();\n if (body.length > 512) {\n return body.slice(0, 512) + '...';\n }\n return body;\n } catch (e) {\n lc.warn?.(\n 'failed to get body preview',\n {\n url: res.url,\n },\n e,\n );\n }\n\n return undefined;\n};\n\nconst MAX_ATTEMPTS = 4;\n\ntype ApiFailedReason =\n | typeof ErrorReason.HTTP\n | typeof ErrorReason.Parse\n | typeof ErrorReason.Internal;\n\nexport type FetchMetricsOptions = {\n operation: ApiOperation;\n cleanupType?: ApiCleanupType | undefined;\n};\n\nexport async function fetchFromAPIServer<TValidator extends Type>(\n validator: TValidator,\n source: 'push' | 'transform',\n lc: LogContext,\n ctx: ConnectionContext,\n shard: ShardID,\n body: ReadonlyJSONValue,\n metricsOpts: FetchMetricsOptions,\n) {\n const metricAttrs: ApiMetricBaseAttrs =\n metricsOpts.operation === 'cleanup' && metricsOpts.cleanupType !== undefined\n ? {\n operation: metricsOpts.operation,\n cleanup_type: metricsOpts.cleanupType,\n }\n : {operation: metricsOpts.operation};\n const requestStart = performance.now();\n let requestMetricAttrs: ApiRequestMetricAttrs | undefined;\n let attemptCount = 0;\n apiInFlight().add(1, metricAttrs);\n\n try {\n const fetchFromAPIServerID = randInt(1, Number.MAX_SAFE_INTEGER).toString(\n 36,\n );\n lc = lc\n .withContext('fetchFromAPIServerID', fetchFromAPIServerID)\n .withContext('source', source);\n\n const fetchConfig =\n source === 'push' ? ctx.mutateContext : ctx.queryContext;\n const url = must(\n fetchConfig.url,\n `Fetch config for ${source} is missing URL`,\n );\n const headerOptions = fetchConfig.headerOptions;\n\n lc.debug?.('fetchFromAPIServer called', {\n url,\n });\n\n if (!urlMatch(url, fetchConfig.allowedUrlPatterns ?? [])) {\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Internal,\n source === 'push'\n ? `URL \"${url}\" is not allowed by the ZERO_MUTATE_URL configuration`\n : `URL \"${url}\" is not allowed by the ZERO_QUERY_URL configuration`,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'url_not_allowed',\n attemptCount,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn');\n }\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (headerOptions.apiKey) {\n headers['X-Api-Key'] = headerOptions.apiKey;\n }\n Object.assign(\n headers,\n headerOptions.customHeaders,\n headerOptions.requestHeaders,\n );\n if (ctx.auth?.raw) {\n headers['Authorization'] = `Bearer ${ctx.auth.raw}`;\n }\n if (headerOptions.cookie) {\n headers['Cookie'] = headerOptions.cookie;\n }\n if (headerOptions.origin) {\n headers['Origin'] = headerOptions.origin;\n }\n propagation.inject(context.active(), headers);\n\n const urlObj = new URL(url);\n const params = new URLSearchParams(urlObj.search);\n\n for (const reserved of reservedParams) {\n if (params.has(reserved)) {\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'config_error',\n attemptCount,\n });\n throw new Error(\n `The push URL cannot contain the reserved query param \"${reserved}\"`,\n );\n }\n }\n\n params.append('schema', upstreamSchema(shard));\n params.append('appID', shard.appID);\n\n urlObj.search = params.toString();\n\n const finalUrl = urlObj.toString();\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n attemptCount = attempt;\n lc = lc.withContext('fetchFromAPIServerAttempt', attempt);\n lc.debug?.('fetch from API server attempt');\n const sleepBeforeRetry = async () => {\n if (attempt < MAX_ATTEMPTS) {\n const delayMs = getBackoffDelayMs(attempt);\n lc.debug?.(`fetch from API server retrying in ${delayMs} ms`);\n await sleep(delayMs);\n return true;\n }\n lc.debug?.('fetch from API server reached max attempts, not retrying');\n return false;\n };\n const attemptStart = performance.now();\n try {\n const response = await fetch(finalUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const bodyPreview = await getBodyPreview(response, lc);\n lc.warn?.('fetch from API server returned non-OK status', {\n url: finalUrl,\n status: response.status,\n bodyPreview,\n });\n // Server errors can be transient, so retry if attempts remain.\n const willRetry =\n response.status >= 500 &&\n response.status < 600 &&\n attempt < MAX_ATTEMPTS;\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'http_error',\n willRetry,\n response,\n });\n if (willRetry && (await sleepBeforeRetry())) {\n continue;\n }\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.HTTP,\n `Fetch from API server returned non-OK status ${response.status}`,\n response,\n bodyPreview,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'http_error',\n attemptCount,\n response,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn');\n }\n\n try {\n const json = await response.json();\n const result = validator.parse(json, {\n mode: 'passthrough',\n });\n const apiError = apiErrorFromResult(result);\n if (apiError) {\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'api_error',\n willRetry: false,\n response,\n errorBody: apiError,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'api_error',\n attemptCount,\n response,\n errorBody: apiError,\n });\n } else {\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'success',\n willRetry: false,\n response,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'success',\n attemptCount,\n response,\n });\n }\n lc.debug?.('fetch from API server succeeded');\n return result;\n } catch (error) {\n lc.warn?.(\n 'failed to parse response',\n {\n url: finalUrl,\n },\n error,\n );\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Parse,\n `Failed to parse response from API server: ${getErrorMessage(error)}`,\n );\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'parse_error',\n willRetry: false,\n response,\n errorBody,\n });\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'parse_error',\n attemptCount,\n response,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, 'warn', {cause: error});\n }\n } catch (error) {\n if (isProtocolError(error)) {\n throw error;\n }\n\n const isFetchFailed =\n error instanceof TypeError && error.message === 'fetch failed';\n // unexpected/unknown errors should be logged at 'error' level so they\n // are investigated\n let logLevel: LogLevel = isFetchFailed ? 'warn' : 'error';\n lc[logLevel]?.(\n 'fetch from API server threw error',\n {url: finalUrl},\n error,\n );\n\n const willRetry = isFetchFailed && attempt < MAX_ATTEMPTS;\n recordApiAttempt(performance.now() - attemptStart, metricAttrs, {\n attempt,\n result: 'fetch_error',\n willRetry,\n });\n\n if (willRetry && (await sleepBeforeRetry())) {\n continue;\n }\n\n const errorBody = apiFailedBody(\n source,\n ErrorReason.Internal,\n `Fetch from API server threw error: ${getErrorMessage(error)}`,\n );\n requestMetricAttrs = apiRequestMetricAttrs(metricAttrs, {\n result: 'fetch_error',\n attemptCount,\n errorBody,\n });\n throw new ProtocolErrorWithLevel(errorBody, logLevel, {cause: error});\n }\n }\n unreachable();\n } finally {\n const attrs =\n requestMetricAttrs ??\n apiRequestMetricAttrs(metricAttrs, {\n result: attemptCount === 0 ? 'config_error' : 'fetch_error',\n attemptCount,\n });\n apiRequests().add(1, attrs);\n apiRequestDuration().recordMs(performance.now() - requestStart, attrs);\n apiInFlight().add(-1, metricAttrs);\n }\n}\n\n/**\n * Returns true if the url matches one of the allowedUrlPatterns.\n *\n * URLPattern automatically ignores query parameters and hash fragments during matching\n * because it sets search and hash to wildcard ('*') by default.\n *\n * Example URLPattern patterns:\n * - \"https://api.example.com/endpoint\" - Exact match for a specific URL\n * - \"https://*.example.com/endpoint\" - Matches any single subdomain (e.g., \"https://api.example.com/endpoint\")\n * - \"https://*.*.example.com/endpoint\" - Matches two subdomains (e.g., \"https://api.v1.example.com/endpoint\")\n * - \"https://api.example.com/*\" - Matches any path under /\n * - \"https://api.example.com/:version/endpoint\" - Matches with named parameter (e.g., \"https://api.example.com/v1/endpoint\")\n */\nexport function urlMatch(\n url: string,\n allowedUrlPatterns: readonly URLPattern[],\n): boolean {\n for (const pattern of allowedUrlPatterns) {\n if (pattern.test(url)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns the delay in milliseconds for the next retry attempt using exponential backoff with jitter.\n *\n * The delay assumes the first retry is attempt 1.\n * The formula is: `min(1000, 100 * 2^(attempt - 1) + jitter)` where jitter is between 0 and 100ms.\n */\nfunction getBackoffDelayMs(attempt: number): number {\n return Math.min(1000, 100 * Math.pow(2, attempt - 1) + Math.random() * 100);\n}\n\nfunction apiFailedBody(\n source: 'push' | 'transform',\n reason: ApiFailedReason,\n message: string,\n response?: Response | undefined,\n bodyPreview?: string | undefined,\n): ErrorBody {\n if (source === 'push') {\n return reason === ErrorReason.HTTP\n ? {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n status: response?.status ?? 0,\n ...(bodyPreview !== undefined ? {bodyPreview} : {}),\n message,\n mutationIDs: [],\n }\n : {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n message,\n mutationIDs: [],\n };\n }\n\n return reason === ErrorReason.HTTP\n ? {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n status: response?.status ?? 0,\n ...(bodyPreview !== undefined ? {bodyPreview} : {}),\n message,\n queryIDs: [],\n }\n : {\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason,\n message,\n queryIDs: [],\n };\n}\n\ntype ApiErrorMetricBody = {\n kind: ErrorBody['kind'];\n reason?: string | undefined;\n};\n\nfunction apiErrorFromResult(result: unknown): ApiErrorMetricBody | undefined {\n const parsed = errorBodySchema.try(result, {mode: 'passthrough'});\n if (parsed.ok) {\n return parsed.value;\n }\n\n if (Array.isArray(result) && result[0] === 'transformFailed') {\n const legacyTransformFailed = errorBodySchema.try(result[1], {\n mode: 'passthrough',\n });\n return legacyTransformFailed.ok ? legacyTransformFailed.value : undefined;\n }\n\n const legacyPushError = pushErrorSchema.try(result, {mode: 'passthrough'});\n return legacyPushError.ok\n ? {\n kind: ErrorKind.PushFailed,\n reason: legacyPushErrorReason(legacyPushError.value.error),\n }\n : undefined;\n}\n\nfunction legacyPushErrorReason(error: PushError['error']): string {\n switch (error) {\n case 'http':\n return ErrorReason.HTTP;\n case 'unsupportedPushVersion':\n return ErrorReason.UnsupportedPushVersion;\n case 'unsupportedSchemaVersion':\n case 'zeroPusher':\n return ErrorReason.Internal;\n }\n}\n\ntype ApiResponseErrorMetricAttrs = Pick<\n ApiRequestMetricAttrs,\n 'http_status_code' | 'http_status_class' | 'error_kind' | 'error_reason'\n>;\n\ntype ApiRequestMetricAttrsOptions = {\n result: ApiRequestResult;\n attemptCount: number;\n response?: Response | undefined;\n errorBody?: ApiErrorMetricBody | undefined;\n};\n\ntype ApiAttemptMetricAttrsOptions = {\n attempt: number;\n result: ApiAttemptResult;\n willRetry: boolean;\n response?: Response | undefined;\n errorBody?: ApiErrorMetricBody | undefined;\n};\n\nfunction apiRequestMetricAttrs(\n baseAttrs: ApiMetricBaseAttrs,\n {result, attemptCount, response, errorBody}: ApiRequestMetricAttrsOptions,\n): ApiRequestMetricAttrs {\n return {\n ...baseAttrs,\n result,\n attempt_count: attemptCount,\n ...apiResponseErrorMetricAttrs(response, errorBody),\n };\n}\n\nfunction apiResponseErrorMetricAttrs(\n response: Response | undefined,\n errorBody: ApiErrorMetricBody | undefined,\n): ApiResponseErrorMetricAttrs {\n const attrs: ApiResponseErrorMetricAttrs = {};\n\n if (response) {\n attrs.http_status_code = response.status;\n attrs.http_status_class = `${Math.floor(response.status / 100)}xx`;\n }\n\n if (errorBody) {\n attrs.error_kind = errorBody.kind;\n if (errorBody.reason !== undefined) {\n attrs.error_reason = errorBody.reason;\n }\n }\n\n return attrs;\n}\n\nfunction recordApiAttempt(\n durationMs: number,\n baseAttrs: ApiMetricBaseAttrs,\n {\n attempt,\n result,\n willRetry,\n response,\n errorBody,\n }: ApiAttemptMetricAttrsOptions,\n) {\n const attrs: ApiAttemptMetricAttrs = {\n ...baseAttrs,\n attempt,\n result,\n will_retry: willRetry,\n ...apiResponseErrorMetricAttrs(response, errorBody),\n };\n apiAttempts().add(1, attrs);\n apiAttemptDuration().recordMs(durationMs, attrs);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,IAAM,iBAAiB,CAAC,UAAU,OAAO;;;;;;;;;;AAWzC,SAAgB,kBAAkB,SAA6B;CAC7D,IAAI;EACF,OAAO,IAAI,WAAW,OAAO;CAC/B,SAAS,GAAG;EACV,MAAM,IAAI,MACR,6CAA6C,QAAQ,YAAY,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAC5G;CACF;AACF;AAEA,IAAa,iBAAiB,OAC5B,KACA,OACgC;CAChC,IAAI;EACF,MAAM,OAAO,MAAM,IAAI,MAAM,EAAE,KA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AAA,GACvB,MAAM,eAAe,UAAU;CAEnC;CAEA,OAAO;AACT;AAEA,SAAS,iBACP,YACA,WACA,EACE,SACA,QACA,WACA,UACA,aAEF;CACA,MAAM,QAA+B;EACnC,GAAG;EACH;EACA;EACA,YAAY;EACZ,GAAG,4BAA4B,UAAU,SAAS;CACpD;CACA,YAAY,EAAE,IAAI,GAAG,KAAK;CAC1B,mBAAmB,EAAE,SAAS,YAAY,KAAK;AACjD"}
@@ -1 +1 @@
1
- {"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/litestream/commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,oBAAoB,CAAC;AAGrD,OAAO,KAAK,EAAC,UAAU,EAAW,MAAM,kBAAkB,CAAC;AAM3D,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,6BAA6B,CAAC;AAkC5D,KAAK,kBAAkB,GAAG;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC;AAUF,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,MAAM,CAAC,QAAQ,CAAC,IAAI,6BAA6B;gBAErC,SAAS,EAAE,MAAM,GAAG,SAAS;CAG1C;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,kBAAkB,EAAE,kBAAkB,GAAG,IAAI,iBAiF9C;AAmQD,wBAAgB,yBAAyB,CACvC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,GACjB,YAAY,CAuCd;AAQD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,IAAI,CAAC,CAgBf;AA6DD;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,EAAE,EAAE,UAAU,EACd,OAAO,EAAE,WAAW,GAAG,KAAK,EAC5B,MAAM,EAAE,MAAM,GACb,IAAI,EAAE,CAoBR"}
1
+ {"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/litestream/commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,oBAAoB,CAAC;AAGrD,OAAO,KAAK,EAAC,UAAU,EAAW,MAAM,kBAAkB,CAAC;AAM3D,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,6BAA6B,CAAC;AAkC5D,KAAK,kBAAkB,GAAG;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC;AAUF,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,MAAM,CAAC,QAAQ,CAAC,IAAI,6BAA6B;gBAErC,SAAS,EAAE,MAAM,GAAG,SAAS;CAG1C;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,kBAAkB,EAAE,kBAAkB,GAAG,IAAI,iBA+C9C;AAiPD,wBAAgB,yBAAyB,CACvC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,GACjB,YAAY,CAuCd;AAQD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,IAAI,CAAC,CAgBf;AA6DD;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,EAAE,EAAE,UAAU,EACd,OAAO,EAAE,WAAW,GAAG,KAAK,EAC5B,MAAM,EAAE,MAAM,GACb,IAAI,EAAE,CAoBR"}
@@ -31,28 +31,17 @@ async function restoreReplica(lc, config, replicaConstraints) {
31
31
  const role = replicaConstraints ? "replication_manager" : "view_syncer";
32
32
  let backupURL = config.litestream.backupURL;
33
33
  let result;
34
- let consecutiveErrors = 0;
35
34
  try {
36
35
  for (;;) {
37
- try {
38
- const attempt = await tryRestore(lc, config, replicaConstraints, role, consecutiveErrors >= 1);
39
- backupURL = attempt.backupURL;
40
- if (attempt.restored) {
41
- result = attempt.result;
42
- return;
43
- }
44
- consecutiveErrors = 0;
45
- if (replicaConstraints) {
46
- result = attempt.result;
47
- throw new BackupNotFoundException(config.litestream.backupURL);
48
- }
49
- } catch (e) {
50
- if (e instanceof BackupNotFoundException) throw e;
51
- if (++consecutiveErrors <= 1) {
52
- lc.warn?.(`restore attempt failed. retrying once`, e);
53
- continue;
54
- }
55
- throw e;
36
+ const attempt = await tryRestore(lc, config, replicaConstraints, role);
37
+ backupURL = attempt.backupURL;
38
+ if (attempt.restored) {
39
+ result = attempt.result;
40
+ return;
41
+ }
42
+ if (replicaConstraints) {
43
+ result = attempt.result;
44
+ throw new BackupNotFoundException(config.litestream.backupURL);
56
45
  }
57
46
  lc.info?.(`replica not found. retrying in ${RETRY_INTERVAL_MS / 1e3} seconds`);
58
47
  await sleep(RETRY_INTERVAL_MS);
@@ -71,7 +60,6 @@ async function restoreReplica(lc, config, replicaConstraints) {
71
60
  }
72
61
  function getLitestream(mode, config, logLevelOverride, backupURLOverride) {
73
62
  const { executable, executableV5, restoreUsingV5, backupURL, logLevel, configPath, endpoint, region, port = config.port + 2, checkpointThresholdMB, minCheckpointPageCount = checkpointThresholdMB * 250, maxCheckpointPageCount = minCheckpointPageCount * 10, incrementalBackupIntervalMinutes, snapshotBackupIntervalHours, multipartConcurrency, multipartSize } = config.litestream;
74
- const snapshotBackupIntervalMinutes = snapshotBackupIntervalHours * 60 - 5;
75
63
  return {
76
64
  litestream: (mode === "restore" && restoreUsingV5 ? executableV5 : executable) ?? must(executable, `Missing --litestream-executable`),
77
65
  env: {
@@ -82,7 +70,8 @@ function getLitestream(mode, config, logLevelOverride, backupURLOverride) {
82
70
  ["ZERO_LITESTREAM_MAX_CHECKPOINT_PAGE_COUNT"]: String(maxCheckpointPageCount),
83
71
  ["ZERO_LITESTREAM_INCREMENTAL_BACKUP_INTERVAL_MINUTES"]: String(incrementalBackupIntervalMinutes),
84
72
  ["ZERO_LITESTREAM_LOG_LEVEL"]: logLevelOverride ?? logLevel,
85
- ["ZERO_LITESTREAM_SNAPSHOT_BACKUP_INTERVAL_MINUTES"]: String(snapshotBackupIntervalMinutes),
73
+ ["ZERO_LITESTREAM_SNAPSHOT_BACKUP_INTERVAL_HOURS"]: String(snapshotBackupIntervalHours),
74
+ ["ZERO_LITESTREAM_SNAPSHOT_RETENTION_INTERVAL_HOURS"]: String(snapshotBackupIntervalHours + 6),
86
75
  ["ZERO_LITESTREAM_MULTIPART_CONCURRENCY"]: String(multipartConcurrency),
87
76
  ["ZERO_LITESTREAM_MULTIPART_SIZE"]: String(multipartSize),
88
77
  ["ZERO_LOG_FORMAT"]: config.log.format,
@@ -93,7 +82,7 @@ function getLitestream(mode, config, logLevelOverride, backupURLOverride) {
93
82
  }
94
83
  };
95
84
  }
96
- async function tryRestore(lc, config, replicaConstraints, role, isFinalAttempt) {
85
+ async function tryRestore(lc, config, replicaConstraints, role) {
97
86
  let snapshotStatus;
98
87
  if (!replicaConstraints) {
99
88
  const waitStart = performance.now();
@@ -157,9 +146,6 @@ async function tryRestore(lc, config, replicaConstraints, role, isFinalAttempt)
157
146
  ...attrs,
158
147
  result: "error"
159
148
  });
160
- const output = (stdout + stderr).trim();
161
- if (isFinalAttempt) lc.error?.(`litestream restore failed after retry`, output || e);
162
- else lc.error?.(`litestream restore attempt failed, will retry`, output || e);
163
149
  throw e;
164
150
  }
165
151
  if (!existsSync(config.replica.file)) {